diff --git a/.eslintrc.json b/.eslintrc.json index 705297c9a8..f53f8b7076 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -23,19 +23,20 @@ "globals": { "cc": false, "wx": false, - "CC_EDITOR": false, - "CC_DEV": false, - "CC_JSB": false, - "CC_PREVIEW": false, - "CC_DEBUG": false, "CC_BUILD": false, + "CC_TEST": false, + "CC_EDITOR": false, + "CC_PREVIEW": false, + "CC_DEV": false, + "CC_DEBUG": false, + "CC_JSB": false, + "CC_WECHATGAME_SUB": false, "CC_WECHATGAME": false, "CC_QQPLAY": false, "CC_RUNTIME": false, "CC_SUPPORT_JIT": false, - "CC_PREVIEW": false, - "CC_PREVIEW": false, - "CC_PREVIEW": false, + "Editor": false, + "_Scene": false, "_ccsg": false } } diff --git a/.gitignore b/.gitignore index ca53b140ee..d57d13d67d 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,8 @@ node_modules /package /tools/jsdoc_toolkit/jsdoc_toolkit-2.4.0 /.project +/dist npm-debug.log DebugInfos.json /rollup/out +/package-lock.json diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 6c0475d26c..ea43954e0f 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,7 +1,7 @@ ChangeLog: Cocos2d-x v3.8 @ September.6 2015 - + [NEW] spine: Supported Spine runtime 2.3 (Both native and web engine) [NEW] Animate: Added Animate's getCurrentFrameIndex function [NEW] network: Upgrade SocketIO support to v1.x @@ -58,9 +58,9 @@ Cocos2d-x v3.7.1 @ August.12 2015 Cocos2d-x v3.7 Final @ July 20 2015 [REFINE] web: Add compatible Uint16Array defintion - + [FIX] web: Fixed url check regular expression not supporting localhost issue - [FIX] web: Fixed issue that sprite doesn't update texture rect correctly + [FIX] web: Fixed issue that sprite doesn't update texture rect correctly Cocos2d-x v3.7 RC1 @ July 14 2015 [REFINE] Improved localStorage warning when disabled @@ -181,9 +181,9 @@ Cocos2d-JS v3.5 @ April 1 2015 * Replaced '==' with '===' for better performance. * Added `path` parameter in `ccs.load` to support modifying cocostudio project resource path. * Added animationList to Cocostudio ActionTimeline to support playing animation by name. -* Made ParticleSystem support creation from an map object. +* Made ParticleSystem support creation from an map object. * Added missing functions to `cc.Grid3D` and `cc.PageTurn3D`. -* Added tip message functions to `cc.TextFieldTTF` for mobile browser. +* Added tip message functions to `cc.TextFieldTTF` for mobile browser. * Added a function `cc.sys.openURL`. * Disabled retina display by default for better performance. * Added Bower support. @@ -192,15 +192,15 @@ Cocos2d-JS v3.5 @ April 1 2015 * Bug fixes: 1. Fixed a bug of chipmunk.js that it doesn't work under closure compiler advanced mode. 2. Fixed a bug of Cocos Studio parser that widget didn't set its layout component. - 3. Fixed grammatical mistakes in cocostudio parser logs. + 3. Fixed grammatical mistakes in cocostudio parser logs. 4. Fixed memory leak issue in `cc.LabelBMFont`. 5. Fixed a bug of `cc.Scale9Sprite` that its `updateDisplayColor` doesn't take effect. 6. Fixed a bug of Cocos Studio parser that `cc.Scale9Sprite` doesn't display correctly if its texture isn't preloaded. - 7. Fixed a bug of `cc.MenuItemSprite` that the construction will fail when parameter `selectedSprite` is a Scale9Sprite instance. + 7. Fixed a bug of `cc.MenuItemSprite` that the construction will fail when parameter `selectedSprite` is a Scale9Sprite instance. 8. Fixed a bug of Cocos Studio parser that the background color of `ccui.Layout` can't be parsed correctly. 9. Fixed a bug of `cc.ClippingNode` that it doesn't work when set `inverted` to true in Canvas Mode. 10. Fixed a bug of `ccs.Armature` that its name was modified to animation name when loading from json files. - 11. Fixed a bug of `ccui.PageView` that it cancel child touch during movment of page view. + 11. Fixed a bug of `ccui.PageView` that it cancel child touch during movment of page view. 12. Fixed a bug of `cc.Scheduler` that its parameter `repeat` is invalid in schedule function. 13. Fixed a bug of `cc.Scheduler` that `unschedule` function may fail. @@ -225,19 +225,19 @@ Cocos2d-JS v3.4 Beta0 @ March 19 2015 1. Added `getSpriteFrame` to `cc.Sprite` to fix API inconsistency. 2. Added `getObject` to `cc.TMXObjectGroup` to fix API inconsistency. 3. Added `addImageAsync` to `cc.textureCache` to fix API inconsistency. - 4. Fixed a bug of `cc.text` that its default font name is incorrect. + 4. Fixed a bug of `cc.text` that its default font name is incorrect. 5. Fixed a bug of `ccui.PageView` that its `getPage` doesn't work. 6. Fixed a bug of `ccui.ImageView` that its `loadTexture` doesn't work while it's invoked multiple times at the same frame. 7. Fixed a bug of `ccui` that its load event callbacks have some mistakes. 8. Fixed a bug of `cc.Layer` that its bake function doesn't work when the layer has a parent node. 9. Fixed typos in `cc.ClippingNode.WebGLRenderCmd` and `cc.ParticleSystem.WebGLRenderCmd` creation. - 10. Fixed a bug of `cc.Sprite` in `setTextureRect`. + 10. Fixed a bug of `cc.Sprite` in `setTextureRect`. 11. Fixed a bug of `cc.Screen`. 12. Fixed a bug of `cc.view` that it doesn't work on iOS 8.1.2. - 13. Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero. - 14. Fixed a bug in hack for particles performance on canvas. + 13. Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero. + 14. Fixed a bug in hack for particles performance on canvas. 15. Fixed a bug of `cc.audioEngine` that it doesn't work after minified/compiled. - 16. Fixed a bug in `CCBoot.js` that WebGL is not activated in web view of iOS 8. + 16. Fixed a bug in `CCBoot.js` that WebGL is not activated in web view of iOS 8. 17. Fixed a bug of `cc.CheckBox` that its position is incorrect when its texture isn't preloaded. 18. Fixed a bug of `cc.TMXLayer` that it stops to work after `setTileGID` called. 19. Fixed a bug of Cocos parser 2.x that it doesn't set widget's LayoutComponent. @@ -247,16 +247,16 @@ Cocos2d-JS v3.3 @ Feb.9, 2015 * Upgraded spine runtime to support the latest version and updated its test case. * Added an option "noCache" for debugging on browsers. -* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode. +* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode. * Added message to `ccs.load` when loading armature json file. * Improved particle system test case. * Bug fixes: - 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true. + 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true. 2. Fixed a bug of `cc.ClippingNode` when its stencil is `cc.Node` object in canvas mode. 3. Fixed a ccui bug that the position of widgets is incorrect after loaded v2.x json file with `ccs.load`. - 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work. - 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled. + 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work. + 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled. 6. Fixed a bug of `ccui.ScrollView` that its `dir` property is null when passing `DIR_NONE` as `direction` in `_endRecordSlidAction` function. Cocos2d-JS v3.3 RC0 @ Feb.1, 2015 @@ -309,7 +309,7 @@ Cocos2d-JS v3.3 Beta @ Jan.24, 2015 9. Fixed a bug of `cc.audioEngine` that its loading path is incorrect. 10. Fixed a bug of `ccui.Widget` that it can't touch when it's reused. 11. Fixed a bug of UI system that the `setNormalizedPosition` doesn't work. - 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`. + 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`. 13. Fixed release texture issue in canvas mode. 14. Fixed a bug of `ccs.actionManager` that its `getActionByName` doesn't work. 15. Fixed a bug of `cc.Sprite` that it can't draw without texture on WebGL mode. @@ -656,7 +656,7 @@ Cocos2d-html5-v3.0 alpha @ March.15, 2014 * Replace `replaceWithScene` and `runWithScene` with `runScene`. * move sys.xxx to cc.sys.xxx. * Refactor CCEGLView.js for better maintainability. -* Refactor CCScheduler.js for better maintainability. +* Refactor scheduler.js for better maintainability. * Remove arguments.callee which is forbidden in ECMAScript strict mode. * Refactor Array clean function for better performance. * Refactor some functions about array operation. diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 0726b09fc4..de7c7a4c46 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -276,7 +276,7 @@ warning: you CANNOT change update priority in scheduled function ### 1507 -CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f +scheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f ### 1508 diff --git a/cocos/2d/base-ui/CCWidgetManager.js b/cocos/2d/base-ui/widget-manager.ts similarity index 55% rename from cocos/2d/base-ui/CCWidgetManager.js rename to cocos/2d/base-ui/widget-manager.ts index 5bbf5785f8..7f3d37d7cc 100644 --- a/cocos/2d/base-ui/CCWidgetManager.js +++ b/cocos/2d/base-ui/widget-manager.ts @@ -2,7 +2,7 @@ Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - http://www.cocos.com + 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, @@ -23,41 +23,48 @@ 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; -var Event = require('../CCNode').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; -var TOP = 1 << 0; -var MID = 1 << 1; // vertical center -var BOT = 1 << 2; -var LEFT = 1 << 3; -var CENTER = 1 << 4; // horizontal center -var RIGHT = 1 << 5; -var HORIZONTAL = LEFT | CENTER | RIGHT; -var VERTICAL = TOP | MID | BOT; - -var AlignMode = cc.Enum({ - ONCE: 0, - ON_WINDOW_RESIZE: 1, - ALWAYS: 2, -}); - -// returns a readonly size of the node -function getReadonlyNodeSize (parent) { - if (parent instanceof cc.Scene) { - return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect; - } - else { - return parent._contentSize; - } +enum AlignMode { + ONCE = 0, + ON_WINDOW_RESIZE = 1, + ALWAYS = 2, } -function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, out_inverseScale) { - var scaleX = widgetNode._parent._scale.x; - var scaleY = widgetNode._parent._scale.y; - var translateX = 0; - var translateY = 0; - for (var node = widgetNode._parent;;) { - var pos = node._position; +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 @@ -68,14 +75,13 @@ function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, return; } if (node !== target) { - var sx = node._scale.x; - var sy = node._scale.y; + const sx = node._scale.x; + const sy = node._scale.y; translateX *= sx; translateY *= sy; scaleX *= sx; scaleY *= sy; - } - else { + } else { break; } } @@ -85,38 +91,40 @@ function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, out_inverseTranslate.y = -translateY; } -var tInverseTranslate = cc.Vec2.ZERO; -var tInverseScale = cc.Vec2.ONE; +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) { - var hasTarget = widget._target; - var target; - var inverseTranslate, inverseScale; + const hasTarget = widget._target; + let target; + let inverseTranslate; + let inverseScale; if (hasTarget) { target = hasTarget; inverseTranslate = tInverseTranslate; inverseScale = tInverseScale; computeInverseTransForTarget(node, target, inverseTranslate, inverseScale); - } - else { + } else { target = node._parent; } - var targetSize = getReadonlyNodeSize(target); - var targetAnchor = target._anchorPoint; + const targetSize = getReadonlyNodeSize(target); + const targetAnchor = target._anchorPoint; - var isRoot = !CC_EDITOR && target instanceof cc.Scene; - var x = node._position.x, y = node._position.y; - var anchor = node._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) { - var localLeft, localRight, targetWidth = targetSize.width; + let localLeft; + let localRight; + const targetWidth = targetSize.width; if (isRoot) { localLeft = cc.visibleRect.left.x; localRight = cc.visibleRect.right.x; - } - else { + } else { localLeft = -targetAnchor.x * targetWidth; localRight = localLeft + targetWidth; } @@ -132,7 +140,9 @@ function align (node, widget) { localRight *= inverseScale.x; } - var width, anchorX = anchor.x, scaleX = node._scale.x; + let width; + let anchorX = anchor.x; + let scaleX = node._scale.x; if (scaleX < 0) { anchorX = 1.0 - anchorX; scaleX = -scaleX; @@ -143,23 +153,21 @@ function align (node, widget) { node.width = width / scaleX; } x = localLeft + anchorX * width; - } - else { + } else { width = node.width * scaleX; if (widget.isAlignHorizontalCenter) { - var localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * targetWidth; - var targetCenter = (0.5 - targetAnchor.x) * targetSize.width; + 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) { + } else if (widget.isAlignLeft) { x = localLeft + anchorX * width; - } - else { + } else { x = localRight + (anchorX - 1) * width; } } @@ -167,12 +175,13 @@ function align (node, widget) { if (widget._alignFlags & VERTICAL) { - var localTop, localBottom, targetHeight = targetSize.height; + let localTop; + let localBottom; + const targetHeight = targetSize.height; if (isRoot) { localBottom = cc.visibleRect.bottom.y; localTop = cc.visibleRect.top.y; - } - else { + } else { localBottom = -targetAnchor.y * targetHeight; localTop = localBottom + targetHeight; } @@ -189,7 +198,9 @@ function align (node, widget) { localTop *= inverseScale.y; } - var height, anchorY = anchor.y, scaleY = node._scale.y; + let height; + let anchorY = anchor.y; + let scaleY = node._scale.y; if (scaleY < 0) { anchorY = 1.0 - anchorY; scaleY = -scaleY; @@ -200,23 +211,21 @@ function align (node, widget) { node.height = height / scaleY; } y = localBottom + anchorY * height; - } - else { + } else { height = node.height * scaleY; if (widget.isAlignVerticalCenter) { - var localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * targetHeight; - var targetMiddle = (0.5 - targetAnchor.y) * targetSize.height; + 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) { + } else if (widget.isAlignBottom) { y = localBottom + anchorY * height; - } - else { + } else { y = localTop + (anchorY - 1) * height; } } @@ -225,38 +234,29 @@ function align (node, widget) { node.setPosition(x, y); } -function visitNode (node) { - var widget = node._widget; +function visitNode (node: Node) { + const widget = node.uiWidgetComp; if (widget) { if (CC_DEV) { - var target = widget._target; - if (target) { - var isParent = node !== target && node.isChildOf(target); - if (!isParent) { - cc.errorID(6500); - widget._target = null; - } - } + // widget._validateTargetInDEV(); } align(node, widget); - if ((!CC_EDITOR || animationState.animatedSinceLastFrame) && widget.alignMode !== AlignMode.ALWAYS) { + if ((!CC_EDITOR /*|| animationState.animatedSinceLastFrame*/) && widget.alignMode !== AlignMode.ALWAYS) { widget.enabled = false; - } - else { + } else { activeWidgets.push(widget); } } - var children = node._children; - for (var i = 0; i < children.length; i++) { - var child = children[i]; - if (child._active) { + const children = node.children; + for (const child of children) { + if (child.active) { visitNode(child); } } } if (CC_EDITOR) { - var animationState = { + const animationState = { previewing: false, time: 0, animatedSinceLastFrame: false, @@ -265,109 +265,110 @@ if (CC_EDITOR) { 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; - } - } - } - } - } + // 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; + // } + // } + // } + // } + // } - var scene = cc.director.getScene(); + const scene = cc.director.getScene(); if (scene) { widgetManager.isAligning = true; if (widgetManager._nodesOrderDirty) { activeWidgets.length = 0; visitNode(scene); widgetManager._nodesOrderDirty = false; - } - else { - var i, widget, 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); - } - } + } 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; + // animationState.animatedSinceLastFrame = false; } } -var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (oldPos) { +function adjustWidgetToAllowMovingInEditor (oldPos: Vec3) { + if (!CC_EDITOR) { + return; + } + if (widgetManager.isAligning) { return; } - var newPos = this.node.position; - var delta = newPos.sub(oldPos); + const newPos = this.node.position; + const delta = newPos.sub(oldPos); - var target = this.node._parent; - var inverseScale = cc.Vec2.ONE; + let target = this.node._parent; + const inverseScale = cc.Vec2.ONE; if (this._target) { target = this._target; computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale); } - var targetSize = getReadonlyNodeSize(target); - var deltaInPercent; + 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 { + } else { deltaInPercent = cc.Vec2.ZERO; } @@ -389,32 +390,35 @@ var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (oldPos) { if (this.isAlignVerticalCenter) { this.verticalCenter += (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; } -}; +} + +function adjustWidgetToAllowResizingInEditor (oldSize: Size) { + if (!CC_EDITOR) { + return; + } -var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) { if (widgetManager.isAligning) { return; } - var newSize = this.node.getContentSize(); - var delta = cc.v2(newSize.width - oldSize.width, newSize.height - oldSize.height); + const newSize = this.node.getContentSize(); + const delta = cc.v2(newSize.width - oldSize.width, newSize.height - oldSize.height); - var target = this.node._parent; - var inverseScale = cc.Vec2.ONE; + let target = this.node._parent; + const inverseScale = cc.Vec2.ONE; if (this._target) { target = this._target; computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale); } - var targetSize = getReadonlyNodeSize(target); - var deltaInPercent; + 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 { + } else { deltaInPercent = cc.Vec2.ZERO; } - var anchor = this.node._anchorPoint; + const anchor = this.node._anchorPoint; if (this.isAlignTop) { this.top -= (this.isAbsoluteTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; @@ -428,52 +432,51 @@ var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) { if (this.isAlignRight) { this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; } -}; +} -var activeWidgets = []; +const activeWidgets = []; // updateAlignment from scene to node recursively -function updateAlignment (node) { - var parent = node._parent; - if (cc.Node.isNode(parent)) { +function updateAlignment (node: Node) { + const parent = node.parent; + if (parent && cc.Node.isNode(parent)) { updateAlignment(parent); } - var widget = node._widget || - node.getComponent(cc.Widget); // node._widget will be null when widget is disabled - if (widget) { + + // node._widget will be null when widget is disabled + const widget = node.uiWidgetComp || node.getComponent(cc.WidgetComponent); + if (widget && parent) { align(node, widget); } } -var widgetManager = cc._widgetManager = module.exports = { +export const widgetManager = cc._widgetManager = { _AlignFlags: { - TOP: TOP, - MID: MID, // vertical center - BOT: BOT, - LEFT: LEFT, - CENTER: CENTER, // horizontal center - RIGHT: RIGHT + TOP, + MID, // vertical center + BOT, + LEFT, + CENTER, // horizontal center + RIGHT, }, isAligning: false, _nodesOrderDirty: false, - _activeWidgetsIterator: new cc.js.array.MutableForwardIterator(activeWidgets), + _activeWidgetsIterator: new array.MutableForwardIterator(activeWidgets), - init: function (director) { + 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 { + } else { if (cc.sys.isMobile) { window.addEventListener('resize', this.onResized.bind(this)); - } - else { + } else { cc.view.on('canvas-resize', this.onResized, this); } } }, - add: function (widget) { + add (widget) { widget.node._widget = widget; this._nodesOrderDirty = true; if (CC_EDITOR && !cc.engine.isPlaying) { @@ -481,7 +484,7 @@ var widgetManager = cc._widgetManager = module.exports = { widget.node.on(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget); } }, - remove: function (widget) { + remove (widget) { widget.node._widget = null; this._activeWidgetsIterator.remove(widget); if (CC_EDITOR && !cc.engine.isPlaying) { @@ -490,30 +493,24 @@ var widgetManager = cc._widgetManager = module.exports = { } }, onResized () { - var scene = cc.director.getScene(); + const scene = cc.director.getScene(); if (scene) { this.refreshWidgetOnResized(scene); } }, refreshWidgetOnResized (node) { - var widget = cc.Node.isNode(node) && node.getComponent(cc.Widget); + const widget = cc.Node.isNode(node) && node.getComponent(cc.Widget); if (widget) { if (widget.alignMode === AlignMode.ON_WINDOW_RESIZE) { widget.enabled = true; } } - var children = node._children; - for (var i = 0; i < children.length; i++) { - var child = children[i]; + const children = node._children; + for (const child of children) { this.refreshWidgetOnResized(child); } }, - updateAlignment: updateAlignment, - AlignMode: AlignMode, + updateAlignment, + AlignMode, }; - -if (CC_EDITOR) { - module.exports._computeInverseTransForTarget = computeInverseTransForTarget; - module.exports._getReadonlyNodeSize = getReadonlyNodeSize; -} diff --git a/cocos/2d/label/CCLabel.js b/cocos/2d/label/CCLabel.js deleted file mode 100644 index 8102cab888..0000000000 --- a/cocos/2d/label/CCLabel.js +++ /dev/null @@ -1,620 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const macro = require('../platform/CCMacro'); -const RenderComponent = require('./CCRenderComponent'); -const renderEngine = require('../renderer/render-engine'); -const RenderFlow = require('../renderer/render-flow'); -const SpriteMaterial = renderEngine.SpriteMaterial; -const ImageAsset = require('../../assets/image-asset'); - -/** - * !#en Enum for text alignment. - * !#zh 文本横向对齐类型 - * @enum Label.HorizontalAlign - */ -/** - * !#en Alignment left for text. - * !#zh 文本内容左对齐。 - * @property {Number} LEFT - */ -/** - * !#en Alignment center for text. - * !#zh 文本内容居中对齐。 - * @property {Number} CENTER - */ -/** - * !#en Alignment right for text. - * !#zh 文本内容右边对齐。 - * @property {Number} RIGHT - */ -const HorizontalAlign = macro.TextAlignment; - -/** - * !#en Enum for vertical text alignment. - * !#zh 文本垂直对齐类型 - * @enum Label.VerticalAlign - */ -/** - * !#en Vertical alignment top for text. - * !#zh 文本顶部对齐。 - * @property {Number} TOP - */ -/** - * !#en Vertical alignment center for text. - * !#zh 文本居中对齐。 - * @property {Number} CENTER - */ -/** - * !#en Vertical alignment bottom for text. - * !#zh 文本底部对齐。 - * @property {Number} BOTTOM - */ -const VerticalAlign = macro.VerticalTextAlignment; - -/** - * !#en Enum for Overflow. - * !#zh Overflow 类型 - * @enum Label.Overflow - */ -/** - * !#en NONE. - * !#zh 不做任何限制。 - * @property {Number} NONE - */ -/** - * !#en In CLAMP mode, when label content goes out of the bounding box, it will be clipped. - * !#zh CLAMP 模式中,当文本内容超出边界框时,多余的会被截断。 - * @property {Number} CLAMP - */ -/** - * !#en In SHRINK mode, the font size will change dynamically to adapt the content size. - * !#zh SHRINK 模式,字体大小会动态变化,以适应内容大小。 - * @property {Number} SHRINK - */ -/** - * !#en In RESIZE_HEIGHT mode, you can only change the width of label and the height is changed automatically. - * !#zh 在 RESIZE_HEIGHT 模式下,只能更改文本的宽度,高度是自动改变的。 - * @property {Number} RESIZE_HEIGHT - */ -const Overflow = cc.Enum({ - NONE: 0, - CLAMP: 1, - SHRINK: 2, - RESIZE_HEIGHT: 3 -}); - -/** - * !#en Enum for font type. - * !#zh Type 类型 - * @enum Label.Type - */ -/** - * !#en The TTF font type. - * !#zh TTF字体 - * @property {Number} TTF - */ -/** - * !#en The bitmap font type. - * !#zh 位图字体 - * @property {Number} BMFont - */ -/** - * !#en The system font type. - * !#zh 系统字体 - * @property {Number} SystemFont - */ - -/** - * !#en The Label Component. - * !#zh 文字标签组件 - * @class Label - * @extends Component - */ -let Label = cc.Class({ - name: 'cc.Label', - extends: RenderComponent, - - ctor () { - if (CC_EDITOR) { - this._userDefinedFont = null; - } - - this._actualFontSize = 0; - this._assemblerData = null; - - this._ttfTexture = null; - }, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.renderers/Label', - help: 'i18n:COMPONENT.help_url.label', - inspector: 'packages://inspector/inspectors/comps/label.js', - }, - - properties: { - _useOriginalSize: true, - - /** - * !#en Content string of label. - * !#zh 标签显示的文本内容。 - * @property {String} string - */ - _string: { - default: '', - formerlySerializedAs: '_N$string', - }, - string: { - get () { - return this._string; - }, - set (value) { - let oldValue = this._string; - this._string = value.toString(); - - if (this.string !== oldValue) { - this._updateRenderData(); - } - - this._checkStringEmpty(); - }, - multiline: true, - tooltip: CC_DEV && 'i18n:COMPONENT.label.string' - }, - - /** - * !#en Horizontal Alignment of label. - * !#zh 文本内容的水平对齐方式。 - * @property {Label.HorizontalAlign} horizontalAlign - */ - horizontalAlign: { - default: HorizontalAlign.LEFT, - type: HorizontalAlign, - tooltip: CC_DEV && 'i18n:COMPONENT.label.horizontal_align', - notify (oldValue) { - if (this.horizontalAlign === oldValue) return; - this._updateRenderData(); - }, - animatable: false - }, - - /** - * !#en Vertical Alignment of label. - * !#zh 文本内容的垂直对齐方式。 - * @property {Label.VerticalAlign} verticalAlign - */ - verticalAlign: { - default: VerticalAlign.TOP, - type: VerticalAlign, - tooltip: CC_DEV && 'i18n:COMPONENT.label.vertical_align', - notify (oldValue) { - if (this.verticalAlign === oldValue) return; - this._updateRenderData(); - }, - animatable: false - }, - - - /** - * !#en The actual rendering font size in shrink mode - * !#zh SHRINK 模式下面文本实际渲染的字体大小 - * @property {Number} actualFontSize - */ - actualFontSize: { - displayName: 'Actual Font Size', - animatable: false, - readonly: true, - get () { - return this._actualFontSize; - } - }, - - _fontSize: 40, - /** - * !#en Font size of label. - * !#zh 文本字体大小。 - * @property {Number} fontSize - */ - fontSize: { - get () { - return this._fontSize; - }, - set (value) { - if (this._fontSize === value) return; - - this._fontSize = value; - this._updateRenderData(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.label.font_size', - }, - - /** - * !#en Font family of label, only take effect when useSystemFont property is true. - * !#zh 文本字体名称, 只在 useSystemFont 属性为 true 的时候生效。 - * @property {String} fontFamily - */ - fontFamily: { - default: "Arial", - tooltip: CC_DEV && 'i18n:COMPONENT.label.font_family', - notify (oldValue) { - if (this.fontFamily === oldValue) return; - this._updateRenderData(); - }, - animatable: false - }, - - _lineHeight: 40, - /** - * !#en Line Height of label. - * !#zh 文本行高。 - * @property {Number} lineHeight - */ - lineHeight: { - get () { - return this._lineHeight; - }, - set (value) { - if (this._lineHeight === value) return; - this._lineHeight = value; - this._updateRenderData(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.label.line_height', - }, - /** - * !#en Overflow of label. - * !#zh 文字显示超出范围时的处理方式。 - * @property {Label.Overflow} overflow - */ - overflow: { - default: Overflow.NONE, - type: Overflow, - tooltip: CC_DEV && 'i18n:COMPONENT.label.overflow', - notify (oldValue) { - if (this.overflow === oldValue) return; - this._updateRenderData(); - }, - animatable: false - }, - - _enableWrapText: true, - /** - * !#en Whether auto wrap label when string width is large than label width. - * !#zh 是否自动换行。 - * @property {Boolean} enableWrapText - */ - enableWrapText: { - get () { - return this._enableWrapText; - }, - set (value) { - if (this._enableWrapText === value) return; - - this._enableWrapText = value; - this._updateRenderData(); - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.label.wrap', - }, - - // 这个保存了旧项目的 file 数据 - _N$file: null, - - /** - * !#en The font of label. - * !#zh 文本字体。 - * @property {Font} font - */ - font: { - get () { - return this._N$file; - }, - set (value) { - if (this.font === value) return; - - //if delete the font, we should change isSystemFontUsed to true - if (!value) { - this._isSystemFontUsed = true; - } - - if (CC_EDITOR && value) { - this._userDefinedFont = value; - } - - this._N$file = value; - this._bmFontOriginalSize = -1; - if (value && this._isSystemFontUsed) - this._isSystemFontUsed = false; - - if ( typeof value === 'string' ) { - cc.warnID(4000); - } - - if (value instanceof cc.BitmapFont) { - this._bmFontOriginalSize = value.fontSize; - } - - if (this._renderData) { - this.destroyRenderData(this._renderData); - this._renderData = null; - } - this._fontAtlas = null; - this._updateAssembler(); - this._activateMaterial(true); - this._updateRenderData(); - }, - type: cc.Font, - tooltip: CC_DEV && 'i18n:COMPONENT.label.font', - animatable: false - }, - - _isSystemFontUsed: true, - - /** - * !#en Whether use system font name or not. - * !#zh 是否使用系统字体。 - * @property {Boolean} isSystemFontUsed - */ - useSystemFont: { - get () { - return this._isSystemFontUsed; - }, - set (value) { - if (this._isSystemFontUsed === value) return; - - this.destroyRenderData(this._renderData); - this._renderData = null; - - if (CC_EDITOR) { - if (!value && this._isSystemFontUsed && this._userDefinedFont) { - this.font = this._userDefinedFont; - this.spacingX = this._spacingX; - return; - } - } - - this._isSystemFontUsed = !!value; - if (value) { - this.font = null; - this._updateAssembler(); - this._updateRenderData(); - this._checkStringEmpty(); - } - else if (!this._userDefinedFont) { - this.disableRender(); - } - - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.label.system_font', - }, - - _bmFontOriginalSize: { - displayName: 'BMFont Original Size', - default: -1, - serializable: false, - readonly: true, - visible: true, - animatable: false - }, - - _spacingX: 0, - spacingX: { - get () { - return this._spacingX; - }, - set (value) { - this._spacingX = value; - this._updateRenderData(); - } - }, - - _isBold: { - default: false, - serializable: false, - }, - _isItalic: { - default: false, - serializable: false, - }, - _isUnderline: { - default: false, - serializable: false, - }, - }, - - statics: { - HorizontalAlign: HorizontalAlign, - VerticalAlign: VerticalAlign, - Overflow: Overflow, - }, - - onEnable () { - this._super(); - - // TODO: Hack for barbarians - if (!this.font && !this._isSystemFontUsed) { - this.useSystemFont = true; - } - // Reapply default font family if necessary - if (this.useSystemFont && !this.fontFamily) { - this.fontFamily = 'Arial'; - } - - // Keep track of Node size - this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this); - this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this); - - this._checkStringEmpty(); - this._updateAssembler(); - this._activateMaterial(); - }, - - onDisable () { - this._super(); - this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this); - this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this); - }, - - onDestroy () { - this._assembler._resetAssemblerData && this._assembler._resetAssemblerData(this._assemblerData); - this._assemblerData = null; - if (this._ttfTexture) { - this._ttfTexture.destroy(); - this._ttfTexture = null; - } - this._super(); - }, - - _canRender () { - let result = this._super(); - let font = this.font; - if (font instanceof cc.BitmapFont) { - let spriteFrame = font.spriteFrame; - // cannot be activated if texture not loaded yet - if (!spriteFrame || !spriteFrame.textureLoaded()) { - result = false; - } - } - return result; - }, - - _checkStringEmpty () { - this.markForRender(!!this.string); - }, - - _updateAssembler () { - let assembler = Label._assembler.getAssembler(this); - - if (this._assembler !== assembler) { - this._assembler = assembler; - this._renderData = null; - } - - if (!this._renderData) { - this._renderData = this._assembler.createData(this); - } - }, - - _activateMaterial (force) { - let material = this._material; - if (material && !force) { - return; - } - - let font = this.font; - if (font instanceof cc.BitmapFont) { - let spriteFrame = font.spriteFrame; - // cannot be activated if texture not loaded yet - if (!spriteFrame || !spriteFrame.textureLoaded()) { - this.disableRender(); - - if (spriteFrame) { - spriteFrame.once('load', this._activateMaterial, this); - spriteFrame.ensureLoadTexture(); - } - return; - } - - // TODO: old texture in material have been released by loader - this._texture = spriteFrame._texture; - } - else { - if (!this._ttfTexture) { - this._ttfTexture = new cc.Texture2D(); - // TTF texture in web will blend with canvas or body background color - if (!CC_JSB) { - this._ttfTexture.setPremultiplyAlpha(true); - } - this._assemblerData = this._assembler._getAssemblerData(); - this._ttfTexture.image = new ImageAsset(this._assemblerData.canvas); - } - this._texture = this._ttfTexture; - } - - // Canvas - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - this._texture.url = this.uuid + '_texture'; - } - // WebGL - else { - if (!material) { - material = new SpriteMaterial(); - } - // Setup blend function for premultiplied ttf label texture - if (this._texture === this._ttfTexture) { - this._srcBlendFactor = cc.macro.BlendFactor.ONE; - } - else { - this._srcBlendFactor = cc.macro.BlendFactor.SRC_ALPHA; - } - material.texture = this._texture; - this._updateMaterial(material); - } - - this.markForUpdateRenderData(true); - this.markForRender(true); - }, - - _updateColor () { - let font = this.font; - if (font instanceof cc.BitmapFont) { - this._super(); - } - else { - this._updateRenderData(); - this.node._renderFlag &= ~RenderFlow.FLAG_COLOR; - } - }, - - _updateRenderData (force) { - let renderData = this._renderData; - if (renderData) { - renderData.vertDirty = true; - renderData.uvDirty = true; - this.markForUpdateRenderData(true); - } - - if (CC_EDITOR || force) { - this._updateAssembler(); - this._activateMaterial(force); - this._assembler.updateRenderData(this); - } - }, - - _enableBold (enabled) { - this._isBold = !!enabled; - }, - - _enableItalics (enabled) { - this._isItalic = !!enabled; - }, - - _enableUnderline (enabled) { - this._isUnderline = !!enabled; - }, - }); - - cc.Label = module.exports = Label; diff --git a/cocos/2d/label/CCLabelOutline.js b/cocos/2d/label/label-outline.ts similarity index 57% rename from cocos/2d/label/CCLabelOutline.js rename to cocos/2d/label/label-outline.ts index ae859c1545..578adefa0a 100644 --- a/cocos/2d/label/CCLabelOutline.js +++ b/cocos/2d/label/label-outline.ts @@ -37,63 +37,51 @@ * node.parent = this.node; */ -let LabelOutline = cc.Class({ - name: 'cc.LabelOutline', - extends: require('./CCComponent'), - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.renderers/LabelOutline', - executeInEditMode: true, - requireComponent: cc.Label, - }, +import { Component } from '../../components/component'; - properties: { - _color: cc.color(255,255,255,255), - _width: 1, +export class LabelOutline extends Component { + private _color = cc.color(255, 255, 255, 255); + private _width = 1; - /** - * !#en Change the outline color - * !#zh 改变描边的颜色 - * @property color - * @type {Color} - * @example - * outline.color = new cc.Color(0.5, 0.3, 0.7, 1.0);; - */ - color: { - get: function () { - return this._color; - }, - set: function (value) { - this._color = cc.color(value); - this._updateRenderData(); - } - }, + /** + * !#en Change the outline color + * !#zh 改变描边的颜色 + * @property color + * @type {Color} + * @example + * outline.color = new cc.Color(0.5, 0.3, 0.7, 1.0);; + */ + get color () { + return this._color; + } + set color (value) { + this._color = cc.color(value); + this._updateRenderData(); + } - /** - * !#en Change the outline width - * !#zh 改变描边的宽度 - * @property width - * @type {Number} - * @example - * outline.width = 3; - */ - width: { - get: function () { - return this._width; - }, - set: function (value) { - this._width = value; - this._updateRenderData(); - } - } - }, + /** + * !#en Change the outline width + * !#zh 改变描边的宽度 + * @property width + * @type {Number} + * @example + * outline.width = 3; + */ + get width () { + return this._width; + } - _updateRenderData () { - let label = this.node.getComponent(cc.Label); + set width (value) { + this._width = value; + this._updateRenderData(); + } + + private _updateRenderData () { + const label = this.node.getComponent(cc.Label); if (label) { label._updateRenderData(true); } } +} -}); - -cc.LabelOutline = module.exports = LabelOutline; +cc.LabelOutline = LabelOutline; diff --git a/cocos/2d/renderable/CCMask.js b/cocos/2d/renderable/CCMask.js deleted file mode 100644 index 35f58a94f5..0000000000 --- a/cocos/2d/renderable/CCMask.js +++ /dev/null @@ -1,443 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const misc = require('../utils/misc'); -const renderEngine = require('../renderer/render-engine'); -const math = renderEngine.math; -const StencilMaterial = renderEngine.StencilMaterial; -const RenderComponent = require('./CCRenderComponent'); -const RenderFlow = require('../renderer/render-flow'); -const Graphics = require('../graphics/graphics'); - -let _vec2_temp = cc.v2(); -let _mat4_temp = math.mat4.create(); - -/** - * !#en the type for mask. - * !#zh 遮罩组件类型 - * @enum Mask.Type - */ -let MaskType = cc.Enum({ - /** - * !#en Rect mask. - * !#zh 使用矩形作为遮罩 - * @property {Number} RECT - */ - RECT: 0, - /** - * !#en Ellipse Mask. - * !#zh 使用椭圆作为遮罩 - * @property {Number} ELLIPSE - */ - ELLIPSE: 1, - /** - * !#en Image Stencil Mask. - * !#zh 使用图像模版作为遮罩 - * @property {Number} IMAGE_STENCIL - */ - IMAGE_STENCIL: 2, -}); - -const SEGEMENTS_MIN = 3; -const SEGEMENTS_MAX = 10000; - -/** - * !#en The Mask Component - * !#zh 遮罩组件 - * @class Mask - * @extends Component - */ -let Mask = cc.Class({ - name: 'cc.Mask', - extends: RenderComponent, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.renderers/Mask', - help: 'i18n:COMPONENT.help_url.mask', - inspector: 'packages://inspector/inspectors/comps/mask.js' - }, - - properties: { - _spriteFrame: { - default: null, - type: cc.SpriteFrame - }, - - /** - * !#en The mask type. - * !#zh 遮罩类型 - * @property type - * @type {Mask.Type} - * @example - * mask.type = cc.Mask.Type.RECT; - */ - _type: MaskType.RECT, - type: { - get: function () { - return this._type; - }, - set: function (value) { - this._type = value; - if (this._type !== MaskType.IMAGE_STENCIL) { - this.spriteFrame = null; - this.alphaThreshold = 0; - this._updateGraphics(); - } - if (this._renderData) { - this.destroyRenderData(this._renderData); - this._renderData = null; - } - this._activateMaterial(); - }, - type: MaskType, - tooltip: CC_DEV && 'i18n:COMPONENT.mask.type', - }, - - /** - * !#en The mask image - * !#zh 遮罩所需要的贴图 - * @property spriteFrame - * @type {SpriteFrame} - * @default null - * @example - * mask.spriteFrame = newSpriteFrame; - */ - spriteFrame: { - type: cc.SpriteFrame, - tooltip: CC_DEV && 'i18n:COMPONENT.mask.spriteFrame', - get: function () { - return this._spriteFrame; - }, - set: function (value) { - let lastSprite = this._spriteFrame; - if (CC_EDITOR) { - if ((lastSprite && lastSprite._uuid) === (value && value._uuid)) { - return; - } - } - else { - if (lastSprite === value) { - return; - } - } - this._spriteFrame = value; - this._applySpriteFrame(lastSprite); - }, - }, - - /** - * !#en - * The alpha threshold.(Not supported Canvas Mode)
- * The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
- * Should be a float between 0 and 1.
- * This default to 0 (so alpha test is disabled). - * When it's set to 1, the stencil will discard all pixels, nothing will be shown, - * In previous version, it act as if the alpha test is disabled, which is incorrect. - * !#zh - * Alpha 阈值(不支持 Canvas 模式)
- * 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。
- * 该数值 0 ~ 1 之间的浮点数,默认值为 0(因此禁用 alpha 测试) - * 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容,在之前的版本中,设置为 1 等同于 0,这种效果其实是不正确的 - * @property alphaThreshold - * @type {Number} - * @default 0 - */ - alphaThreshold: { - default: 0, - type: cc.Float, - range: [0, 1, 0.1], - slide: true, - tooltip: CC_DEV && 'i18n:COMPONENT.mask.alphaThreshold', - notify: function () { - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - cc.warnID(4201); - return; - } - if (this._material) { - this._material.alphaThreshold = this.alphaThreshold; - this._material.updateHash(); - } - } - }, - - /** - * !#en Reverse mask (Not supported Canvas Mode) - * !#zh 反向遮罩(不支持 Canvas 模式) - * @property inverted - * @type {Boolean} - * @default false - */ - inverted: { - default: false, - type: cc.Boolean, - tooltip: CC_DEV && 'i18n:COMPONENT.mask.inverted', - notify: function () { - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - cc.warnID(4202); - return; - } - } - }, - - /** - * TODO: remove segments, not supported by graphics - * !#en The segements for ellipse mask. - * !#zh 椭圆遮罩的曲线细分数 - * @property segements - * @type {Number} - * @default 64 - */ - _segments: 64, - segements: { - get: function () { - return this._segments; - }, - set: function (value) { - this._segments = misc.clampf(value, SEGEMENTS_MIN, SEGEMENTS_MAX); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.mask.segements', - }, - - _resizeToTarget: { - animatable: false, - set: function (value) { - if(value) { - this._resizeNodeToTargetNode(); - } - } - } - }, - - statics: { - Type: MaskType, - }, - - onLoad () { - this._graphics = new Graphics(); - this._graphics.node = this.node; - this._graphics.lineWidth = 0; - this._graphics.strokeColor = cc.color(0, 0, 0, 0); - }, - - onRestore () { - if (!this._graphics) { - this._graphics = new Graphics(); - this._graphics.node = this.node; - this._graphics.lineWidth = 0; - } - if (this._type !== MaskType.IMAGE_STENCIL) { - this._updateGraphics(); - } - }, - - onEnable () { - this._super(); - if (this._type === MaskType.IMAGE_STENCIL) { - if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { - // Do not render when sprite frame is not ready - this.markForRender(false); - if (this._spriteFrame) { - this._spriteFrame.once('load', this._onTextureLoaded, this); - this._spriteFrame.ensureLoadTexture(); - } - } - } - else { - this._updateGraphics(); - } - - this.node.on(cc.Node.EventType.POSITION_CHANGED, this._updateGraphics, this); - this.node.on(cc.Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); - this.node.on(cc.Node.EventType.SCALE_CHANGED, this._updateGraphics, this); - this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateGraphics, this); - this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); - - this.node._renderFlag |= RenderFlow.FLAG_POST_RENDER; - this._activateMaterial(); - }, - - onDisable () { - this._super(); - - this.node.off(cc.Node.EventType.POSITION_CHANGED, this._updateGraphics, this); - this.node.off(cc.Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); - this.node.off(cc.Node.EventType.SCALE_CHANGED, this._updateGraphics, this); - this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateGraphics, this); - this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); - - this.node._renderFlag &= ~RenderFlow.FLAG_POST_RENDER; - }, - - onDestroy () { - this._super(); - this._graphics.destroy(); - }, - - _resizeNodeToTargetNode: CC_EDITOR && function () { - if(this.spriteFrame) { - let rect = this.spriteFrame.getRect(); - this.node.setContentSize(rect.width, rect.height); - } - }, - - _onTextureLoaded () { - // Mark render data dirty - if (this._renderData) { - this._renderData.uvDirty = true; - this._renderData.vertDirty = true; - this.markForUpdateRenderData(true); - } - // Reactivate material - if (this.enabledInHierarchy) { - this._activateMaterial(); - } - }, - - _applySpriteFrame (oldFrame) { - if (oldFrame && oldFrame.off) { - oldFrame.off('load', this._onTextureLoaded, this); - } - let spriteFrame = this._spriteFrame; - if (spriteFrame) { - if (spriteFrame.textureLoaded()) { - this._onTextureLoaded(null); - } - else { - spriteFrame.once('load', this._onTextureLoaded, this); - spriteFrame.ensureLoadTexture(); - } - } - }, - - _activateMaterial () { - // cannot be activated if texture not loaded yet - if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded())) { - this.markForRender(false); - return; - } - - // WebGL - if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { - // Init material - if (!this._material) { - this._material = new StencilMaterial(); - } - - // Reset material - if (this._type === MaskType.IMAGE_STENCIL) { - let texture = this.spriteFrame.getTexture(); - this._material.useModel = false; - this._material.useTexture = true; - this._material.useColor = true; - this._material.texture = texture; - this._material.alphaThreshold = this.alphaThreshold; - } - else { - this._material.useModel = true; - this._material.useTexture = false; - this._material.useColor = false; - } - } - - this.markForRender(true); - }, - - _updateGraphics () { - let node = this.node; - let graphics = this._graphics; - // Share render data with graphics content - graphics.clear(false); - let width = node._contentSize.width; - let height = node._contentSize.height; - let x = -width * node._anchorPoint.x; - let y = -height * node._anchorPoint.y; - if (this._type === MaskType.RECT) { - graphics.rect(x, y, width, height); - } - else if (this._type === MaskType.ELLIPSE) { - let cx = x + width / 2, - cy = y + height / 2, - rx = width / 2, - ry = height / 2; - graphics.ellipse(cx, cy, rx, ry); - } - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - graphics.stroke(); - } - else { - graphics.fill(); - } - }, - - _hitTest (cameraPt) { - let node = this.node; - let size = node.getContentSize(), - w = size.width, - h = size.height, - testPt = _vec2_temp; - - node._updateWorldMatrix(); - math.mat4.invert(_mat4_temp, node._worldMatrix); - math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); - testPt.x += node._anchorPoint.x * w; - testPt.y += node._anchorPoint.y * h; - - if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) { - return testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h; - } - else if (this.type === MaskType.ELLIPSE) { - let rx = w / 2, ry = h / 2; - let px = testPt.x - 0.5 * w, py = testPt.y - 0.5 * h; - return px * px / (rx * rx) + py * py / (ry * ry) < 1; - } - }, - - markForUpdateRenderData (enable) { - if (enable && this.enabledInHierarchy) { - this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - } - else if (!enable) { - this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; - } - }, - - markForRender (enable) { - if (enable && this.enabledInHierarchy) { - this.node._renderFlag |= (RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | - RenderFlow.FLAG_POST_RENDER); - } - else if (!enable) { - this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_POST_RENDER); - } - }, - - disableRender () { - this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | - RenderFlow.FLAG_POST_RENDER); - }, -}); - -cc.Mask = module.exports = Mask; diff --git a/cocos/2d/renderable/CCRenderComponent.js b/cocos/2d/renderable/CCRenderComponent.js deleted file mode 100644 index 4ff2a9f050..0000000000 --- a/cocos/2d/renderable/CCRenderComponent.js +++ /dev/null @@ -1,224 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const Component = require('./CCComponent'); -const renderEngine = require('../renderer/render-engine'); -const RenderFlow = require('../renderer/render-flow'); -const BlendFactor = require('../platform/CCMacro').BlendFactor; -const RenderData = renderEngine.RenderData; -const gfx = renderEngine.gfx; - -/** - * !#en - * Base class for components which supports rendering features. - * !#zh - * 所有支持渲染的组件的基类 - * - * @class RenderComponent - * @extends Component - */ -let RenderComponent = cc.Class({ - name: 'RenderComponent', - extends: Component, - - editor: CC_EDITOR && { - executeInEditMode: true, - disallowMultiple: true - }, - - properties: { - _srcBlendFactor: BlendFactor.SRC_ALPHA, - _dstBlendFactor: BlendFactor.ONE_MINUS_SRC_ALPHA, - - /** - * !#en specify the source Blend Factor, this will generate a custom material object, please pay attention to the memory cost. - * !#zh 指定原图的混合模式,这会克隆一个新的材质对象,注意这带来的 - * @property srcBlendFactor - * @type {macro.BlendFactor} - * @example - * sprite.srcBlendFactor = cc.macro.BlendFactor.ONE; - */ - srcBlendFactor: { - get: function() { - return this._srcBlendFactor; - }, - set: function(value) { - if (this._srcBlendFactor === value) return; - this._srcBlendFactor = value; - this._updateBlendFunc(true); - }, - animatable: false, - type:BlendFactor, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.src_blend_factor' - }, - - /** - * !#en specify the destination Blend Factor. - * !#zh 指定目标的混合模式 - * @property dstBlendFactor - * @type {macro.BlendFactor} - * @example - * sprite.dstBlendFactor = cc.macro.BlendFactor.ONE; - */ - dstBlendFactor: { - get: function() { - return this._dstBlendFactor; - }, - set: function(value) { - if (this._dstBlendFactor === value) return; - this._dstBlendFactor = value; - this._updateBlendFunc(true); - }, - animatable: false, - type: BlendFactor, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.dst_blend_factor' - }, - }, - - ctor () { - this._material = null; - this._renderData = null; - this.__allocedDatas = []; - this._vertexFormat = null; - this._toPostHandle = false; - this._assembler = this.constructor._assembler; - this._postAssembler = this.constructor._postAssembler; - }, - - onEnable () { - if (this.node._renderComponent) { - this.node._renderComponent.enabled = false; - } - this.node._renderComponent = this; - this.node._renderFlag |= RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR; - }, - - onDisable () { - this.node._renderComponent = null; - this.disableRender(); - }, - - onDestroy () { - for (let i = 0, l = this.__allocedDatas.length; i < l; i++) { - RenderData.free(this.__allocedDatas[i]); - } - this.__allocedDatas.length = 0; - this._material = null; - this._renderData = null; - }, - - _canRender () { - return this._enabled; - }, - - markForUpdateRenderData (enable) { - if (enable && this._canRender()) { - this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - } - else if (!enable) { - this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; - } - }, - - markForRender (enable) { - if (enable && this._canRender()) { - this.node._renderFlag |= RenderFlow.FLAG_RENDER; - } - else if (!enable) { - this.node._renderFlag &= ~RenderFlow.FLAG_RENDER; - } - }, - - markForCustomIARender (enable) { - if (enable && this._canRender()) { - this.node._renderFlag |= RenderFlow.FLAG_CUSTOM_IA_RENDER; - } - else if (!enable) { - this.node._renderFlag &= ~RenderFlow.FLAG_CUSTOM_IA_RENDER; - } - }, - - disableRender () { - this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_CUSTOM_IA_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR); - }, - - requestRenderData () { - let data = RenderData.alloc(); - this.__allocedDatas.push(data); - return data; - }, - - destroyRenderData (data) { - let index = this.__allocedDatas.indexOf(data); - if (index !== -1) { - this.__allocedDatas.splice(index, 1); - RenderData.free(data); - } - }, - - _updateColor () { - let material = this._material; - if (material) { - material.color = this.node.color; - material.updateHash(); - - // reset flag when set color to material successfully - this.node._renderFlag &= ~RenderFlow.FLAG_COLOR; - } - }, - - getMaterial () { - return this._material; - }, - - _updateMaterial (material) { - this._material = material; - - this._updateBlendFunc(); - material.updateHash(); - }, - - _updateBlendFunc: function (updateHash) { - if (!this._material) { - return; - } - - var pass = this._material._mainTech.passes[0]; - pass.setBlend( - gfx.BLEND_FUNC_ADD, - this._srcBlendFactor, this._dstBlendFactor, - gfx.BLEND_FUNC_ADD, - this._srcBlendFactor, this._dstBlendFactor - ); - - if (updateHash) { - this._material.updateHash(); - } - }, -}); -RenderComponent._assembler = null; -RenderComponent._postAssembler = null; - -cc.RenderComponent = module.exports = RenderComponent; \ No newline at end of file diff --git a/cocos/2d/renderable/CCSprite.js b/cocos/2d/renderable/CCSprite.js deleted file mode 100644 index cd2de5ab18..0000000000 --- a/cocos/2d/renderable/CCSprite.js +++ /dev/null @@ -1,661 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const misc = require('../utils/misc'); -const NodeEvent = require('../CCNode').EventType; -const RenderComponent = require('./CCRenderComponent'); -const RenderFlow = require('../renderer/render-flow'); -const renderEngine = require('../renderer/render-engine'); -const SpriteMaterial = renderEngine.SpriteMaterial; -const GraySpriteMaterial = renderEngine.GraySpriteMaterial; - -/** - * !#en Enum for sprite type. - * !#zh Sprite 类型 - * @enum Sprite.Type - */ -var SpriteType = cc.Enum({ - /** - * !#en The simple type. - * !#zh 普通类型 - * @property {Number} SIMPLE - */ - SIMPLE: 0, - /** - * !#en The sliced type. - * !#zh 切片(九宫格)类型 - * @property {Number} SLICED - */ - SLICED: 1, - /** - * !#en The tiled type. - * !#zh 平铺类型 - * @property {Number} TILED - */ - TILED: 2, - /** - * !#en The filled type. - * !#zh 填充类型 - * @property {Number} FILLED - */ - FILLED: 3, - /** - * !#en The mesh type. - * !#zh 以 Mesh 三角形组成的类型 - * @property {Number} MESH - */ - MESH: 4 -}); - -/** - * !#en Enum for fill type. - * !#zh 填充类型 - * @enum Sprite.FillType - */ -var FillType = cc.Enum({ - /** - * !#en The horizontal fill. - * !#zh 水平方向填充 - * @property {Number} HORIZONTAL - */ - HORIZONTAL: 0, - /** - * !#en The vertical fill. - * !#zh 垂直方向填充 - * @property {Number} VERTICAL - */ - VERTICAL: 1, - /** - * !#en The radial fill. - * !#zh 径向填充 - * @property {Number} RADIAL - */ - RADIAL:2, -}); - -/** - * !#en Sprite Size can track trimmed size, raw size or none. - * !#zh 精灵尺寸调整模式 - * @enum Sprite.SizeMode - */ -var SizeMode = cc.Enum({ - /** - * !#en Use the customized node size. - * !#zh 使用节点预设的尺寸 - * @property {Number} CUSTOM - */ - CUSTOM: 0, - /** - * !#en Match the trimmed size of the sprite frame automatically. - * !#zh 自动适配为精灵裁剪后的尺寸 - * @property {Number} TRIMMED - */ - TRIMMED: 1, - /** - * !#en Match the raw size of the sprite frame automatically. - * !#zh 自动适配为精灵原图尺寸 - * @property {Number} RAW - */ - RAW: 2 -}); - -var State = cc.Enum({ - /** - * !#en The normal state - * !#zh 正常状态 - * @property {Number} NORMAL - */ - NORMAL: 0, - /** - * !#en The gray state, all color will be modified to grayscale value. - * !#zh 灰色状态,所有颜色会被转换成灰度值 - * @property {Number} GRAY - */ - GRAY: 1 -}); - -/** - * !#en Renders a sprite in the scene. - * !#zh 该组件用于在场景中渲染精灵。 - * @class Sprite - * @extends Component - * @example - * // Create a new node and add sprite components. - * var node = new cc.Node("New Sprite"); - * var sprite = node.addComponent(cc.Sprite); - * node.parent = this.node; - */ -var Sprite = cc.Class({ - name: 'cc.Sprite', - extends: RenderComponent, - - ctor () { - this._assembler = null; - this._graySpriteMaterial = null; - this._spriteMaterial = null; - }, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.renderers/Sprite', - help: 'i18n:COMPONENT.help_url.sprite', - inspector: 'packages://inspector/inspectors/comps/sprite.js', - }, - - properties: { - _spriteFrame: { - default: null, - type: cc.SpriteFrame - }, - _type: SpriteType.SIMPLE, - _sizeMode: SizeMode.TRIMMED, - _fillType: 0, - _fillCenter: cc.v2(0,0), - _fillStart: 0, - _fillRange: 0, - _isTrimmedMode: true, - _state: 0, - _atlas: { - default: null, - type: cc.SpriteAtlas, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.atlas', - editorOnly: true, - visible: true, - animatable: false - }, - - /** - * !#en The sprite frame of the sprite. - * !#zh 精灵的精灵帧 - * @property spriteFrame - * @type {SpriteFrame} - * @example - * sprite.spriteFrame = newSpriteFrame; - */ - spriteFrame: { - get: function () { - return this._spriteFrame; - }, - set: function (value, force) { - var lastSprite = this._spriteFrame; - if (CC_EDITOR) { - if (!force && ((lastSprite && lastSprite._uuid) === (value && value._uuid))) { - return; - } - } - else { - if (lastSprite === value) { - return; - } - } - this._spriteFrame = value; - // render & update render data flag will be triggered while applying new sprite frame - this.markForUpdateRenderData(false); - this._applySpriteFrame(lastSprite); - if (CC_EDITOR) { - this.node.emit('spriteframe-changed', this); - } - }, - type: cc.SpriteFrame, - }, - - /** - * !#en The sprite render type. - * !#zh 精灵渲染类型 - * @property type - * @type {Sprite.Type} - * @example - * sprite.type = cc.Sprite.Type.SIMPLE; - */ - type: { - get: function () { - return this._type; - }, - set: function (value) { - if (this._type !== value) { - this.destroyRenderData(this._renderData); - this._renderData = null; - this._type = value; - this._updateAssembler(); - } - }, - type: SpriteType, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.type', - }, - - /** - * !#en - * The fill type, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. - * !#zh - * 精灵填充类型,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 - * @property fillType - * @type {Sprite.FillType} - * @example - * sprite.fillType = cc.Sprite.FillType.HORIZONTAL; - */ - fillType : { - get: function () { - return this._fillType; - }, - set: function(value) { - if (value !== this._fillType) { - if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) { - this.destroyRenderData(this._renderData); - this._renderData = null; - } - else if (this._renderData) { - this.markForUpdateRenderData(true); - } - this._fillType = value; - this._updateAssembler(); - } - }, - type: FillType, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_type' - }, - - /** - * !#en - * The fill Center, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. - * !#zh - * 填充中心点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 - * @property fillCenter - * @type {Vec2} - * @example - * sprite.fillCenter = new cc.Vec2(0, 0); - */ - fillCenter: { - get: function() { - return this._fillCenter; - }, - set: function(value) { - this._fillCenter.x = value.x; - this._fillCenter.y = value.y; - if (this._type === SpriteType.FILLED && this._renderData) { - this.markForUpdateRenderData(true); - } - }, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_center', - }, - - /** - * !#en - * The fill Start, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. - * !#zh - * 填充起始点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 - * @property fillStart - * @type {Number} - * @example - * // -1 To 1 between the numbers - * sprite.fillStart = 0.5; - */ - fillStart: { - get: function() { - return this._fillStart; - }, - set: function(value) { - this._fillStart = misc.clampf(value, -1, 1); - if (this._type === SpriteType.FILLED && this._renderData) { - this.markForUpdateRenderData(true); - } - }, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_start' - }, - - /** - * !#en - * The fill Range, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. - * !#zh - * 填充范围,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 - * @property fillRange - * @type {Number} - * @example - * // -1 To 1 between the numbers - * sprite.fillRange = 1; - */ - fillRange: { - get: function() { - return this._fillRange; - }, - set: function(value) { - this._fillRange = misc.clampf(value, -1, 1); - if (this._type === SpriteType.FILLED && this._renderData) { - this.markForUpdateRenderData(true); - } - }, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_range' - }, - /** - * !#en specify the frame is trimmed or not. - * !#zh 是否使用裁剪模式 - * @property trim - * @type {Boolean} - * @example - * sprite.trim = true; - */ - trim: { - get: function () { - return this._isTrimmedMode; - }, - set: function (value) { - if (this._isTrimmedMode !== value) { - this._isTrimmedMode = value; - if ((this._type === SpriteType.SIMPLE || this._type === SpriteType.MESH) && - this._renderData) { - this.markForUpdateRenderData(true); - } - } - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.trim' - }, - - - /** - * !#en specify the size tracing mode. - * !#zh 精灵尺寸调整模式 - * @property sizeMode - * @type {Sprite.SizeMode} - * @example - * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; - */ - sizeMode: { - get: function () { - return this._sizeMode; - }, - set: function (value) { - this._sizeMode = value; - if (value !== SizeMode.CUSTOM) { - this._applySpriteSize(); - } - }, - animatable: false, - type: SizeMode, - tooltip: CC_DEV && 'i18n:COMPONENT.sprite.size_mode' - } - }, - - statics: { - FillType: FillType, - Type: SpriteType, - SizeMode: SizeMode, - State: State, - }, - - setVisible: function (visible) { - this.enabled = visible; - }, - - /** - * Change the state of sprite. - * @method setState - * @see `Sprite.State` - * @param state {Sprite.State} NORMAL or GRAY State. - */ - setState: function (state) { - if (this._state === state) return; - this._state = state; - this._activateMaterial(); - }, - - /** - * Gets the current state. - * @method getState - * @see `Sprite.State` - * @return {Sprite.State} - */ - getState: function () { - return this._state; - }, - - onEnable: function () { - this._super(); - - if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { - // Do not render when sprite frame is not ready - this.disableRender(); - if (this._spriteFrame) { - this._spriteFrame.once('load', this._onTextureLoaded, this); - this._spriteFrame.ensureLoadTexture(); - } - } - - this._updateAssembler(); - this._activateMaterial(); - - this.node.on(NodeEvent.SIZE_CHANGED, this._onNodeSizeDirty, this); - this.node.on(NodeEvent.ANCHOR_CHANGED, this._onNodeSizeDirty, this); - }, - - onDisable: function () { - this._super(); - - this.node.off(NodeEvent.SIZE_CHANGED, this._onNodeSizeDirty, this); - this.node.off(NodeEvent.ANCHOR_CHANGED, this._onNodeSizeDirty, this); - }, - - _onNodeSizeDirty () { - if (!this._renderData) return; - this.markForUpdateRenderData(true); - }, - - _updateAssembler: function () { - let assembler = Sprite._assembler.getAssembler(this); - - if (this._assembler !== assembler) { - this._assembler = assembler; - this._renderData = null; - } - - if (!this._renderData) { - this._renderData = this._assembler.createData(this); - this._renderData.material = this._material; - this.markForUpdateRenderData(true); - } - }, - - _activateMaterial: function () { - let spriteFrame = this._spriteFrame; - - // WebGL - if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { - // Get material - let material; - if (this._state === State.GRAY) { - if (!this._graySpriteMaterial) { - this._graySpriteMaterial = new GraySpriteMaterial(); - } - material = this._graySpriteMaterial; - } - else { - if (!this._spriteMaterial) { - this._spriteMaterial = new SpriteMaterial(); - } - material = this._spriteMaterial; - } - // Set texture - if (spriteFrame && spriteFrame.textureLoaded()) { - let texture = spriteFrame.getTexture(); - if (material.texture !== texture) { - material.texture = texture; - this._updateMaterial(material); - } - else if (material !== this._material) { - this._updateMaterial(material); - } - if (this._renderData) { - this._renderData.material = material; - } - - this.node._renderFlag |= RenderFlow.FLAG_COLOR; - this.markForUpdateRenderData(true); - this.markForRender(true); - } - else { - this.disableRender(); - } - } - else { - this.markForUpdateRenderData(true); - this.markForRender(true); - } - }, - - _applyAtlas: CC_EDITOR && function (spriteFrame) { - // Set atlas - if (spriteFrame && spriteFrame._atlasUuid) { - var self = this; - cc.AssetLibrary.loadAsset(spriteFrame._atlasUuid, function (err, asset) { - self._atlas = asset; - }); - } else { - this._atlas = null; - } - }, - - _canRender () { - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - if (!this._enabled) return false; - } - else { - if (!this._enabled || !this._material) return false; - } - - let spriteFrame = this._spriteFrame; - if (!spriteFrame || !spriteFrame.textureLoaded()) { - return false; - } - return true; - }, - - markForUpdateRenderData (enable) { - if (enable && this._canRender()) { - this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - - let renderData = this._renderData; - if (renderData) { - renderData.uvDirty = true; - renderData.vertDirty = true; - } - } - else if (!enable) { - this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; - } - }, - - _applySpriteSize: function () { - if (this._spriteFrame) { - if (SizeMode.RAW === this._sizeMode) { - var size = this._spriteFrame.getOriginalSize(); - this.node.setContentSize(size); - } else if (SizeMode.TRIMMED === this._sizeMode) { - var rect = this._spriteFrame.getRect(); - this.node.setContentSize(rect.width, rect.height); - } - - this._activateMaterial(); - } - }, - - _onTextureLoaded: function () { - if (!this.isValid) { - return; - } - - this._applySpriteSize(); - }, - - _applySpriteFrame: function (oldFrame) { - if (oldFrame && oldFrame.off) { - oldFrame.off('load', this._onTextureLoaded, this); - } - - var spriteFrame = this._spriteFrame; - if (!spriteFrame || (this._material && this._material._texture) !== (spriteFrame && spriteFrame._texture)) { - // disable render flow until texture is loaded - this.markForRender(false); - } - - if (spriteFrame) { - if (!oldFrame || spriteFrame._texture !== oldFrame._texture) { - if (spriteFrame.textureLoaded()) { - this._onTextureLoaded(null); - } - else { - spriteFrame.once('load', this._onTextureLoaded, this); - spriteFrame.ensureLoadTexture(); - } - } - else { - this._applySpriteSize(); - } - } - - if (CC_EDITOR) { - // Set atlas - this._applyAtlas(spriteFrame); - } - }, - - _resized: CC_EDITOR && function () { - if (this._spriteFrame) { - var actualSize = this.node.getContentSize(); - var expectedW = actualSize.width; - var expectedH = actualSize.height; - if (this._sizeMode === SizeMode.RAW) { - var size = this._spriteFrame.getOriginalSize(); - expectedW = size.width; - expectedH = size.height; - } else if (this._sizeMode === SizeMode.TRIMMED) { - var rect = this._spriteFrame.getRect(); - expectedW = rect.width; - expectedH = rect.height; - - } - - if (expectedW !== actualSize.width || expectedH !== actualSize.height) { - this._sizeMode = SizeMode.CUSTOM; - } - } - }, -}); - -if (CC_EDITOR) { - // override __preload - Sprite.prototype.__superPreload = cc.Component.prototype.__preload; - Sprite.prototype.__preload = function () { - if (this.__superPreload) this.__superPreload(); - this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); - }; - // override onDestroy - Sprite.prototype.__superOnDestroy = cc.Component.prototype.onDestroy; - Sprite.prototype.onDestroy = function () { - if (this.__superOnDestroy) this.__superOnDestroy(); - this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); - }; -} - -cc.Sprite = module.exports = Sprite; diff --git a/cocos/2d/renderer/utils/label/bmfont.js b/cocos/2d/renderer/utils/label/bmfont.js index e05fad174d..7520f736bb 100644 --- a/cocos/2d/renderer/utils/label/bmfont.js +++ b/cocos/2d/renderer/utils/label/bmfont.js @@ -23,14 +23,19 @@ THE SOFTWARE. ****************************************************************************/ -const macro = require('../../../platform/CCMacro'); +// const macro = require('../../../platform/CCMacro'); + +// const Label = require('../../../components/CCLabel'); +// const Overflow = Label.Overflow; + +// const textUtils = require('../../../utils/text-utils'); +import macro from '../../../../core/platform/CCMacro'; +import Label from '../../../../3d/ui/components/label-component'; +import textUtils from '../../../../core/utils/text-utils'; -const Label = require('../../../components/CCLabel'); const Overflow = Label.Overflow; -const textUtils = require('../../../utils/text-utils'); - -let FontLetterDefinition = function() { +let FontLetterDefinition = function () { this._u = 0; this._v = 0; this._width = 0; @@ -42,16 +47,16 @@ let FontLetterDefinition = function() { this._xAdvance = 0; }; -cc.FontAtlas = function (fntConfig) { - this._letterDefinitions = {}; -}; +class FontAtlas { + constructor(fntConfig) { + this._letterDefinitions = {}; + } -cc.FontAtlas.prototype = { - constructor: cc.FontAtlas, - addLetterDefinitions: function(letter, letterDefinition) { + addLetterDefinitions(letter, letterDefinition) { this._letterDefinitions[letter] = letterDefinition; - }, - cloneLetterDefinition: function() { + } + + cloneLetterDefinition() { let copyLetterDefinitions = {}; for (let key in this._letterDefinitions) { let value = new FontLetterDefinition(); @@ -59,15 +64,17 @@ cc.FontAtlas.prototype = { copyLetterDefinitions[key] = value; } return copyLetterDefinitions; - }, - assignLetterDefinitions: function(letterDefinition) { + } + + assignLetterDefinitions(letterDefinition) { for (let key in this._letterDefinitions) { let newValue = letterDefinition[key]; let oldValue = this._letterDefinitions[key]; cc.js.mixin(oldValue, newValue); } - }, - scaleFontLetterDefinition: function(scaleFactor) { + } + + scaleFontLetterDefinition(scaleFactor) { for (let fontDefinition in this._letterDefinitions) { let letterDefinitions = this._letterDefinitions[fontDefinition]; letterDefinitions._width *= scaleFactor; @@ -76,8 +83,9 @@ cc.FontAtlas.prototype = { letterDefinitions._offsetY *= scaleFactor; letterDefinitions._xAdvance *= scaleFactor; } - }, - getLetterDefinitionForChar: function(char) { + } + + getLetterDefinitionForChar(char) { let hasKey = this._letterDefinitions.hasOwnProperty(char.charCodeAt(0)); let letterDefinition; if (hasKey) { @@ -87,9 +95,11 @@ cc.FontAtlas.prototype = { } return letterDefinition; } -}; +} -let LetterInfo = function() { +cc.FontAtlas = FontAtlas; + +let LetterInfo = function () { this._char = ''; this._valid = true; this._positionX = 0; @@ -110,12 +120,12 @@ let _labelDimensions = cc.size(); let _fontAtlas = null; let _fntConfig = null; let _numberOfLines = 0; -let _textDesiredHeight = 0; -let _letterOffsetY = 0; -let _tailoredTopY = 0; -let _tailoredBottomY = 0; -let _bmfontScale = 1.0; -let _lineBreakWithoutSpaces = false; +let _textDesiredHeight = 0; +let _letterOffsetY = 0; +let _tailoredTopY = 0; +let _tailoredBottomY = 0; +let _bmfontScale = 1.0; +let _lineBreakWithoutSpaces = false; let _spriteFrame = null; let _lineSpacing = 0; let _string = ''; @@ -132,39 +142,39 @@ let _labelWidth = 0; let _labelHeight = 0; let _maxLineWidth = 0; -module.exports = { - updateRenderData (comp) { +let bmfont = { + updateRenderData(comp) { if (!comp._renderData.vertDirty) return; if (_comp === comp) return; _comp = comp; - + this._updateProperties(); this._updateContent(); - + _comp._actualFontSize = _fontSize; _comp.node.setContentSize(_contentSize); _comp._renderData.vertDirty = _comp._renderData.uvDirty = false; _comp = null; - + this._resetProperties(); }, - _updateFontScale () { + _updateFontScale() { _bmfontScale = _fontSize / _originFontSize; }, - _updateProperties () { + _updateProperties() { let fontAsset = _comp.font; _spriteFrame = fontAsset.spriteFrame; _fntConfig = fontAsset._fntConfig; _fontAtlas = _comp._fontAtlas; if (!_fontAtlas) { - _fontAtlas = new cc.FontAtlas(_fntConfig); - + _fontAtlas = new FontAtlas(_fntConfig); + let fontDict = _fntConfig.fontDefDictionary; for (let fontDef in fontDict) { @@ -199,7 +209,7 @@ module.exports = { _spacingX = _comp.spacingX; _overflow = _comp.overflow; _lineHeight = _comp._lineHeight; - + // should wrap text if (_overflow === Overflow.NONE) { _isWrapText = false; @@ -214,19 +224,19 @@ module.exports = { this._setupBMFontOverflowMetrics(); }, - _resetProperties () { + _resetProperties() { _fontAtlas = null; _fntConfig = null; _spriteFrame = null; }, - _updateContent () { + _updateContent() { this._updateFontScale(); this._computeHorizontalKerningForText(); this._alignText(); }, - _computeHorizontalKerningForText () { + _computeHorizontalKerningForText() { let string = _string; let stringLen = string.length; @@ -246,7 +256,7 @@ module.exports = { } }, - _multilineTextWrap: function(nextTokenFunc) { + _multilineTextWrap(nextTokenFunc) { let textLen = _string.length; let lineIndex = 0; @@ -384,11 +394,11 @@ module.exports = { return true; }, - _getFirstCharLen: function() { + _getFirstCharLen() { return 1; }, - _getFirstWordLen: function(text, startIndex, textLen) { + _getFirstWordLen(text, startIndex, textLen) { let character = text.charAt(startIndex); if (textUtils.isUnicodeCJK(character) || character === "\n" @@ -412,9 +422,9 @@ module.exports = { } letterX = nextLetterX + letterDef._offsetX * _bmfontScale; - if(letterX + letterDef._width * _bmfontScale > _maxLineWidth - && !textUtils.isUnicodeSpace(character) - && _maxLineWidth > 0) { + if (letterX + letterDef._width * _bmfontScale > _maxLineWidth + && !textUtils.isUnicodeSpace(character) + && _maxLineWidth > 0) { return len; } nextLetterX += letterDef._xAdvance * _bmfontScale + _spacingX; @@ -429,15 +439,15 @@ module.exports = { return len; }, - _multilineTextWrapByWord: function() { + _multilineTextWrapByWord() { return this._multilineTextWrap(this._getFirstWordLen); }, - _multilineTextWrapByChar: function() { + _multilineTextWrapByChar() { return this._multilineTextWrap(this._getFirstCharLen); }, - _recordPlaceholderInfo: function(letterIndex, char) { + _recordPlaceholderInfo(letterIndex, char) { if (letterIndex >= _lettersInfo.length) { let tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); @@ -447,7 +457,7 @@ module.exports = { _lettersInfo[letterIndex]._valid = false; }, - _recordLetterInfo: function(letterDefinitions, letterPosition, character, letterIndex, lineIndex) { + _recordLetterInfo(letterDefinitions, letterPosition, character, letterIndex, lineIndex) { if (letterIndex >= _lettersInfo.length) { let tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); @@ -461,7 +471,7 @@ module.exports = { _lettersInfo[letterIndex]._positionY = letterPosition.y; }, - _alignText: function() { + _alignText() { _textDesiredHeight = 0; _linesWidth.length = 0; @@ -487,7 +497,7 @@ module.exports = { } }, - _scaleFontSizeDown (fontSize) { + _scaleFontSizeDown(fontSize) { let shouldUpdateContent = true; if (!fontSize) { fontSize = 0.1; @@ -500,11 +510,11 @@ module.exports = { } }, - _shrinkLabelToContentSize (lambda) { + _shrinkLabelToContentSize(lambda) { let fontSize = _fontSize; let originalLineHeight = _lineHeight; let fontAtlas = _fontAtlas; - + let i = 0; let tempLetterDefinition = fontAtlas.cloneLetterDefinition(); let flag = true; @@ -540,7 +550,7 @@ module.exports = { } }, - _isVerticalClamp () { + _isVerticalClamp() { if (_textDesiredHeight > _contentSize.height) { return true; } else { @@ -548,7 +558,7 @@ module.exports = { } }, - _isHorizontalClamp () { + _isHorizontalClamp() { let letterDefinitions = _fontAtlas._letterDefinitions; let letterClamp = false; for (let ctr = 0, l = _string.length; ctr < l; ++ctr) { @@ -560,11 +570,11 @@ module.exports = { let lineIndex = letterInfo._lineIndex; if (_labelWidth > 0) { if (!_isWrapText) { - if(px > _contentSize.width){ + if (px > _contentSize.width) { letterClamp = true; break; } - }else{ + } else { let wordWidth = _linesWidth[lineIndex]; if (wordWidth > _contentSize.width && (px > _contentSize.width || px < 0)) { letterClamp = true; @@ -578,20 +588,20 @@ module.exports = { return letterClamp; }, - _isHorizontalClamped (px, lineIndex) { + _isHorizontalClamped(px, lineIndex) { let wordWidth = _linesWidth[lineIndex]; let letterOverClamp = (px > _contentSize.width || px < 0); - if(!_isWrapText){ + if (!_isWrapText) { return letterOverClamp; - }else{ + } else { return (wordWidth > _contentSize.width && letterOverClamp); } }, - _updateQuads () { + _updateQuads() { let letterDefinitions = _fontAtlas._letterDefinitions; - + let texture = _spriteFrame._texture; let node = _comp.node; @@ -601,7 +611,7 @@ module.exports = { let contentSize = _contentSize, appx = node._anchorPoint.x * contentSize.width, appy = node._anchorPoint.y * contentSize.height; - + let ret = true; for (let ctr = 0, l = _string.length; ctr < l; ++ctr) { let letterInfo = _lettersInfo[ctr]; @@ -655,7 +665,7 @@ module.exports = { let trimmedLeft = offset.x + (originalSize.width - rect.width) / 2; let trimmedTop = offset.y - (originalSize.height - rect.height) / 2; - if(!isRotated) { + if (!isRotated) { _tmpRect.x += (rect.x - trimmedLeft); _tmpRect.y += (rect.y + trimmedTop); } else { @@ -675,12 +685,12 @@ module.exports = { return ret; }, - appendQuad (renderData, texture, rect, rotated, x, y, scale) { + appendQuad(renderData, texture, rect, rotated, x, y, scale) { }, - _computeAlignmentOffset: function() { + _computeAlignmentOffset() { _linesOffsetX.length = 0; - + switch (_hAlign) { case macro.TextAlignment.LEFT: for (let i = 0; i < _numberOfLines; ++i) { @@ -716,7 +726,7 @@ module.exports = { } }, - _setupBMFontOverflowMetrics () { + _setupBMFontOverflowMetrics() { let newWidth = _contentSize.width, newHeight = _contentSize.height; @@ -736,3 +746,5 @@ module.exports = { _maxLineWidth = newWidth; } }; + +export default bmfont; diff --git a/cocos/2d/renderer/utils/label/ttf.js b/cocos/2d/renderer/utils/label/ttf.js index 1c4e9b5611..2adb5d0709 100644 --- a/cocos/2d/renderer/utils/label/ttf.js +++ b/cocos/2d/renderer/utils/label/ttf.js @@ -23,14 +23,13 @@ THE SOFTWARE. ****************************************************************************/ -const macro = require('../../../platform/CCMacro'); -const textUtils = require('../../../utils/text-utils'); - -const Component = require('../../../components/CCComponent'); -const Label = require('../../../components/CCLabel'); -const LabelOutline = require('../../../components/CCLabelOutline'); -const Overflow = Label.Overflow; +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'; +const Overflow = LabelComponent.Overflow; const WHITE = cc.Color.WHITE; const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component); @@ -67,7 +66,7 @@ let _sharedLabelData; // let _canvasPool = { pool: [], - get () { + get() { let data = this.pool.pop(); if (!data) { @@ -81,7 +80,7 @@ let _canvasPool = { return data; }, - put (canvas) { + put(canvas) { if (this.pool.length >= 32) { return; } @@ -90,32 +89,31 @@ let _canvasPool = { }; -module.exports = { - - _getAssemblerData () { - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - _sharedLabelData = _canvasPool.get(); - } - else { - if (!_sharedLabelData) { - let labelCanvas = document.createElement("canvas"); - _sharedLabelData = { - canvas: labelCanvas, - context: labelCanvas.getContext("2d") - }; - } - } - _sharedLabelData.canvas.width = _sharedLabelData.canvas.height = 1; - return _sharedLabelData; +export default { + _getAssemblerData() { + // if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { + // _sharedLabelData = _canvasPool.get(); + // } + // else { + // if (!_sharedLabelData) { + let labelCanvas = document.createElement("canvas"); + let sharedLabelData = { + canvas: labelCanvas, + context: labelCanvas.getContext("2d") + }; + // } + // } + sharedLabelData.canvas.width = sharedLabelData.canvas.height = 1; + return sharedLabelData; }, - _resetAssemblerData (assemblerData) { + _resetAssemblerData(assemblerData) { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS && assemblerData) { _canvasPool.put(assemblerData); } }, - updateRenderData (comp) { + updateRenderData(comp) { if (!comp._renderData.vertDirty) return; this._updateFontFamly(comp); @@ -138,10 +136,10 @@ module.exports = { _texture = null; }, - _updateVerts () { + _updateVerts() { }, - _updateFontFamly (comp) { + _updateFontFamly(comp) { if (!comp.useSystemFont) { if (comp.font) { if (comp.font._nativeAsset) { @@ -163,12 +161,12 @@ module.exports = { } }, - _updateProperties (comp) { + _updateProperties(comp) { let assemblerData = comp._assemblerData; _context = assemblerData.context; _canvas = assemblerData.canvas; _texture = comp._texture; - + _string = comp.string.toString(); _fontSize = comp._fontSize; _drawFontsize = _fontSize; @@ -178,7 +176,7 @@ module.exports = { _lineHeight = comp._lineHeight; _hAlign = comp.horizontalAlign; _vAlign = comp.verticalAlign; - _color = comp.node.color; + _color = comp._color; _isBold = comp._isBold; _isItalic = comp._isItalic; _isUnderline = comp._isUnderline; @@ -208,7 +206,7 @@ module.exports = { } }, - _calculateFillTextStartPosition () { + _calculateFillTextStartPosition() { let lineHeight = this._getLineHeight(); let lineCount = _splitedStrings.length; let labelX; @@ -237,7 +235,7 @@ module.exports = { return cc.v2(labelX, firstLinelabelY); }, - _updateTexture () { + _updateTexture() { _context.clearRect(0, 0, _canvas.width, _canvas.height); _context.font = _fontDesc; @@ -271,10 +269,11 @@ module.exports = { } } - _texture.handleLoadedTexture(); + // _texture.handleLoadedTexture(); + _texture.mipmaps = [_texture.image]; }, - _calculateUnderlineStartPosition () { + _calculateUnderlineStartPosition() { let lineHeight = this._getLineHeight(); let lineCount = _splitedStrings.length; let labelX; @@ -295,7 +294,7 @@ module.exports = { return cc.v2(labelX, firstLinelabelY); }, - _updateLabelDimensions () { + _updateLabelDimensions() { let paragraphedStrings = _string.split('\n'); if (_overflow === Overflow.RESIZE_HEIGHT) { @@ -323,7 +322,7 @@ module.exports = { _canvas.height = _canvasSize.height; }, - _calculateTextBaseline () { + _calculateTextBaseline() { let node = this._node; let hAlign; let vAlign; @@ -351,7 +350,7 @@ module.exports = { _context.textBaseline = vAlign; }, - _calculateSplitedStrings () { + _calculateSplitedStrings() { let paragraphedStrings = _string.split('\n'); if (_isWrapText) { @@ -360,9 +359,9 @@ module.exports = { for (let i = 0; i < paragraphedStrings.length; ++i) { let allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i]); let textFragment = textUtils.fragmentText(paragraphedStrings[i], - allWidth, - canvasWidthNoMargin, - this._measureText(_context)); + allWidth, + canvasWidthNoMargin, + this._measureText(_context)); _splitedStrings = _splitedStrings.concat(textFragment); } } @@ -372,7 +371,7 @@ module.exports = { }, - _getFontDesc () { + _getFontDesc() { let fontDesc = _fontSize.toString() + 'px '; fontDesc = fontDesc + _fontFamily; if (_isBold) { @@ -382,7 +381,7 @@ module.exports = { return fontDesc; }, - _getLineHeight () { + _getLineHeight() { let nodeSpacingY = _lineHeight; if (nodeSpacingY === 0) { nodeSpacingY = _fontSize; @@ -393,7 +392,7 @@ module.exports = { return nodeSpacingY | 0; }, - _calculateParagraphLength (paragraphedStrings, ctx) { + _calculateParagraphLength(paragraphedStrings, ctx) { let paragraphLength = []; for (let i = 0; i < paragraphedStrings.length; ++i) { @@ -404,20 +403,20 @@ module.exports = { return paragraphLength; }, - _measureText (ctx) { + _measureText(ctx) { return function (string) { return textUtils.safeMeasureText(ctx, string); }; }, - _calculateLabelFont () { + _calculateLabelFont() { _fontDesc = this._getFontDesc(); _context.font = _fontDesc; if (_overflow === Overflow.SHRINK) { let paragraphedStrings = _string.split('\n'); let paragraphLength = this._calculateParagraphLength(paragraphedStrings, _context); - + _splitedStrings = paragraphedStrings; let i = 0; let totalHeight = 0; @@ -459,9 +458,9 @@ module.exports = { let j = 0; let allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i]); textFragment = textUtils.fragmentText(paragraphedStrings[i], - allWidth, - canvasWidthNoMargin, - this._measureText(_context)); + allWidth, + canvasWidthNoMargin, + this._measureText(_context)); while (j < textFragment.length) { let measureWidth = textUtils.safeMeasureText(_context, textFragment[j]); maxLength = measureWidth; diff --git a/cocos/2d/renderer/webgl/assemblers/label/ttf.js b/cocos/2d/renderer/webgl/assemblers/label/ttf.js deleted file mode 100644 index 0d980acdc1..0000000000 --- a/cocos/2d/renderer/webgl/assemblers/label/ttf.js +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const js = require('../../../../platform/js'); -const ttfUtls = require('../../../utils/label/ttf'); - -module.exports = js.addon({ - createData (comp) { - let renderData = comp.requestRenderData(); - - renderData.dataLength = 4; - renderData.vertexCount = 4; - renderData.indiceCount = 6; - - let data = renderData._data; - data[0].u = 0; - data[0].v = 1; - data[1].u = 1; - data[1].v = 1; - data[2].u = 0; - data[2].v = 0; - data[3].u = 1; - data[3].v = 0; - return renderData; - }, - - fillBuffers (comp, renderer) { - let data = comp._renderData._data, - node = comp.node, - matrix = node._worldMatrix, - a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2; - - buffer.request(4, 6); - - // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData; - - // vertex - for (let i = 0; i < 4; i++) { - let vert = data[i]; - vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; - vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; - vbuf[vertexOffset++] = vert.u; - vbuf[vertexOffset++] = vert.v; - } - }, - - _updateVerts (comp) { - let renderData = comp._renderData; - - let node = comp.node, - width = node.width, - height = node.height, - appx = node.anchorX * width, - appy = node.anchorY * height; - - let data = renderData._data; - data[0].x = -appx; - data[0].y = -appy; - data[1].x = width - appx; - data[1].y = -appy; - data[2].x = -appx; - data[2].y = height - appy; - data[3].x = width - appx; - data[3].y = height - appy; - } -}, ttfUtls); diff --git a/cocos/2d/renderer/webgl/assemblers/mask-assembler.js b/cocos/2d/renderer/webgl/assemblers/mask-assembler.js deleted file mode 100644 index f73ebd73dc..0000000000 --- a/cocos/2d/renderer/webgl/assemblers/mask-assembler.js +++ /dev/null @@ -1,144 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const StencilManager = require('../stencil-manager'); -const Node = require('../../../CCNode'); -const Mask = require('../../../components/CCMask'); -const Graphics = require('../../../graphics/graphics'); -const RenderFlow = require('../../render-flow'); - -const spriteAssembler = require('./sprite/simple'); -const graphicsAssembler = require('./graphics'); - -let _stencilMgr = StencilManager.sharedManager; -// for nested mask, we might need multiple graphics component to avoid data conflict -let _graphicsPool = []; -let _graphicsUsing = []; - -function getGraphics () { - let graphics = _graphicsPool.pop(); - - if (!graphics) { - let graphicsNode = new Node(); - graphics = graphicsNode.addComponent(Graphics); - graphics._activateMaterial(); - graphics.lineWidth = 0; - graphics.rect(0, 0, cc.visibleRect.width, cc.visibleRect.height); - graphics.fill(); - graphicsAssembler.updateRenderData(graphics); - } - return graphics; -} - -let maskFrontAssembler = { - updateRenderData (mask) { - if (!mask._renderData) { - if (mask._type === Mask.Type.IMAGE_STENCIL) { - mask._renderData = spriteAssembler.createData(mask); - } - else { - // for updateGraphics calculation - mask._renderData = mask.requestRenderData(); - } - } - let renderData = mask._renderData; - - if (mask._type === Mask.Type.IMAGE_STENCIL) { - if (mask.spriteFrame) { - let size = mask.node._contentSize; - let anchor = mask.node._anchorPoint; - renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); - renderData.dataLength = 4; - spriteAssembler.updateRenderData(mask); - renderData.material = mask._material; - } - else { - mask._material = null; - } - } - else { - mask._graphics._material = mask._material; - graphicsAssembler.updateRenderData(mask._graphics); - } - }, - - fillBuffers (mask, renderer) { - // Invalid state - if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) { - // HACK: Must push mask after batch, so we can only put this logic in fillVertexBuffer or fillIndexBuffer - _stencilMgr.pushMask(mask); - _stencilMgr.clear(); - - mask._clearGraphics = getGraphics(); - graphicsAssembler.fillBuffers(mask._clearGraphics, renderer); - - _stencilMgr.enterLevel(); - - // vertex buffer - renderer.node = mask.node; - renderer.material = mask._material; - if (mask._type === Mask.Type.IMAGE_STENCIL) { - spriteAssembler.fillBuffers(mask, renderer); - renderer._flush(); - } - else { - graphicsAssembler.fillBuffers(mask._graphics, renderer); - } - } - - mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - } -}; - -let maskEndAssembler = { - fillBuffers (mask, renderer) { - // Invalid state - if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) { - // HACK: Must pop mask after batch, so we can only put this logic in fillBuffers - _stencilMgr.exitMask(); - - _graphicsUsing.push(mask._clearGraphics); - mask._clearGraphics = null; - - // Clear graphics can only be recycled after the mask stack exits entirely. - if (_stencilMgr.stage === StencilManager.Stage.DISABLED) { - for (let i = 0; i < _graphicsUsing.length; i++) { - _graphicsPool.push(_graphicsUsing[i]); - } - _graphicsUsing.length = 0; - } - } - - mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - } -}; - -Mask._assembler = maskFrontAssembler; -Mask._postAssembler = maskEndAssembler; - -module.exports = { - front: maskFrontAssembler, - end: maskEndAssembler -} \ No newline at end of file diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js b/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js deleted file mode 100644 index 474fe24380..0000000000 --- a/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js +++ /dev/null @@ -1,248 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const Sprite = require('../../../../components/CCSprite'); -const FillType = Sprite.FillType; - -const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); - -module.exports = { - useModel: false, - updateRenderData (sprite) { - let frame = sprite.spriteFrame; - - // TODO: Material API design and export from editor could affect the material activation process - // need to update the logic here - if (frame) { - if (!frame._original && dynamicAtlasManager) { - dynamicAtlasManager.insertSpriteFrame(frame); - } - if (sprite._material._texture !== frame._texture) { - sprite._activateMaterial(); - } - } - - let renderData = sprite._renderData; - if (renderData && frame) { - let uvDirty = renderData.uvDirty, - vertDirty = renderData.vertDirty; - - if (!uvDirty && !vertDirty) { - return sprite.__allocedDatas; - } - - let fillStart = sprite._fillStart; - let fillRange = sprite._fillRange; - - if (fillRange < 0) { - fillStart += fillRange; - fillRange = -fillRange; - } - - fillRange = fillStart + fillRange; - - fillStart = fillStart > 1.0 ? 1.0 : fillStart; - fillStart = fillStart < 0.0 ? 0.0 : fillStart; - - fillRange = fillRange > 1.0 ? 1.0 : fillRange; - fillRange = fillRange < 0.0 ? 0.0 : fillRange; - fillRange = fillRange - fillStart; - fillRange = fillRange < 0 ? 0 : fillRange; - - let fillEnd = fillStart + fillRange; - fillEnd = fillEnd > 1 ? 1 : fillEnd; - - if (uvDirty) { - this.updateUVs(sprite, fillStart, fillEnd); - } - if (vertDirty) { - this.updateVerts(sprite, fillStart, fillEnd); - this.updateWorldVerts(sprite); - } - } - }, - - updateUVs (sprite, fillStart, fillEnd) { - let spriteFrame = sprite._spriteFrame, - renderData = sprite._renderData, - data = renderData._data; - - //build uvs - let atlasWidth = spriteFrame._texture.width; - let atlasHeight = spriteFrame._texture.height; - let textureRect = spriteFrame._rect; - //uv computation should take spritesheet into account. - let ul, vb, ur, vt; - let quadUV0, quadUV1, quadUV2, quadUV3, quadUV4, quadUV5, quadUV6, quadUV7; - if (spriteFrame._rotated) { - ul = (textureRect.x) / atlasWidth; - vb = (textureRect.y + textureRect.width) / atlasHeight; - ur = (textureRect.x + textureRect.height) / atlasWidth; - vt = (textureRect.y) / atlasHeight; - - quadUV0 = quadUV2 = ul; - quadUV4 = quadUV6 = ur; - quadUV3 = quadUV7 = vb; - quadUV1 = quadUV5 = vt; - } - else { - ul = (textureRect.x) / atlasWidth; - vb = (textureRect.y + textureRect.height) / atlasHeight; - ur = (textureRect.x + textureRect.width) / atlasWidth; - vt = (textureRect.y) / atlasHeight; - - quadUV0 = quadUV4 = ul; - quadUV2 = quadUV6 = ur; - quadUV1 = quadUV3 = vb; - quadUV5 = quadUV7 = vt; - } - - switch (sprite._fillType) { - case FillType.HORIZONTAL: - data[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart; - data[0].v = quadUV1; - data[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd; - data[1].v = quadUV3; - data[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart; - data[2].v = quadUV5; - data[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd; - data[3].v = quadUV7; - break; - case FillType.VERTICAL: - data[0].u = quadUV0; - data[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart; - data[1].u = quadUV2; - data[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart; - data[2].u = quadUV4; - data[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd; - data[3].u = quadUV6; - data[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd; - break; - default: - cc.errorID(2626); - break; - } - - renderData.uvDirty = false; - }, - - updateVerts (sprite, fillStart, fillEnd) { - let renderData = sprite._renderData, - data = renderData._data, - node = sprite.node, - width = node.width, height = node.height, - appx = node.anchorX * width, appy = node.anchorY * height; - - let l = -appx, b = -appy, - r = width-appx, t = height-appy; - - let progressStart, progressEnd; - switch (sprite._fillType) { - case FillType.HORIZONTAL: - progressStart = l + (r - l) * fillStart; - progressEnd = l + (r - l) * fillEnd; - - l = progressStart; - r = progressEnd; - break; - case FillType.VERTICAL: - progressStart = b + (t - b) * fillStart; - progressEnd = b + (t - b) * fillEnd; - - b = progressStart; - t = progressEnd; - break; - default: - cc.errorID(2626); - break; - } - - data[4].x = l; - data[4].y = b; - data[5].x = r; - data[5].y = b; - data[6].x = l; - data[6].y = t; - data[7].x = r; - data[7].y = t; - - renderData.vertDirty = false; - }, - - createData (sprite) { - let renderData = sprite.requestRenderData(); - // 0-4 for world verts - // 5-8 for local verts - renderData.dataLength = 8; - renderData.vertexCount = 4; - renderData.indiceCount = 6; - return renderData; - }, - - updateWorldVerts (sprite) { - let node = sprite.node, - data = sprite._renderData._data; - - let matrix = node._worldMatrix, - a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - for (let i = 0; i < 4; i++) { - let local = data[i+4]; - let world = data[i]; - world.x = local.x * a + local.y * c + tx; - world.y = local.x * b + local.y * d + ty; - } - }, - - fillBuffers (sprite, renderer) { - if (renderer.worldMatDirty) { - this.updateWorldVerts(sprite); - } - - let data = sprite._renderData._data, - node = sprite.node, - matrix = node._worldMatrix, - a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2; - - buffer.request(4, 6); - - // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData; - - // vertex - for (let i = 0; i < 4; i++) { - let vert = data[i]; - vbuf[vertexOffset++] = vert.x; - vbuf[vertexOffset++] = vert.y; - vbuf[vertexOffset++] = vert.u; - vbuf[vertexOffset++] = vert.v; - } - } -}; diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/radial-filled.js b/cocos/2d/renderer/webgl/assemblers/sprite/radial-filled.js deleted file mode 100644 index 3dca7ed1ef..0000000000 --- a/cocos/2d/renderer/webgl/assemblers/sprite/radial-filled.js +++ /dev/null @@ -1,364 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); - -const PI_2 = Math.PI * 2; - -module.exports = { - useModel: false, - - _vertPos: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)], - _vertices: [0, 0, 0, 0], - _uvs: [0, 0, 0, 0, 0, 0, 0, 0], - _intersectPoint_1: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)], - _intersectPoint_2: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)], - _center: cc.v2(0, 0), - _triangles: [], - - createData (sprite) { - return sprite.requestRenderData(); - }, - - updateRenderData (sprite) { - let frame = sprite.spriteFrame; - - // TODO: Material API design and export from editor could affect the material activation process - // need to update the logic here - if (frame) { - if (!frame._original && dynamicAtlasManager) { - dynamicAtlasManager.insertSpriteFrame(frame); - } - if (sprite._material._texture !== frame._texture) { - sprite._activateMaterial(); - } - } - - let renderData = sprite._renderData; - if (renderData && frame) { - if (renderData.vertDirty || renderData.uvDirty) { - let data = renderData._data; - - let fillStart = sprite._fillStart; - let fillRange = sprite._fillRange; - if (fillRange < 0) { - fillStart += fillRange; - fillRange = -fillRange; - } - - //do round fill start [0,1), include 0, exclude 1 - while (fillStart >= 1.0) fillStart -= 1.0; - while (fillStart < 0.0) fillStart += 1.0; - - fillStart *= PI_2; - fillRange *= PI_2; - let fillEnd = fillStart + fillRange; - - //build vertices - this._calculateVertices(sprite); - //build uvs - this._calculateUVs(frame); - - let center = this._center; - - let vertPos = this._vertPos, - vertices = this._vertices; - - let triangles = this._triangles; - - this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart, this._intersectPoint_1); - this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart + fillRange, this._intersectPoint_2); - - let offset = 0; - for (let triangleIndex = 0; triangleIndex < 4; ++triangleIndex) { - let triangle = triangles[triangleIndex]; - if (!triangle) { - continue; - } - //all in - if (fillRange >= PI_2) { - renderData.dataLength = offset + 3; - this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); - offset += 3; - continue; - } - //test against - let startAngle = this._getVertAngle(center, vertPos[triangle[0]]); - let endAngle = this._getVertAngle(center, vertPos[triangle[1]]); - if(endAngle < startAngle) endAngle += PI_2; - startAngle -= PI_2; - endAngle -= PI_2; - //testing - for(let testIndex = 0; testIndex < 3; ++testIndex) { - if(startAngle >= fillEnd) { - //all out - } else if (startAngle >= fillStart) { - renderData.dataLength = offset + 3; - if(endAngle >= fillEnd) { - //startAngle to fillEnd - this._generateTriangle(data, offset, center, vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]); - } else { - //startAngle to endAngle - this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); - } - offset += 3; - } else { - //startAngle < fillStart - if(endAngle <= fillStart) { - //all out - } else if(endAngle <= fillEnd) { - renderData.dataLength = offset + 3; - //fillStart to endAngle - this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], vertPos[triangle[1]]); - offset += 3; - } else { - renderData.dataLength = offset + 3; - //fillStart to fillEnd - this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]); - offset += 3; - } - } - //add 2 * PI - startAngle += PI_2; - endAngle += PI_2; - } - } - - renderData.indiceCount = renderData.vertexCount = offset; - renderData.vertDirty = renderData.uvDirty = false; - } - } - }, - - _getVertAngle: function(start, end) { - let placementX, placementY; - placementX = end.x - start.x; - placementY = end.y - start.y; - - if(placementX === 0 && placementY === 0) { - return undefined; - } else if(placementX === 0) { - if(placementY > 0) { - return Math.PI * 0.5; - } else { - return Math.PI * 1.5; - } - } else { - let angle = Math.atan(placementY / placementX); - if(placementX < 0) { - angle += Math.PI; - } - - return angle; - } - }, - - _generateTriangle: function(data, offset, vert0, vert1, vert2) { - let vertices = this._vertices; - let v0x = vertices[0]; - let v0y = vertices[1]; - let v1x = vertices[2]; - let v1y = vertices[3]; - - data[offset].x = vert0.x; - data[offset].y = vert0.y; - data[offset+1].x = vert1.x; - data[offset+1].y = vert1.y; - data[offset+2].x = vert2.x; - data[offset+2].y = vert2.y; - - let progressX, progressY; - progressX = (vert0.x - v0x) / (v1x - v0x); - progressY = (vert0.y - v0y) / (v1y - v0y); - this._generateUV(progressX, progressY, data, offset); - - progressX = (vert1.x - v0x) / (v1x - v0x); - progressY = (vert1.y - v0y) / (v1y - v0y); - this._generateUV(progressX, progressY, data, offset + 1); - - progressX = (vert2.x - v0x) / (v1x - v0x); - progressY = (vert2.y - v0y) / (v1y - v0y); - this._generateUV(progressX, progressY, data, offset + 2); - }, - - _generateUV : function(progressX, progressY, data, offset) { - let uvs = this._uvs; - let px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX; - let px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX; - let py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX; - let py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX; - let uv = data[offset]; - uv.u = px1 + (px2 - px1) * progressY; - uv.v = py1 + (py2 - py1) * progressY; - }, - - _calcInsectedPoints: function(left, right, bottom, top, center, angle, intersectPoints) { - //left bottom, right, top - let sinAngle = Math.sin(angle); - let cosAngle = Math.cos(angle); - let tanAngle,cotAngle; - if(Math.cos(angle) !== 0) { - tanAngle = sinAngle / cosAngle; - //calculate right and left - if((left - center.x) * cosAngle > 0) { - let yleft = center.y + tanAngle * (left - center.x); - intersectPoints[0].x = left; - intersectPoints[0].y = yleft; - } - if((right - center.x) * cosAngle > 0) { - let yright = center.y + tanAngle * (right - center.x); - - intersectPoints[2].x = right; - intersectPoints[2].y = yright; - } - - } - - if(Math.sin(angle) !== 0) { - cotAngle = cosAngle / sinAngle; - //calculate top and bottom - if((top - center.y) * sinAngle > 0) { - let xtop = center.x + cotAngle * (top-center.y); - intersectPoints[3].x = xtop; - intersectPoints[3].y = top; - } - if((bottom - center.y) * sinAngle > 0) { - let xbottom = center.x + cotAngle * (bottom-center.y); - intersectPoints[1].x = xbottom; - intersectPoints[1].y = bottom; - } - - } - }, - - _calculateVertices : function (sprite) { - let node = sprite.node, - width = node.width, height = node.height, - appx = node.anchorX * width, appy = node.anchorY * height; - - let l = -appx, b = -appy, - r = width-appx, t = height-appy; - - let vertices = this._vertices; - vertices[0] = l; - vertices[1] = b; - vertices[2] = r; - vertices[3] = t; - - let center = this._center, - fillCenter = sprite._fillCenter, - cx = center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r-l) + l, - cy = center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t-b) + b; - - let vertPos = this._vertPos; - vertPos[0].x = vertPos[3].x = l; - vertPos[1].x = vertPos[2].x = r; - vertPos[0].y = vertPos[1].y = b; - vertPos[2].y = vertPos[3].y = t; - - let triangles = this._triangles; - triangles.length = 0; - if(cx !== vertices[0]) { - triangles[0] = [3, 0]; - } - if(cx !== vertices[2]) { - triangles[2] = [1, 2]; - } - if(cy !== vertices[1]) { - triangles[1] = [0, 1]; - } - if(cy !== vertices[3]) { - triangles[3] = [2, 3]; - } - }, - - _calculateUVs : function (spriteFrame) { - let atlasWidth = spriteFrame._texture.width; - let atlasHeight = spriteFrame._texture.height; - let textureRect = spriteFrame._rect; - - let u0, u1, v0, v1; - let uvs = this._uvs; - - if (spriteFrame._rotated) { - u0 = (textureRect.x) / atlasWidth; - u1 = (textureRect.x + textureRect.height) / atlasWidth; - - v0 = (textureRect.y) / atlasHeight; - v1 = (textureRect.y + textureRect.width) / atlasHeight; - - uvs[0] = uvs[2] = u0; - uvs[4] = uvs[6] = u1; - uvs[3] = uvs[7] = v1; - uvs[1] = uvs[5] = v0; - } - else { - u0 = (textureRect.x) / atlasWidth; - u1 = (textureRect.x + textureRect.width) / atlasWidth; - - v0 = (textureRect.y) / atlasHeight; - v1 = (textureRect.y + textureRect.height) / atlasHeight; - - uvs[0] = uvs[4] = u0; - uvs[2] = uvs[6] = u1; - uvs[1] = uvs[3] = v1; - uvs[5] = uvs[7] = v0; - } - }, - - fillBuffers (sprite, renderer) { - let renderData = sprite._renderData, - data = renderData._data, - node = sprite.node; - - let matrix = node._worldMatrix, - a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - // buffer - let buffer = renderer._meshBuffer, - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData; - - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, - vertexId = buffer.vertexOffset; - - buffer.request(renderData.vertexCount, renderData.indiceCount); - - let count = data.length; - for (let i = 0; i < count; i++) { - let vert = data[i]; - vbuf[vertexOffset ++] = vert.x * a + vert.y * c + tx; - vbuf[vertexOffset ++] = vert.x * b + vert.y * d + ty; - vbuf[vertexOffset ++] = vert.u; - vbuf[vertexOffset ++] = vert.v; - } - - for (let i = 0; i < count; i++) { - ibuf[indiceOffset+i] = vertexId+i; - } - }, -}; diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/simple.js b/cocos/2d/renderer/webgl/assemblers/sprite/simple.js deleted file mode 100644 index d684b2c021..0000000000 --- a/cocos/2d/renderer/webgl/assemblers/sprite/simple.js +++ /dev/null @@ -1,150 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); - -module.exports = { - useModel: false, - - updateRenderData (sprite) { - let frame = sprite._spriteFrame; - - // TODO: Material API design and export from editor could affect the material activation process - // need to update the logic here - if (frame) { - if (!frame._original && dynamicAtlasManager) { - dynamicAtlasManager.insertSpriteFrame(frame); - } - if (sprite._material._texture !== frame._texture) { - sprite._activateMaterial(); - } - } - - let renderData = sprite._renderData; - if (renderData && frame) { - if (renderData.vertDirty) { - this.updateVerts(sprite); - } - } - }, - - fillBuffers (sprite, renderer) { - let data = sprite._renderData._data, - node = sprite.node, - matrix = node._worldMatrix, - a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2; - - buffer.request(4, 6); - - // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData; - - // get uv from sprite frame directly - let uv = sprite._spriteFrame.uv; - vbuf[vertexOffset+2] = uv[0]; - vbuf[vertexOffset+3] = uv[1]; - vbuf[vertexOffset+6] = uv[2]; - vbuf[vertexOffset+7] = uv[3]; - vbuf[vertexOffset+10] = uv[4]; - vbuf[vertexOffset+11] = uv[5]; - vbuf[vertexOffset+14] = uv[6]; - vbuf[vertexOffset+15] = uv[7]; - - let data0 = data[0], data3 = data[3], - vl = data0.x, vr = data3.x, - vb = data0.y, vt = data3.y; - - let al = a * vl, ar = a * vr, - bl = b * vl, br = b * vr, - cb = c * vb, ct = c * vt, - db = d * vb, dt = d * vt; - - // left bottom - vbuf[vertexOffset] = al + cb + tx; - vbuf[vertexOffset+1] = bl + db + ty; - // right bottom - vbuf[vertexOffset+4] = ar + cb + tx; - vbuf[vertexOffset+5] = br + db + ty; - // left top - vbuf[vertexOffset+8] = al + ct + tx; - vbuf[vertexOffset+9] = bl + dt + ty; - // right top - vbuf[vertexOffset+12] = ar + ct + tx; - vbuf[vertexOffset+13] = br + dt + ty; - }, - - createData (sprite) { - let renderData = sprite.requestRenderData(); - renderData.dataLength = 4; - renderData.vertexCount = 4; - renderData.indiceCount = 6; - return renderData; - }, - - updateVerts (sprite) { - let renderData = sprite._renderData, - node = sprite.node, - data = renderData._data, - cw = node.width, ch = node.height, - appx = node.anchorX * cw, appy = node.anchorY * ch, - l, b, r, t; - if (sprite.trim) { - l = -appx; - b = -appy; - r = cw - appx; - t = ch - appy; - } - else { - let frame = sprite.spriteFrame, - ow = frame._originalSize.width, oh = frame._originalSize.height, - rw = frame._rect.width, rh = frame._rect.height, - offset = frame._offset, - scaleX = cw / ow, scaleY = ch / oh; - let trimLeft = offset.x + (ow - rw) / 2; - let trimRight = offset.x - (ow - rw) / 2; - let trimBottom = offset.y + (oh - rh) / 2; - let trimTop = offset.y - (oh - rh) / 2; - l = trimLeft * scaleX - appx; - b = trimBottom * scaleY - appy; - r = cw + trimRight * scaleX - appx; - t = ch + trimTop * scaleY - appy; - } - - data[0].x = l; - data[0].y = b; - // data[1].x = r; - // data[1].y = b; - // data[2].x = l; - // data[2].y = t; - data[3].x = r; - data[3].y = t; - - renderData.vertDirty = false; - } -}; diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/sliced.js b/cocos/2d/renderer/webgl/assemblers/sprite/sliced.js deleted file mode 100644 index 3279497dab..0000000000 --- a/cocos/2d/renderer/webgl/assemblers/sprite/sliced.js +++ /dev/null @@ -1,164 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); - -module.exports = { - useModel: false, - - createData (sprite) { - let renderData = sprite.requestRenderData(); - // 0-4 for local verts - // 5-20 for world verts - renderData.dataLength = 20; - - renderData.vertexCount = 16; - renderData.indiceCount = 54; - return renderData; - }, - - updateRenderData (sprite, batchData) { - let frame = sprite.spriteFrame; - - // TODO: Material API design and export from editor could affect the material activation process - // need to update the logic here - if (frame) { - if (!frame._original && dynamicAtlasManager) { - dynamicAtlasManager.insertSpriteFrame(frame); - } - if (sprite._material._texture !== frame._texture) { - sprite._activateMaterial(); - } - } - - let renderData = sprite._renderData; - if (renderData && frame) { - let vertDirty = renderData.vertDirty; - if (vertDirty) { - this.updateVerts(sprite); - this.updateWorldVerts(sprite); - } - } - }, - - updateVerts (sprite) { - let renderData = sprite._renderData, - data = renderData._data, - node = sprite.node, - width = node.width, height = node.height, - appx = node.anchorX * width, appy = node.anchorY * height; - - let frame = sprite.spriteFrame; - let leftWidth = frame.insetLeft; - let rightWidth = frame.insetRight; - let topHeight = frame.insetTop; - let bottomHeight = frame.insetBottom; - - let sizableWidth = width - leftWidth - rightWidth; - let sizableHeight = height - topHeight - bottomHeight; - let xScale = width / (leftWidth + rightWidth); - let yScale = height / (topHeight + bottomHeight); - xScale = (isNaN(xScale) || xScale > 1) ? 1 : xScale; - yScale = (isNaN(yScale) || yScale > 1) ? 1 : yScale; - sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; - sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; - - data[0].x = -appx; - data[0].y = -appy; - data[1].x = leftWidth * xScale - appx; - data[1].y = bottomHeight * yScale - appy; - data[2].x = data[1].x + sizableWidth; - data[2].y = data[1].y + sizableHeight; - data[3].x = width - appx; - data[3].y = height - appy; - - renderData.vertDirty = false; - }, - - fillBuffers (sprite, renderer) { - if (renderer.worldMatDirty) { - this.updateWorldVerts(sprite); - } - - let renderData = sprite._renderData, - data = renderData._data; - - let buffer = renderer._meshBuffer, - vertexOffset = buffer.byteOffset >> 2, - vertexCount = renderData.vertexCount; - - let indiceOffset = buffer.indiceOffset, - vertexId = buffer.vertexOffset; - - let uvSliced = sprite.spriteFrame.uvSliced; - - buffer.request(vertexCount, renderData.indiceCount); - - // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - ibuf = buffer._iData; - - for (let i = 4; i < 20; ++i) { - let vert = data[i]; - let uvs = uvSliced[i - 4]; - - vbuf[vertexOffset++] = vert.x; - vbuf[vertexOffset++] = vert.y; - vbuf[vertexOffset++] = uvs.u; - vbuf[vertexOffset++] = uvs.v; - } - - for (let r = 0; r < 3; ++r) { - for (let c = 0; c < 3; ++c) { - let start = vertexId + r*4 + c; - ibuf[indiceOffset++] = start; - ibuf[indiceOffset++] = start + 1; - ibuf[indiceOffset++] = start + 4; - ibuf[indiceOffset++] = start + 1; - ibuf[indiceOffset++] = start + 5; - ibuf[indiceOffset++] = start + 4; - } - } - }, - - updateWorldVerts (sprite) { - let node = sprite.node, - data = sprite._renderData._data; - - let matrix = node._worldMatrix, - a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - for (let row = 0; row < 4; ++row) { - let rowD = data[row]; - for (let col = 0; col < 4; ++col) { - let colD = data[col]; - let world = data[4 + row*4 + col]; - world.x = colD.x*a + rowD.y*c + tx; - world.y = colD.x*b + rowD.y*d + ty; - } - } - }, -}; diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/tiled.js b/cocos/2d/renderer/webgl/assemblers/sprite/tiled.js deleted file mode 100644 index 9e60ca17d4..0000000000 --- a/cocos/2d/renderer/webgl/assemblers/sprite/tiled.js +++ /dev/null @@ -1,190 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); - -module.exports = { - useModel: false, - - createData (sprite) { - return sprite.requestRenderData(); - }, - - updateRenderData (sprite) { - let frame = sprite.spriteFrame; - - // TODO: Material API design and export from editor could affect the material activation process - // need to update the logic here - if (frame) { - if (!frame._original && dynamicAtlasManager) { - dynamicAtlasManager.insertSpriteFrame(frame); - } - if (sprite._material._texture !== frame._texture) { - sprite._activateMaterial(); - } - } - - let renderData = sprite._renderData; - if (!frame || !renderData || - !(renderData.uvDirty || renderData.vertDirty)) - return; - - let texture = frame._texture; - let texw = texture.width, - texh = texture.height, - rect = frame._rect; - - let node = sprite.node, - contentWidth = Math.abs(node.width), - contentHeight = Math.abs(node.height), - appx = node.anchorX * contentWidth, - appy = node.anchorY * contentHeight; - - let rectWidth = rect.width, - rectHeight = rect.height, - hRepeat = contentWidth / rectWidth, - vRepeat = contentHeight / rectHeight, - row = Math.ceil(vRepeat), - col = Math.ceil(hRepeat); - - let data = renderData._data; - renderData.dataLength = Math.max(8, row+1, col+1); - - for (let i = 0; i <= col; ++i) { - data[i].x = Math.min(rectWidth * i, contentWidth) - appx; - } - for (let i = 0; i <= row; ++i) { - data[i].y = Math.min(rectHeight * i, contentHeight) - appy; - } - - // update data property - renderData.vertexCount = row * col * 4; - renderData.indiceCount = row * col * 6; - renderData.uvDirty = false; - renderData.vertDirty = false; - }, - - fillBuffers (sprite, renderer) { - let node = sprite.node, - renderData = sprite._renderData, - data = renderData._data; - - // buffer - let buffer = renderer._meshBuffer, - vertexOffset = buffer.byteOffset >> 2; - - let indiceOffset = buffer.indiceOffset, - vertexId = buffer.vertexOffset; - - buffer.request(renderData.vertexCount, renderData.indiceCount); - - // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - ibuf = buffer._iData; - - let rotated = sprite.spriteFrame._rotated; - let uv = sprite.spriteFrame.uv; - let rect = sprite.spriteFrame._rect; - let contentWidth = Math.abs(node.width); - let contentHeight = Math.abs(node.height); - let hRepeat = contentWidth / rect.width; - let vRepeat = contentHeight / rect.height; - let row = Math.ceil(vRepeat), - col = Math.ceil(hRepeat); - - let matrix = node._worldMatrix; - let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - let x, x1, y, y1, coefu, coefv; - for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { - y = data[yindex].y; - y1 = data[yindex+1].y; - coefv = Math.min(1, vRepeat - yindex); - for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { - coefu = Math.min(1, hRepeat - xindex); - x = data[xindex].x; - x1 = data[xindex+1].x; - - // Vertex - // lb - vbuf[vertexOffset] = x * a + y * c + tx; - vbuf[vertexOffset+1] = x * b + y * d + ty; - // rb - vbuf[vertexOffset+4] = x1 * a + y * c + tx; - vbuf[vertexOffset+5] = x1 * b + y * d + ty; - // lt - vbuf[vertexOffset+8] = x * a + y1 * c + tx; - vbuf[vertexOffset+9] = x * b + y1 * d + ty; - // rt - vbuf[vertexOffset+12] = x1 * a + y1 * c + tx; - vbuf[vertexOffset+13] = x1 * b + y1 * d + ty; - - // UV - if (rotated) { - // lb - vbuf[vertexOffset+2] = uv[0]; - vbuf[vertexOffset+3] = uv[1]; - // rb - vbuf[vertexOffset+6] = uv[0]; - vbuf[vertexOffset+7] = uv[1] + (uv[7] - uv[1]) * coefu; - // lt - vbuf[vertexOffset+10] = uv[0] + (uv[6] - uv[0]) * coefv; - vbuf[vertexOffset+11] = uv[1]; - // rt - vbuf[vertexOffset+14] = vbuf[vertexOffset+10]; - vbuf[vertexOffset+15] = vbuf[vertexOffset+7]; - } - else { - // lb - vbuf[vertexOffset+2] = uv[0]; - vbuf[vertexOffset+3] = uv[1]; - // rb - vbuf[vertexOffset+6] = uv[0] + (uv[6] - uv[0]) * coefu; - vbuf[vertexOffset+7] = uv[1]; - // lt - vbuf[vertexOffset+10] = uv[0]; - vbuf[vertexOffset+11] = uv[1] + (uv[7] - uv[1]) * coefv; - // rt - vbuf[vertexOffset+14] = vbuf[vertexOffset+6]; - vbuf[vertexOffset+15] = vbuf[vertexOffset+11]; - } - vertexOffset += 16; - } - } - - // update indices - let length = renderData.indiceCount; - for (let i = 0; i < length; i+=6) { - ibuf[indiceOffset++] = vertexId; - ibuf[indiceOffset++] = vertexId+1; - ibuf[indiceOffset++] = vertexId+2; - ibuf[indiceOffset++] = vertexId+1; - ibuf[indiceOffset++] = vertexId+3; - ibuf[indiceOffset++] = vertexId+2; - vertexId += 4; - } - }, -}; \ No newline at end of file diff --git a/cocos/2d/ui/CCButton.js b/cocos/2d/ui/CCButton.js deleted file mode 100644 index 0c3163fc45..0000000000 --- a/cocos/2d/ui/CCButton.js +++ /dev/null @@ -1,687 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const Component = require('./CCComponent'); -const misc = require('../utils/misc'); - -/** - * !#en Enum for transition type. - * !#zh 过渡类型 - * @enum Button.Transition - */ -let Transition = cc.Enum({ - /** - * !#en The none type. - * !#zh 不做任何过渡 - * @property {Number} NONE - */ - NONE: 0, - - /** - * !#en The color type. - * !#zh 颜色过渡 - * @property {Number} COLOR - */ - COLOR: 1, - - /** - * !#en The sprite type. - * !#zh 精灵过渡 - * @property {Number} SPRITE - */ - SPRITE: 2, - /** - * !#en The scale type - * !#zh 缩放过渡 - * @property {Number} SCALE - */ - SCALE: 3 -}); - -/** - * !#en - * Button has 4 Transition types
- * When Button state changed:
- * If Transition type is Button.Transition.NONE, Button will do nothing
- * If Transition type is Button.Transition.COLOR, Button will change target's color
- * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite
- * If Transition type is Button.Transition.SCALE, Button will change target node's scale
- * - * Button will trigger 5 events:
- * Button.EVENT_TOUCH_DOWN
- * Button.EVENT_TOUCH_UP
- * Button.EVENT_HOVER_IN
- * Button.EVENT_HOVER_MOVE
- * Button.EVENT_HOVER_OUT
- * - * !#zh - * 按钮组件。可以被按下,或者点击。
- * - * 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:
- * -Button.Transition.NONE // 不做任何过渡
- * -Button.Transition.COLOR // 进行颜色之间过渡
- * -Button.Transition.SPRITE // 进行精灵之间过渡
- * -Button.Transition.SCALE // 进行缩放过渡
- * - * 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):
- * // 以下事件可以在全平台上都触发
- * -cc.Node.EventType.TOUCH_START // 按下时事件
- * -cc.Node.EventType.TOUCH_Move // 按住移动后事件
- * -cc.Node.EventType.TOUCH_END // 按下后松开后事件
- * -cc.Node.EventType.TOUCH_CANCEL // 按下取消事件
- * // 以下事件只在 PC 平台上触发
- * -cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件
- * -cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件
- * -cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件
- * -cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件
- * -cc.Node.EventType.MOUSE_UP // 鼠标松开事件
- * -cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件
- * - * @class Button - * @extends Component - * @example - * - * // Add an event to the button. - * button.node.on(cc.Node.EventType.TOUCH_START, function (event) { - * cc.log("This is a callback after the trigger event"); - * }); - - * // You could also add a click event - * //Note: In this way, you can't get the touch event info, so use it wisely. - * button.node.on('click', function (button) { - * //The event is a custom event, you could get the Button component via first argument - * }) - * - */ -let Button = cc.Class({ - name: 'cc.Button', - extends: Component, - - ctor () { - this._pressed = false; - this._hovered = false; - this._fromColor = null; - this._toColor = null; - this._time = 0; - this._transitionFinished = true; - this._fromScale = 1.0; - this._toScale = 1.0; - this._originalScale = 1.0; - - this._sprite = null; - - if (CC_EDITOR) { - this._previousNormalSprite = null; - } - }, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/Button', - help: 'i18n:COMPONENT.help_url.button', - inspector: 'packages://inspector/inspectors/comps/button.js', - executeInEditMode: true - }, - - properties: { - /** - * !#en - * Whether the Button is disabled. - * If true, the Button will trigger event and do transition. - * !#zh - * 按钮事件是否被响应,如果为 false,则按钮将被禁用。 - * @property {Boolean} interactable - * @default true - */ - interactable: { - default: true, - tooltip: CC_DEV && 'i18n:COMPONENT.button.interactable', - notify (oldValue) { - if (CC_EDITOR) { - if (oldValue) { - this._previousNormalSprite = this.normalSprite; - } else { - this.normalSprite = this._previousNormalSprite; - } - } - this._updateState(); - - if (!this.interactable) { - this._resetState(); - } - }, - animatable: false - }, - - _resizeToTarget: { - animatable: false, - set (value) { - if (value) { - this._resizeNodeToTargetNode(); - } - } - }, - - /** - * !#en When this flag is true, Button target sprite will turn gray when interactable is false. - * !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰 - * @property {Boolean} enableAutoGrayEffect - */ - enableAutoGrayEffect: { - default: false, - tooltip: CC_DEV && 'i18n:COMPONENT.button.auto_gray_effect', - notify () { - this._updateDisabledState(); - } - }, - - /** - * !#en Transition type - * !#zh 按钮状态改变时过渡方式。 - * @property {Button.Transition} transition - * @default Button.Transition.Node - */ - transition: { - default: Transition.NONE, - tooltip: CC_DEV && 'i18n:COMPONENT.button.transition', - type: Transition, - animatable: false - }, - - // color transition - - /** - * !#en Normal state color. - * !#zh 普通状态下按钮所显示的颜色。 - * @property {Color} normalColor - */ - normalColor: { - default: cc.color(214, 214, 214), - displayName: 'Normal', - tooltip: CC_DEV && 'i18n:COMPONENT.button.normal_color', - notify () { - this._updateState(); - } - }, - - /** - * !#en Pressed state color - * !#zh 按下状态时按钮所显示的颜色。 - * @property {Color} pressedColor - */ - pressedColor: { - default: cc.color(211, 211, 211), - displayName: 'Pressed', - tooltip: CC_DEV && 'i18n:COMPONENT.button.pressed_color', - }, - - /** - * !#en Hover state color - * !#zh 悬停状态下按钮所显示的颜色。 - * @property {Color} hoverColor - */ - hoverColor: { - default: cc.Color.WHITE, - displayName: 'Hover', - tooltip: CC_DEV && 'i18n:COMPONENT.button.hover_color', - }, - - /** - * !#en Disabled state color - * !#zh 禁用状态下按钮所显示的颜色。 - * @property {Color} disabledColor - */ - disabledColor: { - default: cc.color(124, 124, 124), - displayName: 'Disabled', - tooltip: CC_DEV && 'i18n:COMPONENT.button.disabled_color', - notify () { - this._updateState(); - } - }, - - /** - * !#en Color and Scale transition duration - * !#zh 颜色过渡和缩放过渡时所需时间 - * @property {Number} duration - */ - duration: { - default: 0.1, - range: [0, 10], - tooltip: CC_DEV && 'i18n:COMPONENT.button.duration', - }, - - /** - * !#en When user press the button, the button will zoom to a scale. - * The final scale of the button equals (button original scale * zoomScale) - * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale - * @property {Number} zoomScale - */ - zoomScale: { - default: 1.2, - tooltip: CC_DEV && 'i18n:COMPONENT.button.zoom_scale' - }, - - // sprite transition - /** - * !#en Normal state sprite - * !#zh 普通状态下按钮所显示的 Sprite 。 - * @property {SpriteFrame} normalSprite - */ - normalSprite: { - default: null, - type: cc.SpriteFrame, - displayName: 'Normal', - tooltip: CC_DEV && 'i18n:COMPONENT.button.normal_sprite', - notify () { - this._updateState(); - } - }, - - /** - * !#en Pressed state sprite - * !#zh 按下状态时按钮所显示的 Sprite 。 - * @property {SpriteFrame} pressedSprite - */ - pressedSprite: { - default: null, - type: cc.SpriteFrame, - displayName: 'Pressed', - tooltip: CC_DEV && 'i18n:COMPONENT.button.pressed_sprite', - formerlySerializedAs: 'pressedSprite', - notify () { - this._updateState(); - } - }, - - /** - * !#en Hover state sprite - * !#zh 悬停状态下按钮所显示的 Sprite 。 - * @property {SpriteFrame} hoverSprite - */ - hoverSprite: { - default: null, - type: cc.SpriteFrame, - displayName: 'Hover', - tooltip: CC_DEV && 'i18n:COMPONENT.button.hover_sprite', - formerlySerializedAs: 'hoverSprite', - notify () { - this._updateState(); - } - }, - - /** - * !#en Disabled state sprite - * !#zh 禁用状态下按钮所显示的 Sprite 。 - * @property {SpriteFrame} disabledSprite - */ - disabledSprite: { - default: null, - type: cc.SpriteFrame, - displayName: 'Disabled', - tooltip: CC_DEV && 'i18n:COMPONENT.button.disabled_sprite', - notify () { - this._updateState(); - } - }, - - /** - * !#en - * Transition target. - * When Button state changed: - * If Transition type is Button.Transition.NONE, Button will do nothing - * If Transition type is Button.Transition.COLOR, Button will change target's color - * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite - * !#zh - * 需要过渡的目标。 - * 当前按钮状态改变规则: - * -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。 - * -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。 - * -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 - * @property {Node} target - */ - target: { - default: null, - type: cc.Node, - tooltip: CC_DEV && "i18n:COMPONENT.button.target", - notify () { - this._applyTarget(); - } - }, - - /** - * !#en If Button is clicked, it will trigger event's handler - * !#zh 按钮的点击事件列表。 - * @property {Component.EventHandler[]} clickEvents - */ - clickEvents: { - default: [], - type: cc.Component.EventHandler, - tooltip: CC_DEV && 'i18n:COMPONENT.button.click_events', - } - }, - - statics: { - Transition: Transition, - }, - - __preload () { - if (!this.target) { - this.target = this.node; - } - this._applyTarget(); - this._updateState(); - }, - - _resetState () { - this._pressed = false; - this._hovered = false; - // // Restore button status - let target = this.target; - let transition = this.transition; - if (transition === Transition.COLOR && this.interactable) { - target.color = this.normalColor; - } else if (transition === Transition.SCALE) { - target.scale = this._originalScale; - } - this._transitionFinished = true; - }, - - onEnable () { - // check sprite frames - if (this.normalSprite) { - this.normalSprite.ensureLoadTexture(); - } - if (this.hoverSprite) { - this.hoverSprite.ensureLoadTexture(); - } - if (this.pressedSprite) { - this.pressedSprite.ensureLoadTexture(); - } - if (this.disabledSprite) { - this.disabledSprite.ensureLoadTexture(); - } - // - if (!CC_EDITOR) { - this._registerEvent(); - } else { - this.node.on('spriteframe-changed', function (comp) { - if (this.transition === Transition.SPRITE) { - this.normalSprite = comp.spriteFrame; - } - }.bind(this)); - } - }, - - 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(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'); - } - }, - - update (dt) { - let target = this.target; - if (this._transitionFinished) return; - if (this.transition !== Transition.COLOR && this.transition !== Transition.SCALE) return; - - this.time += dt; - let ratio = 1.0; - if (this.duration > 0) { - ratio = this.time / this.duration; - } - - if (ratio >= 1) { - ratio = 1; - this._transitionFinished = true; - } - - if (this.transition === Transition.COLOR) { - target.color = this._fromColor.lerp(this._toColor, ratio); - } else if (this.transition === Transition.SCALE) { - target.scale = misc.lerp(this._fromScale, this._toScale, ratio); - } - - }, - - _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); - - this.node.on(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); - this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); - }, - - _getTargetSprite (target) { - let sprite = null; - if (target) { - sprite = target.getComponent(cc.Sprite); - } - return sprite; - }, - - _applyTarget () { - this._sprite = this._getTargetSprite(this.target); - if (this.target) { - this._originalScale = this.target.scale; - } - }, - - // touch event handler - _onTouchBegan (event) { - if (!this.interactable || !this.enabledInHierarchy) return; - - this._pressed = true; - this._updateState(); - event.stopPropagation(); - }, - - _onTouchMove (event) { - if (!this.interactable || !this.enabledInHierarchy || !this._pressed) return; - // mobile phone will not emit _onMouseMoveOut, - // so we have to do hit test when touch moving - let touch = event.touch; - let hit = this.node._hitTest(touch.getLocation()); - - if (this.transition === Transition.SCALE && this.target) { - if (hit) { - this._fromScale = this._originalScale; - this._toScale = this._originalScale * this.zoomScale; - this._transitionFinished = false; - } else { - this.time = 0; - this._transitionFinished = true; - this.target.scale = this._originalScale; - } - } else { - let state; - if (hit) { - state = 'pressed'; - } else { - state = 'normal'; - } - this._applyTransition(state); - } - event.stopPropagation(); - }, - - _onTouchEnded (event) { - if (!this.interactable || !this.enabledInHierarchy) return; - - if (this._pressed) { - cc.Component.EventHandler.emitEvents(this.clickEvents, event); - this.node.emit('click', this); - } - this._pressed = false; - this._updateState(); - event.stopPropagation(); - }, - - _onTouchCancel () { - if (!this.interactable || !this.enabledInHierarchy) return; - - this._pressed = false; - this._updateState(); - }, - - _onMouseMoveIn () { - if (this._pressed || !this.interactable || !this.enabledInHierarchy) return; - if (this.transition === Transition.SPRITE && !this.hoverSprite) return; - - if (!this._hovered) { - this._hovered = true; - this._updateState(); - } - }, - - _onMouseMoveOut () { - if (this._hovered) { - this._hovered = false; - this._updateState(); - } - }, - - // state handler - _updateState () { - let state = this._getButtonState(); - this._applyTransition(state); - this._updateDisabledState(); - }, - - _getButtonState () { - let state; - if (!this.interactable) { - state = 'disabled'; - } - else if (this._pressed) { - state = 'pressed'; - } - else if (this._hovered) { - state = 'hover'; - } - else { - state = 'normal'; - } - return state; - }, - - _updateColorTransition (state) { - let color = this[state + 'Color']; - let target = this.target; - - if (CC_EDITOR) { - target.color = color; - } - else { - this._fromColor = target.color.clone(); - this._toColor = color; - this.time = 0; - this._transitionFinished = false; - } - }, - - _updateSpriteTransition (state) { - let sprite = this[state + 'Sprite']; - if (this._sprite && sprite) { - this._sprite.spriteFrame = sprite; - } - }, - - _updateScaleTransition (state) { - if (state === 'pressed') { - this._zoomUp(); - } else { - this._zoomBack(); - } - }, - - _zoomUp () { - this._fromScale = this._originalScale; - this._toScale = this._originalScale * this.zoomScale; - this.time = 0; - this._transitionFinished = false; - }, - - _zoomBack () { - this._fromScale = this.target.scale; - this._toScale = this._originalScale; - this.time = 0; - this._transitionFinished = false; - }, - - _applyTransition (state) { - let transition = this.transition; - if (transition === Transition.COLOR) { - this._updateColorTransition(state); - } else if (transition === Transition.SPRITE) { - this._updateSpriteTransition(state); - } else if (transition === Transition.SCALE) { - this._updateScaleTransition(state); - } - }, - - _resizeNodeToTargetNode: CC_EDITOR && function () { - if (this.target) { - this.node.setContentSize(this.target.getContentSize()); - } - }, - - _updateDisabledState () { - if (this._sprite) { - if (this.enableAutoGrayEffect) { - if (!(this.transition === Transition.SPRITE && this.disabledSprite)) { - if (!this.interactable) { - this._sprite.setState(cc.Sprite.State.GRAY); - return; - } - } - } - this._sprite.setState(cc.Sprite.State.NORMAL); - } - } -}); - -cc.Button = module.exports = Button; - -/** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event click - * @param {Event.EventCustom} event - * @param {Button} button - The Button component. - */ diff --git a/cocos/2d/ui/CCProgressBar.js b/cocos/2d/ui/CCProgressBar.js deleted file mode 100644 index a90d987d1a..0000000000 --- a/cocos/2d/ui/CCProgressBar.js +++ /dev/null @@ -1,297 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const misc = require('../utils/misc'); -const Component = require('./CCComponent'); - -/** - * !#en Enum for ProgressBar mode - * !#zh 进度条模式 - * @enum ProgressBar.Mode - */ -var Mode = cc.Enum({ - /** - * !#en TODO - * !#zh 水平方向模式 - * @property {Number} HORIZONTAL - */ - HORIZONTAL: 0, - - /** - * !#en TODO - * !#zh 垂直方向模式 - * @property {Number} VERTICAL - */ - VERTICAL: 1, - /** - * !#en TODO - * !#zh 填充模式 - * @property {Number} FILLED - */ - FILLED: 2, -}); - -/** - * !#en - * Visual indicator of progress in some operation. - * Displays a bar to the user representing how far the operation has progressed. - * !#zh - * 进度条组件,可用于显示加载资源时的进度。 - * @class ProgressBar - * @extends Component - * @example - * // update progressBar - * update: function (dt) { - * var progress = progressBar.progress; - * if (progress > 0) { - * progress += dt; - * } - * else { - * progress = 1; - * } - * progressBar.progress = progress; - * } - * - */ -var ProgressBar = cc.Class({ - name: 'cc.ProgressBar', - extends: Component, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/ProgressBar', - help: 'i18n:COMPONENT.help_url.progressbar', - }, - - _initBarSprite: function() { - if (this.barSprite) { - var entity = this.barSprite.node; - if (!entity) return; - - var nodeSize = this.node.getContentSize(); - var nodeAnchor = this.node.getAnchorPoint(); - - var entitySize = entity.getContentSize(); - - if(entity.parent === this.node){ - this.node.setContentSize(entitySize); - } - - if (this.barSprite.fillType === cc.Sprite.FillType.RADIAL) { - this.mode = Mode.FILLED; - } - - var barSpriteSize = entity.getContentSize(); - if (this.mode === Mode.HORIZONTAL) { - this.totalLength = barSpriteSize.width; - } - else if(this.mode === Mode.VERTICAL) { - this.totalLength = barSpriteSize.height; - } - else { - this.totalLength = this.barSprite.fillRange; - } - - if(entity.parent === this.node){ - var x = - nodeSize.width * nodeAnchor.x; - var y = 0; - entity.setPosition(cc.v2(x, y)); - } - } - }, - - _updateBarStatus: function() { - if (this.barSprite) { - var entity = this.barSprite.node; - - if (!entity) return; - - var entityAnchorPoint = entity.getAnchorPoint(); - var entitySize = entity.getContentSize(); - var entityPosition = entity.getPosition(); - - var anchorPoint = cc.v2(0, 0.5); - var progress = misc.clamp01(this.progress); - var actualLenth = this.totalLength * progress; - var finalContentSize; - var totalWidth; - var totalHeight; - switch (this.mode) { - case Mode.HORIZONTAL: - if (this.reverse) { - anchorPoint = cc.v2(1, 0.5); - } - finalContentSize = cc.size(actualLenth, entitySize.height); - totalWidth = this.totalLength; - totalHeight = entitySize.height; - break; - case Mode.VERTICAL: - if (this.reverse) { - anchorPoint = cc.v2(0.5, 1); - } else { - anchorPoint = cc.v2(0.5, 0); - } - finalContentSize = cc.size(entitySize.width, actualLenth); - totalWidth = entitySize.width; - totalHeight = this.totalLength; - break; - } - - //handling filled mode - if (this.mode === Mode.FILLED) { - if (this.barSprite.type !== cc.Sprite.Type.FILLED) { - cc.warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!'); - } else { - if (this.reverse) { - actualLenth = actualLenth * -1; - } - this.barSprite.fillRange = actualLenth; - } - } else { - if (this.barSprite.type !== cc.Sprite.Type.FILLED) { - - var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; - var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; - var finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); - - entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y); - - entity.setAnchorPoint(anchorPoint); - entity.setContentSize(finalContentSize); - } else { - cc.warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!'); - } - } - - - - } - }, - - properties: { - /** - * !#en The targeted Sprite which will be changed progressively. - * !#zh 用来显示进度条比例的 Sprite 对象。 - * @property {Sprite} barSprite - */ - barSprite: { - default: null, - type: cc.Sprite, - tooltip: CC_DEV && 'i18n:COMPONENT.progress.bar_sprite', - notify: function() { - this._initBarSprite(); - }, - animatable: false - }, - - /** - * !#en The progress mode, there are two modes supported now: horizontal and vertical. - * !#zh 进度条的模式 - * @property {ProgressBar.Mode} mode - */ - mode: { - default: Mode.HORIZONTAL, - type: Mode, - tooltip: CC_DEV && 'i18n:COMPONENT.progress.mode', - notify: function() { - if (this.barSprite) { - var entity = this.barSprite.node; - if (!entity) return; - - var entitySize = entity.getContentSize(); - if (this.mode === Mode.HORIZONTAL) { - this.totalLength = entitySize.width; - } else if (this.mode === Mode.VERTICAL) { - this.totalLength = entitySize.height; - } else if (this.mode === Mode.FILLED) { - this.totalLength = this.barSprite.fillRange; - } - } - }, - animatable: false - }, - - _N$totalLength: 1, - /** - * !#en The total width or height of the bar sprite. - * !#zh 进度条实际的总长度 - * @property {Number} totalLength - */ - totalLength: { - range: [0, Number.MAX_VALUE], - tooltip: CC_DEV && 'i18n:COMPONENT.progress.total_length', - get: function () { - return this._N$totalLength; - }, - set: function(value) { - if (this.mode === Mode.FILLED) { - value = misc.clamp01(value); - } - this._N$totalLength = value; - this._updateBarStatus(); - } - }, - - /** - * !#en The current progress of the bar sprite. The valid value is between 0-1. - * !#zh 当前进度值,该数值的区间是 0-1 之间。 - * @property {Number} progress - */ - progress: { - default: 1, - type: 'Float', - range: [0, 1, 0.1], - slide: true, - tooltip: CC_DEV && 'i18n:COMPONENT.progress.progress', - notify: function() { - this._updateBarStatus(); - } - }, - - /** - * !#en Whether reverse the progress direction of the bar sprite. - * !#zh 进度条是否进行反方向变化。 - * @property {Boolean} reverse - */ - reverse: { - default: false, - tooltip: CC_DEV && 'i18n:COMPONENT.progress.reverse', - notify: function() { - if (this.barSprite) { - this.barSprite.fillStart = 1 - this.barSprite.fillStart; - } - this._updateBarStatus(); - }, - animatable: false - } - }, - - statics: { - Mode: Mode - } -}); - - -cc.ProgressBar = module.exports = ProgressBar; diff --git a/cocos/2d/ui/CCScrollBar.js b/cocos/2d/ui/CCScrollBar.js deleted file mode 100644 index 070f28dbd3..0000000000 --- a/cocos/2d/ui/CCScrollBar.js +++ /dev/null @@ -1,357 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const misc = require('../utils/misc'); -const Component = require('./CCComponent'); - -var GETTINGSHORTERFACTOR = 20; - -/** - * Enum for Scrollbar direction - * @enum Scrollbar.Direction - */ -var Direction = cc.Enum({ - /** - * @property {Number} HORIZONTAL - */ - HORIZONTAL: 0, - - /** - * @property {Number} VERTICAL - */ - VERTICAL: 1 -}); - -/** - * !#en - * The Scrollbar control allows the user to scroll an image or other view that is too large to see completely - * !#zh 滚动条组件 - * @class Scrollbar - * @extends Component - */ -var Scrollbar = cc.Class({ - name: 'cc.Scrollbar', - extends: require('./CCComponent'), - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/ScrollBar', - help: 'i18n:COMPONENT.help_url.scrollbar', - }, - - properties: { - _scrollView: null, - _touching: false, - _autoHideRemainingTime: { - default: 0, - serializable: false - }, - _opacity: 255, - - /** - * !#en The "handle" part of the scrollbar. - * !#zh 作为当前滚动区域位置显示的滑块 Sprite。 - * @property {Sprite} handle - */ - handle: { - default: null, - type: cc.Sprite, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.handle', - notify: function() { - this._onScroll(cc.v2(0, 0)); - }, - animatable: false - }, - - /** - * !#en The direction of scrollbar. - * !#zh ScrollBar 的滚动方向。 - * @property {Scrollbar.Direction} direction - */ - direction: { - default: Direction.HORIZONTAL, - type: Direction, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.direction', - notify: function() { - this._onScroll(cc.v2(0, 0)); - }, - animatable: false - }, - - /** - * !#en Whether enable auto hide or not. - * !#zh 是否在没有滚动动作时自动隐藏 ScrollBar。 - * @property {Boolean} enableAutoHide - */ - enableAutoHide: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.auto_hide', - }, - - /** - * !#en - * The time to hide scrollbar when scroll finished. - * Note: This value is only useful when enableAutoHide is true. - * !#zh - * 没有滚动动作后经过多久会自动隐藏。 - * 注意:只要当 “enableAutoHide” 为 true 时,才有效。 - * @property {Number} autoHideTime - */ - autoHideTime: { - default: 1.0, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.auto_hide_time', - } - }, - - statics: { - Direction: Direction - }, - - setTargetScrollView: function(scrollView) { - this._scrollView = scrollView; - }, - - _convertToScrollViewSpace: function(content) { - var worldSpacePos = content.convertToWorldSpace(cc.v2(0, 0)); - var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos); - return scrollViewSpacePos; - }, - - _setOpacity: function(opacity) { - if (this.handle) { - this.node.opacity = opacity; - this.handle.node.opacity = opacity; - } - }, - - _onScroll: function(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); - } - } - }, - - _updateHanlderPosition: function(position) { - if (this.handle) { - var oldPosition = this._fixupHandlerPosition(); - - this.handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y); - } - }, - - _fixupHandlerPosition: function() { - var barSize = this.node.getContentSize(); - var barAnchor = this.node.getAnchorPoint(); - var handleSize = this.handle.node.getContentSize(); - - 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); - - if (this.direction === Direction.HORIZONTAL) { - fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2); - } else if (this.direction === Direction.VERTICAL) { - fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y); - } - - this.handle.node.setPosition(fixupPosition); - - return fixupPosition; - }, - - _onTouchBegan: function() { - if (!this.enableAutoHide) { - return; - } - this._touching = true; - }, - - _conditionalDisableScrollBar: function (contentSize, scrollViewSize) { - if(contentSize.width <= scrollViewSize.width - && this.direction === Direction.HORIZONTAL){ - return true; - } - - if(contentSize.height <= scrollViewSize.height - && this.direction === Direction.VERTICAL){ - return true; - } - return false; - }, - - _onTouchEnded: function() { - if (!this.enableAutoHide) { - return; - } - - this._touching = false; - - if (this.autoHideTime <= 0) { - return; - } - - - if (this._scrollView) { - var content = this._scrollView.content; - if(content){ - var contentSize = content.getContentSize(); - var scrollViewSize = this._scrollView.node.getContentSize(); - - if(this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { - return; - } - } - } - - this._autoHideRemainingTime = this.autoHideTime; - }, - - _calculateLength: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) { - var denominatorValue = contentMeasure; - if (outOfBoundary) { - denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR; - } - - var lengthRation = scrollViewMeasure / denominatorValue; - return handleNodeMeasure * lengthRation; - }, - - _calculatePosition: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) { - var denominatorValue = contentMeasure - scrollViewMeasure; - if (outOfBoundary) { - denominatorValue += Math.abs(outOfBoundary); - } - - var positionRatio = 0; - if (denominatorValue) { - positionRatio = contentPosition / denominatorValue; - positionRatio = misc.clamp01(positionRatio); - } - - var position = (handleNodeMeasure - actualLenth) * positionRatio; - if (this.direction === Direction.VERTICAL) { - return cc.v2(0, position); - } else { - return cc.v2(position, 0); - } - }, - - _updateLength: function(length) { - if (this.handle) { - var handleNode = this.handle.node; - var handleNodeSize = handleNode.getContentSize(); - handleNode.setAnchorPoint(cc.v2(0, 0)); - if (this.direction === Direction.HORIZONTAL) { - handleNode.setContentSize(length, handleNodeSize.height); - } else { - handleNode.setContentSize(handleNodeSize.width, length); - } - } - }, - - _processAutoHide: function(deltaTime) { - if (!this.enableAutoHide || this._autoHideRemainingTime <= 0) { - return; - } else if (this._touching) { - return; - } - - - this._autoHideRemainingTime -= deltaTime; - if (this._autoHideRemainingTime <= this.autoHideTime) { - this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); - var opacity = this._opacity * (this._autoHideRemainingTime / this.autoHideTime); - this._setOpacity(opacity); - } - }, - - start: function() { - if (this.enableAutoHide) { - this._setOpacity(0); - } - }, - - hide: function() { - this._autoHideRemainingTime = 0; - this._setOpacity(0); - }, - - show: function() { - this._autoHideRemainingTime = this.autoHideTime; - this._setOpacity(this._opacity); - }, - - update: function(dt) { - this._processAutoHide(dt); - } -}); - - -cc.Scrollbar = module.exports = Scrollbar; diff --git a/cocos/2d/ui/CCSlider.js b/cocos/2d/ui/CCSlider.js deleted file mode 100644 index 11e0b270a0..0000000000 --- a/cocos/2d/ui/CCSlider.js +++ /dev/null @@ -1,240 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const misc = require('../utils/misc'); -const Component = require('./CCComponent'); - -/** - * !#en The Slider Direction - * !#zh 滑动器方向 - * @enum Slider.Direction - */ -var Direction = cc.Enum({ - /** - * !#en The horizontal direction. - * !#zh 水平方向 - * @property {Number} Horizontal - */ - Horizontal: 0, - /** - * !#en The vertical direction. - * !#zh 垂直方向 - * @property {Number} Vertical - */ - Vertical: 1 -}); - -/** - * !#en The Slider Control - * !#zh 滑动器组件 - * @class Slider - * @extends Component - */ -var Slider = cc.Class({ - name: 'cc.Slider', - extends: Component, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/Slider', - help: 'i18n:COMPONENT.help_url.slider' - }, - - ctor: function () { - this._offset = cc.v2(); - this._touchHandle = false; - this._dragging = false; - }, - - properties: { - /** - * !#en The "handle" part of the slider - * !#zh 滑动器滑块按钮部件 - * @property {Button} handle - */ - handle: { - default: null, - type: cc.Button, - tooltip: CC_DEV && 'i18n:COMPONENT.slider.handle', - notify: function() { - if (CC_EDITOR && this.handle) { - this._updateHandlePosition(); - } - } - }, - - /** - * !#en The slider direction - * !#zh 滑动器方向 - * @property {Slider.Direction} direction - */ - direction: { - default: Direction.Horizontal, - type: Direction, - tooltip: CC_DEV && 'i18n:COMPONENT.slider.direction' - }, - - /** - * !#en The current progress of the slider. The valid value is between 0-1 - * !#zh 当前进度值,该数值的区间是 0-1 之间 - * @property {Number} progress - */ - progress: { - default: 0.5, - type: cc.Float, - range: [0, 1, 0.1], - slide: true, - tooltip: CC_DEV && 'i18n:COMPONENT.slider.progress', - notify: function() { - this._updateHandlePosition(); - } - }, - - /** - * !#en The slider events callback - * !#zh 滑动器组件事件回调函数 - * @property {Component.EventHandler[]} slideEvents - */ - slideEvents: { - default: [], - type: cc.Component.EventHandler, - tooltip: CC_DEV && 'i18n:COMPONENT.slider.slideEvents' - } - }, - - statics: { - Direction: Direction - }, - - __preload: function () { - this._updateHandlePosition(); - }, - - // 注册事件 - onEnable: function () { - this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); - this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); - this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); - if (this.handle && this.handle.isValid) { - this.handle.node.on(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this); - this.handle.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); - this.handle.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); - } - }, - - onDisable: function() { - this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); - this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); - this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); - if (this.handle && this.handle.isValid) { - this.handle.node.off(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this); - this.handle.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); - this.handle.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); - } - }, - - _onHandleDragStart: function (event) { - this._dragging = true; - this._touchHandle = true; - this._offset = this.handle.node.convertToNodeSpaceAR(event.touch.getLocation()); - event.stopPropagation(); - }, - - _onTouchBegan: function (event) { - if (!this.handle) { return; } - this._dragging = true; - if (!this._touchHandle) { - this._handleSliderLogic(event.touch); - } - event.stopPropagation(); - }, - - _onTouchMoved: function (event) { - if (!this._dragging) { return; } - this._handleSliderLogic(event.touch); - event.stopPropagation(); - }, - - _onTouchEnded: function (event) { - this._dragging = false; - this._touchHandle = false; - this._offset = cc.v2(); - event.stopPropagation(); - }, - - _onTouchCancelled: function (event) { - this._dragging = false; - event.stopPropagation(); - }, - - _handleSliderLogic: function (touch) { - this._updateProgress(touch); - this._emitSlideEvent(); - }, - - _emitSlideEvent: function () { - cc.Component.EventHandler.emitEvents(this.slideEvents, this); - this.node.emit('slide', this); - }, - - _updateProgress: function (touch) { - if (!this.handle) { return; } - var localTouchPos = this.node.convertToNodeSpaceAR(touch.getLocation()); - if (this.direction === Direction.Horizontal) { - this.progress = misc.clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width); - } - else { - this.progress = misc.clamp01(0.5 + (localTouchPos.y - this._offset.y) / this.node.height); - } - }, - - _updateHandlePosition: function () { - if (!this.handle) { return; } - var handlelocalPos; - if (this.direction === Direction.Horizontal) { - handlelocalPos = cc.v2(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0); - } - else { - handlelocalPos = cc.v2(0, -this.node.height * this.node.anchorY + this.progress * this.node.height); - } - var worldSpacePos = this.node.convertToWorldSpaceAR(handlelocalPos); - this.handle.node.position = this.handle.node.parent.convertToNodeSpaceAR(worldSpacePos); - } - -}); - -cc.Slider = module.exports = Slider; - -/** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event slide - * @param {Event.EventCustom} event - * @param {Slider} slider - The slider component. - */ diff --git a/cocos/2d/ui/CCToggle.js b/cocos/2d/ui/CCToggle.js deleted file mode 100644 index 5f546d8e89..0000000000 --- a/cocos/2d/ui/CCToggle.js +++ /dev/null @@ -1,243 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -/** - * !#en The toggle component is a CheckBox, when it used together with a ToggleGroup, it - * could be treated as a RadioButton. - * !#zh Toggle 是一个 CheckBox,当它和 ToggleGroup 一起使用的时候,可以变成 RadioButton。 - * @class Toggle - * @extends Button - */ -var Toggle = cc.Class({ - name: 'cc.Toggle', - extends: require('./CCButton'), - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/Toggle', - help: 'i18n:COMPONENT.help_url.toggle', - inspector: 'packages://inspector/inspectors/comps/toggle.js', - }, - - properties: { - /** - * !#en When this value is true, the check mark component will be enabled, otherwise - * the check mark component will be disabled. - * !#zh 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。 - * @property {Boolean} isChecked - */ - isChecked: { - default: true, - tooltip: CC_DEV && 'i18n:COMPONENT.toggle.isChecked', - notify: function () { - this._updateCheckMark(); - } - }, - - /** - * !#en The toggle group which the toggle belongs to, when it is null, the toggle is a CheckBox. - * Otherwise, the toggle is a RadioButton. - * !#zh Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox, - * 否则,Toggle 是一个 RadioButton。 - * @property {ToggleGroup} toggleGroup - */ - toggleGroup: { - default: null, - tooltip: CC_DEV && 'i18n:COMPONENT.toggle.toggleGroup', - type: require('./CCToggleGroup') - }, - - /** - * !#en The image used for the checkmark. - * !#zh Toggle 处于选中状态时显示的图片 - * @property {Sprite} checkMark - */ - checkMark: { - default: null, - type: cc.Sprite, - tooltip: CC_DEV && 'i18n:COMPONENT.toggle.checkMark' - }, - - /** - * !#en If Toggle is clicked, it will trigger event's handler - * !#zh Toggle 按钮的点击事件列表。 - * @property {Component.EventHandler[]} checkEvents - */ - checkEvents: { - default: [], - type: cc.Component.EventHandler - }, - - _resizeToTarget: { - animatable: false, - set: function (value) { - if (value) { - this._resizeNodeToTargetNode(); - } - } - }, - - }, - - onEnable: function () { - this._super(); - if (!CC_EDITOR) { - this._registerToggleEvent(); - } - if (this.toggleGroup && this.toggleGroup.enabled) { - this.toggleGroup.addToggle(this); - } - }, - - onDisable: function () { - this._super(); - if (!CC_EDITOR) { - this._unregisterToggleEvent(); - } - if (this.toggleGroup && this.toggleGroup.enabled) { - this.toggleGroup.removeToggle(this); - } - }, - - _updateCheckMark: function () { - if (this.checkMark) { - this.checkMark.node.active = !!this.isChecked; - } - }, - - _updateDisabledState: function () { - this._super(); - - if (this.checkMark) { - this.checkMark.setState(0); - } - if (this.enableAutoGrayEffect) { - if (this.checkMark && !this.interactable) { - this.checkMark.setState(1); - } - } - }, - - _registerToggleEvent: function () { - this.node.on('click', this.toggle, this); - }, - - _unregisterToggleEvent: function () { - this.node.off('click', this.toggle, this); - }, - - toggle: function (event) { - var group = this.toggleGroup || this._toggleContainer; - - if (group && group.enabled && this.isChecked) { - if (!group.allowSwitchOff) { - return; - } - } - - this.isChecked = !this.isChecked; - - this._updateCheckMark(); - - if (group && group.enabled) { - group.updateToggles(this); - } - - this._emitToggleEvents(event); - }, - - _emitToggleEvents: function () { - this.node.emit('toggle', this); - if (this.checkEvents) { - cc.Component.EventHandler.emitEvents(this.checkEvents, this); - } - }, - - /** - * !#en Make the toggle button checked. - * !#zh 使 toggle 按钮处于选中状态 - * @method check - */ - check: function () { - var group = this.toggleGroup || this._toggleContainer; - - if (group && group.enabled && this.isChecked) { - if (!group.allowSwitchOff) { - return; - } - } - - this.isChecked = true; - - if (group && group.enabled) { - group.updateToggles(this); - } - - this._emitToggleEvents(); - }, - - /** - * !#en Make the toggle button unchecked. - * !#zh 使 toggle 按钮处于未选中状态 - * @method uncheck - */ - uncheck: function () { - var group = this.toggleGroup || this._toggleContainer; - - if (group && group.enabled && this.isChecked) { - if (!group.allowSwitchOff) { - return; - } - } - - this.isChecked = false; - - this._emitToggleEvents(); - } -}); - -cc.Toggle = module.exports = Toggle; - - -var js = require('../platform/js'); - -js.get(Toggle.prototype, '_toggleContainer', - function () { - var parent = this.node.parent; - if (cc.Node.isNode(parent)) { - return parent.getComponent(cc.ToggleContainer); - } - return null; - } -); - -/** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event toggle - * @param {Event.EventCustom} event - * @param {Toggle} toggle - The Toggle component. - */ diff --git a/cocos/2d/ui/CCWidget.js b/cocos/2d/ui/CCWidget.js deleted file mode 100644 index be95904646..0000000000 --- a/cocos/2d/ui/CCWidget.js +++ /dev/null @@ -1,685 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -var WidgetManager = require('../base-ui/CCWidgetManager'); - -/** - * !#en Enum for Widget's alignment mode, indicating when the widget should refresh. - * !#zh Widget 的对齐模式,表示 Widget 应该何时刷新。 - * @enum Widget.AlignMode - */ -/** - * !#en - * Only align once when the Widget is enabled for the first time. - * This will allow the script or animation to continue controlling the current node. - * It will only be aligned once before the end of frame when onEnable is called, - * then immediately disables the Widget. - * !#zh - * 仅在 Widget 第一次激活时对齐一次,便于脚本或动画继续控制当前节点。 - * 开启后会在 onEnable 时所在的那一帧结束前对齐一次,然后立刻禁用该 Widget。 - * @property {Number} ONCE - */ -/** - * !#en Align first from the beginning as ONCE, and then realign it every time the window is resized. - * !#zh 一开始会像 ONCE 一样对齐一次,之后每当窗口大小改变时还会重新对齐。 - * @property {Number} ON_WINDOW_RESIZE - */ -/** - * !#en Keep aligning all the way. - * !#zh 始终保持对齐。 - * @property {Number} ALWAYS - */ -var AlignMode = WidgetManager.AlignMode; - -var AlignFlags = WidgetManager._AlignFlags; -var TOP = AlignFlags.TOP; -var MID = AlignFlags.MID; -var BOT = AlignFlags.BOT; -var LEFT = AlignFlags.LEFT; -var CENTER = AlignFlags.CENTER; -var RIGHT = AlignFlags.RIGHT; -var TOP_BOT = TOP | BOT; -var LEFT_RIGHT = LEFT | RIGHT; - -/** - * !#en - * Stores and manipulate the anchoring based on its parent. - * Widget are used for GUI but can also be used for other things. - * Widget will adjust current node's position and size automatically, but the results after adjustment can not be obtained until the next frame unless you call {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}} manually. - * !#zh - * Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。 - * Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到,除非你先手动调用 {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}}。 - * - * @class Widget - * @extends Component - */ -var Widget = cc.Class({ - name: 'cc.Widget', extends: require('./CCComponent'), - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/Widget', - help: 'i18n:COMPONENT.help_url.widget', - inspector: 'packages://inspector/inspectors/comps/ccwidget.js', - executeInEditMode: true, - disallowMultiple: true, - }, - - properties: { - - /** - * !#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. - * !#zh 指定一个对齐目标,只能是当前节点的其中一个父节点,默认为空,为空时表示当前父节点。 - * @property {Node} target - * @default null - */ - target: { - get: function () { - return this._target; - }, - set: function (value) { - this._target = value; - 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); - } - }, - type: cc.Node, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.target', - }, - - // ENABLE ALIGN ? - - /** - * !#en Whether to align the top. - * !#zh 是否对齐上边。 - * @property isAlignTop - * @type {Boolean} - * @default false - */ - isAlignTop: { - get: function () { - return (this._alignFlags & TOP) > 0; - }, - set: function (value) { - this._setAlign(TOP, value); - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_top', - }, - - /** - * !#en - * Vertically aligns the midpoint, This will open the other vertical alignment options cancel. - * !#zh - * 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。 - * @property isAlignVerticalCenter - * @type {Boolean} - * @default false - */ - isAlignVerticalCenter: { - get: function () { - return (this._alignFlags & MID) > 0; - }, - set: function (value) { - if (value) { - this.isAlignTop = false; - this.isAlignBottom = false; - this._alignFlags |= MID; - } - else { - this._alignFlags &= ~MID; - } - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_v_center', - }, - - /** - * !#en Whether to align the bottom. - * !#zh 是否对齐下边。 - * @property isAlignBottom - * @type {Boolean} - * @default false - */ - isAlignBottom: { - get: function () { - return (this._alignFlags & BOT) > 0; - }, - set: function (value) { - this._setAlign(BOT, value); - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_bottom', - }, - - /** - * !#en Whether to align the left. - * !#zh 是否对齐左边 - * @property isAlignLeft - * @type {Boolean} - * @default false - */ - isAlignLeft: { - get: function () { - return (this._alignFlags & LEFT) > 0; - }, - set: function (value) { - this._setAlign(LEFT, value); - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_left', - }, - - /** - * !#en - * Horizontal aligns the midpoint. This will open the other horizontal alignment options canceled. - * !#zh - * 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。 - * @property isAlignHorizontalCenter - * @type {Boolean} - * @default false - */ - isAlignHorizontalCenter: { - get: function () { - return (this._alignFlags & CENTER) > 0; - }, - set: function (value) { - if (value) { - this.isAlignLeft = false; - this.isAlignRight = false; - this._alignFlags |= CENTER; - } - else { - this._alignFlags &= ~CENTER; - } - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_h_center', - }, - - /** - * !#en Whether to align the right. - * !#zh 是否对齐右边。 - * @property isAlignRight - * @type {Boolean} - * @default false - */ - isAlignRight: { - get: function () { - return (this._alignFlags & RIGHT) > 0; - }, - set: function (value) { - this._setAlign(RIGHT, value); - }, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_right', - }, - - /** - * !#en - * Whether the stretched horizontally, when enable the left and right alignment will be stretched horizontally, - * the width setting is invalid (read only). - * !#zh - * 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸,此时节点的宽度只读。 - * @property isStretchWidth - * @type {Boolean} - * @default false - * @readOnly - */ - isStretchWidth: { - get: function () { - return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT; - }, - visible: false - }, - /** - * !#en - * Whether the stretched vertically, when enable the left and right alignment will be stretched vertically, - * then height setting is invalid (read only) - * !#zh - * 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度只读。 - * @property isStretchHeight - * @type {Boolean} - * @default false - * @readOnly - */ - isStretchHeight: { - get: function () { - return (this._alignFlags & TOP_BOT) === TOP_BOT; - }, - visible: false - }, - - // ALIGN MARGINS - - /** - * !#en - * The margins between the top of this node and the top of parent node, - * the value can be negative, Only available in 'isAlignTop' open. - * !#zh - * 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。 - * @property top - * @type {Number} - * @default 0 - */ - top: { - get: function () { - return this._top; - }, - set: function (value) { - this._top = value; - }, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.top', - }, - - /** - * !#en - * The margins between the bottom of this node and the bottom of parent node, - * the value can be negative, Only available in 'isAlignBottom' open. - * !#zh - * 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。 - * @property bottom - * @type {Number} - * @default 0 - */ - bottom: { - get: function () { - return this._bottom; - }, - set: function (value) { - this._bottom = value; - }, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.bottom', - }, - - /** - * !#en - * The margins between the left of this node and the left of parent node, - * the value can be negative, Only available in 'isAlignLeft' open. - * !#zh - * 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。 - * @property left - * @type {Number} - * @default 0 - */ - left: { - get: function () { - return this._left; - }, - set: function (value) { - this._left = value; - }, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.left', - }, - - /** - * !#en - * The margins between the right of this node and the right of parent node, - * the value can be negative, Only available in 'isAlignRight' open. - * !#zh - * 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。 - * @property right - * @type {Number} - * @default 0 - */ - right: { - get: function () { - return this._right; - }, - set: function (value) { - this._right = value; - }, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.right', - }, - - /** - * !#en - * Horizontal aligns the midpoint offset value, - * the value can be negative, Only available in 'isAlignHorizontalCenter' open. - * !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。 - * @property horizontalCenter - * @type {Number} - * @default 0 - */ - horizontalCenter: { - get: function () { - return this._horizontalCenter; - }, - set: function (value) { - this._horizontalCenter = value; - }, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.horizontal_center', - }, - - /** - * !#en - * Vertical aligns the midpoint offset value, - * the value can be negative, Only available in 'isAlignVerticalCenter' open. - * !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。 - * @property verticalCenter - * @type {Number} - * @default 0 - */ - verticalCenter: { - get: function () { - return this._verticalCenter; - }, - set: function (value) { - this._verticalCenter = value; - }, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.vertical_center', - }, - - // PARCENTAGE OR ABSOLUTE - - /** - * !#en If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin. - * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 - * @property isAbsoluteHorizontalCenter - * @type {Boolean} - * @default true - */ - isAbsoluteHorizontalCenter: { - get: function () { - return this._isAbsHorizontalCenter; - }, - set: function (value) { - this._isAbsHorizontalCenter = value; - }, - animatable: false - }, - - /** - * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin. - * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 - * @property isAbsoluteVerticalCenter - * @type {Boolean} - * @default true - */ - isAbsoluteVerticalCenter: { - get: function () { - return this._isAbsVerticalCenter; - }, - set: function (value) { - this._isAbsVerticalCenter = value; - }, - animatable: false - }, - - /** - * !#en - * If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. - * !#zh - * 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 - * @property isAbsoluteTop - * @type {Boolean} - * @default true - */ - isAbsoluteTop: { - get: function () { - return this._isAbsTop; - }, - set: function (value) { - this._isAbsTop = value; - }, - animatable: false - }, - - /** - * !#en - * If true, bottom is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. - * !#zh - * 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 - * @property isAbsoluteBottom - * @type {Boolean} - * @default true - */ - isAbsoluteBottom: { - get: function () { - return this._isAbsBottom; - }, - set: function (value) { - this._isAbsBottom = value; - }, - animatable: false - }, - - /** - * !#en - * If true, left is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. - * !#zh - * 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 - * @property isAbsoluteLeft - * @type {Boolean} - * @default true - */ - isAbsoluteLeft: { - get: function () { - return this._isAbsLeft; - }, - set: function (value) { - this._isAbsLeft = value; - }, - animatable: false - }, - - /** - * !#en - * If true, right is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. - * !#zh - * 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 - * @property isAbsoluteRight - * @type {Boolean} - * @default true - */ - isAbsoluteRight: { - get: function () { - return this._isAbsRight; - }, - set: function (value) { - this._isAbsRight = value; - }, - animatable: false - }, - - /** - * !#en Specifies the alignment mode of the Widget, which determines when the widget should refresh. - * !#zh 指定 Widget 的对齐模式,用于决定 Widget 应该何时刷新。 - * @property {Widget.AlignMode} alignMode - * @example - * widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE; - */ - alignMode: { - default: AlignMode.ON_WINDOW_RESIZE, - type: AlignMode, - tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_mode', - }, - - // - - _wasAlignOnce: { - default: undefined, - formerlySerializedAs: 'isAlignOnce', - }, - - _target: null, - - /** - * !#zh: 对齐开关,由 AlignFlags 组成 - * - * @property _alignFlags - * @type {Number} - * @default 0 - * @private - */ - _alignFlags: 0, - - _left: 0, - _right: 0, - _top: 0, - _bottom: 0, - _verticalCenter: 0, - _horizontalCenter: 0, - _isAbsLeft: true, - _isAbsRight: true, - _isAbsTop: true, - _isAbsBottom: true, - _isAbsHorizontalCenter: true, - _isAbsVerticalCenter: true, - - // original size before align - _originalWidth: 0, - _originalHeight: 0 - }, - - statics: { - AlignMode: AlignMode, - }, - - onLoad: function () { - if (this._wasAlignOnce !== undefined) { - // migrate for old version - this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; - this._wasAlignOnce = undefined; - } - }, - - onEnable: function () { - WidgetManager.add(this); - }, - - onDisable: function () { - WidgetManager.remove(this); - }, - - _setAlign: function (flag, isAlign) { - var current = (this._alignFlags & flag) > 0; - if (isAlign == current) { - return; - } - var isHorizontal = (flag & LEFT_RIGHT) > 0; - if (isAlign) { - this._alignFlags |= flag; - - if (isHorizontal) { - this.isAlignHorizontalCenter = false; - if (this.isStretchWidth) { - // become stretch - this._originalWidth = this.node.width; - // test check conflict - if (CC_EDITOR && !cc.engine.isPlaying) { - _Scene.DetectConflict.checkConflict_Widget(this); - } - } - } - else { - this.isAlignVerticalCenter = false; - if (this.isStretchHeight) { - // become stretch - this._originalHeight = this.node.height; - // test check conflict - if (CC_EDITOR && !cc.engine.isPlaying) { - _Scene.DetectConflict.checkConflict_Widget(this); - } - } - } - - 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); - } - } - else { - if (isHorizontal) { - if (this.isStretchWidth) { - // will cancel stretch - this.node.width = this._originalWidth; - } - } - else { - if (this.isStretchHeight) { - // will cancel stretch - this.node.height = this._originalHeight; - } - } - - this._alignFlags &= ~flag; - } - }, - - /** - * !#en - * Immediately perform the widget alignment. You need to manually call this method only if - * you need to get the latest results after the alignment before the end of current frame. - * !#zh - * 立刻执行 widget 对齐操作。这个接口一般不需要手工调用。 - * 只有当你需要在当前帧结束前获得 widget 对齐后的最新结果时才需要手动调用这个方法。 - * - * @method updateAlignment - * - * @example - * widget.top = 10; // change top margin - * cc.log(widget.node.y); // not yet changed - * widget.updateAlignment(); - * cc.log(widget.node.y); // changed - */ - updateAlignment: function () { - WidgetManager.updateAlignment(this.node); - }, -}); - -/** - * !#en - * When turned on, it will only be aligned once at the end of the onEnable frame, - * then immediately disables the current component. - * This will allow the script or animation to continue controlling the current node. - * Note: It will still be aligned at the frame when onEnable is called. - * !#zh - * 开启后仅会在 onEnable 的当帧结束时对齐一次,然后立刻禁用当前组件。 - * 这样便于脚本或动画继续控制当前节点。 - * 注意:onEnable 时所在的那一帧仍然会进行对齐。 - * @property {Boolean} isAlignOnce - * @default false - * @deprecated - */ -Object.defineProperty(Widget.prototype, 'isAlignOnce', { - get () { - if (CC_DEBUG) { - cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode === cc.Widget.AlignMode.ONCE` instead please.'); - } - return this.alignMode === AlignMode.ONCE; - }, - set (value) { - if (CC_DEBUG) { - cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode = cc.Widget.AlignMode.*` instead please.'); - } - this.alignMode = value ? AlignMode.ONCE : AlignMode.ALWAYS; - } -}); - - -cc.Widget = module.exports = Widget; diff --git a/cocos/2d/ui/editbox/CCEditBox.js b/cocos/2d/ui/editbox/CCEditBox.js deleted file mode 100644 index b6b5be0ffd..0000000000 --- a/cocos/2d/ui/editbox/CCEditBox.js +++ /dev/null @@ -1,729 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const macro = require('../../platform/CCMacro'); -const EditBoxImpl = require('../editbox/CCEditBoxImpl'); -const Label = require('../CCLabel'); -const Types = require('./types'); -const InputMode = Types.InputMode; -const InputFlag = Types.InputFlag; -const KeyboardReturnType = Types.KeyboardReturnType; - -const LEFT_PADDING = 2; - -function capitalize (string) { - return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); -} - -function capitalizeFirstLetter (string) { - return string.charAt(0).toUpperCase() + string.slice(1); -} - - -/** - * !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users. - * !#zh EditBox 组件,用于获取用户的输入文本。 - * @class EditBox - * @extends Component - */ -let EditBox = cc.Class({ - name: 'cc.EditBox', - extends: cc.Component, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/EditBox', - inspector: 'packages://inspector/inspectors/comps/cceditbox.js', - help: 'i18n:COMPONENT.help_url.editbox', - executeInEditMode: true, - }, - - properties: { - _useOriginalSize: true, - _string: '', - /** - * !#en Input string of EditBox. - * !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。 - * @property {String} string - */ - string: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.string', - get () { - return this._string; - }, - set(value) { - if (this.maxLength >= 0 && value.length >= this.maxLength) { - value = value.slice(0, this.maxLength); - } - - this._string = value; - if (this._impl) { - this._updateString(value); - } - } - }, - - /** - * !#en The background image of EditBox. - * !#zh 输入框的背景图片 - * @property {SpriteFrame} backgroundImage - */ - backgroundImage: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.backgroundImage', - default: null, - type: cc.SpriteFrame, - notify () { - this._createBackgroundSprite(); - } - }, - - /** - * !#en - * The return key type of EditBox. - * Note: it is meaningless for web platforms and desktop platforms. - * !#zh - * 指定移动设备上面回车按钮的样式。 - * 注意:这个选项对 web 平台与 desktop 平台无效。 - * @property {EditBox.KeyboardReturnType} returnType - * @default KeyboardReturnType.DEFAULT - */ - returnType: { - default: KeyboardReturnType.DEFAULT, - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.returnType', - displayName: 'KeyboardReturnType', - type: KeyboardReturnType, - notify () { - if (this._impl) { - this._impl.returnType = this.returnType; - } - } - }, - - /** - * !#en Set the input flags that are to be applied to the EditBox. - * !#zh 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。 - * @property {EditBox.InputFlag} inputFlag - * @default InputFlag.DEFAULT - */ - inputFlag: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.input_flag', - default: InputFlag.DEFAULT, - type: InputFlag, - notify () { - if (this._impl) { - this._impl.setInputFlag(this.inputFlag); - this._updateString(this._string); - } - } - }, - /** - * !#en - * Set the input mode of the edit box. - * If you pass ANY, it will create a multiline EditBox. - * !#zh - * 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。 - * @property {EditBox.InputMode} inputMode - * @default InputMode.ANY - */ - inputMode: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.input_mode', - default: InputMode.ANY, - type: InputMode, - notify () { - if (this._impl) { - this._impl.setInputMode(this.inputMode); - } - } - }, - - /** - * !#en Font size of the input text. - * !#zh 输入框文本的字体大小 - * @property {Number} fontSize - */ - fontSize: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.font_size', - default: 20, - notify () { - if (this._textLabel) { - this._textLabel.fontSize = this.fontSize; - } - if (this._impl) { - this._impl.setFontSize(this.fontSize); - } - } - }, - - /** - * !#en Change the lineHeight of displayed text. - * !#zh 输入框文本的行高。 - * @property {Number} lineHeight - */ - lineHeight: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.line_height', - default: 40, - notify () { - if (this._textLabel) { - this._textLabel.lineHeight = this.lineHeight; - } - } - }, - - /** - * !#en Font color of the input text. - * !#zh 输入框文本的颜色。 - * @property {Color} fontColor - */ - fontColor: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.font_color', - default: cc.Color.WHITE, - notify () { - if (this._textLabel) { - this._textLabel.node.opacity = this.fontColor.a; - this._textLabel.node.color = this.fontColor; - } - if (this._impl) { - this._impl.setFontColor(this.fontColor); - } - } - }, - - /** - * !#en The display text of placeholder. - * !#zh 输入框占位符的文本内容。 - * @property {String} placeholder - */ - placeholder: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder', - default: 'Enter text here...', - notify () { - if (this._placeholderLabel) { - this._placeholderLabel.string = this.placeholder; - } - if (this._impl) { - this._impl.setPlaceholderText(this.placeholder); - } - } - }, - - /** - * !#en The font size of placeholder. - * !#zh 输入框占位符的字体大小。 - * @property {Number} placeholderFontSize - */ - placeholderFontSize: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder_font_size', - default: 20, - notify () { - if (this._placeholderLabel) { - this._placeholderLabel.fontSize = this.placeholderFontSize; - } - } - }, - - /** - * !#en The font color of placeholder. - * !#zh 输入框占位符的字体颜色。 - * @property {Color} placeholderFontColor - */ - placeholderFontColor: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder_font_color', - default: cc.Color.GRAY, - notify () { - if (this._placeholderLabel) { - this._placeholderLabel.node.color = this.placeholderFontColor; - this._placeholderLabel.node.opacity = this.placeholderFontColor.a; - } - } - }, - - /** - * !#en The maximize input length of EditBox. - * - If pass a value less than 0, it won't limit the input number of characters. - * - If pass 0, it doesn't allow input any characters. - * !#zh 输入框最大允许输入的字符个数。 - * - 如果值为小于 0 的值,则不会限制输入字符个数。 - * - 如果值为 0,则不允许用户进行任何输入。 - * @property {Number} maxLength - */ - maxLength: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.max_length', - default: 20, - notify () { - if (this._impl) { - this._impl.setMaxLength(this.maxLength); - } - } - }, - - /** - * !#en The input is always visible and be on top of the game view (only useful on Web). - * !zh 输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义) - * Note: only available on Web at the moment. - * @property {Boolean} stayOnTop - */ - stayOnTop: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.stay_on_top', - default: false, - notify () { - if (this._impl) { - this._updateStayOnTop(); - } - } - }, - - _tabIndex: 0, - - /** - * !#en Set the tabIndex of the DOM input element (only useful on Web). - * !#zh 修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)。 - * @property {Number} tabIndex - */ - tabIndex: { - tooltip: CC_DEV && 'i18n:COMPONENT.editbox.tab_index', - get () { - return this._tabIndex; - }, - set (value) { - this._tabIndex = value; - if (this._impl) { - this._impl.setTabIndex(value); - } - } - }, - - /** - * !#en The event handler to be called when EditBox began to edit text. - * !#zh 开始编辑文本输入框触发的事件回调。 - * @property {Component.EventHandler[]} editingDidBegan - */ - editingDidBegan: { - default: [], - type: cc.Component.EventHandler, - }, - - /** - * !#en The event handler to be called when EditBox text changes. - * !#zh 编辑文本输入框时触发的事件回调。 - * @property {Component.EventHandler[]} textChanged - */ - textChanged: { - default: [], - type: cc.Component.EventHandler, - }, - - /** - * !#en The event handler to be called when EditBox edit ends. - * !#zh 结束编辑文本输入框时触发的事件回调。 - * @property {Component.EventHandler[]} editingDidEnded - */ - editingDidEnded: { - default: [], - type: cc.Component.EventHandler, - }, - - /** - * !#en The event handler to be called when return key is pressed. Windows is not supported. - * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台 - * @property {Component.EventHandler[]} editingReturn - */ - editingReturn: { - default: [], - type: cc.Component.EventHandler - } - - }, - - statics: { - _EditBoxImpl: EditBoxImpl, - KeyboardReturnType: KeyboardReturnType, - InputFlag: InputFlag, - InputMode: InputMode - }, - - _init () { - this._createBackgroundSprite(); - this._createLabels(); - this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this); - - let impl = this._impl = new EditBoxImpl(); - - impl.setDelegate(this); - impl.setNode(this.node); - impl.setInputMode(this.inputMode); - impl.setMaxLength(this.maxLength); - impl.setInputFlag(this.inputFlag); - impl.setReturnType(this.returnType); - impl.setTabIndex(this.tabIndex); - impl.setFontColor(this.fontColor); - impl.setFontSize(this.fontSize); - impl.setPlaceholderText(this.placeholder); - - this._updateStayOnTop(); - this._updateString(this.string); - this._syncSize(); - }, - - _updateStayOnTop () { - if (this.stayOnTop) { - this._hideLabels(); - } - else { - this._showLabels(); - } - this._impl.stayOnTop(this.stayOnTop); - }, - - _syncSize () { - let size = this.node.getContentSize(); - - this._background.node.setAnchorPoint(this.node.getAnchorPoint()); - this._background.node.setContentSize(size); - - this._updateLabelPosition(size); - this._impl.setSize(size.width, size.height); - }, - - _updateLabelPosition (size) { - let node = this.node; - let offx = -node.anchorX * node.width; - let offy = -node.anchorY * node.height; - - let placeholderLabel = this._placeholderLabel; - let textLabel = this._textLabel; - - textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); - placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); - placeholderLabel.lineHeight = size.height; - - placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); - textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); - - if (this.inputMode === InputMode.ANY){ - placeholderLabel.verticalAlign = macro.VerticalTextAlignment.TOP; - placeholderLabel.enableWrapText = true; - textLabel.verticalAlign = macro.VerticalTextAlignment.TOP; - textLabel.enableWrapText = true; - } - else { - placeholderLabel.verticalAlign = macro.VerticalTextAlignment.CENTER; - placeholderLabel.enableWrapText = false; - textLabel.verticalAlign = macro.VerticalTextAlignment.CENTER; - textLabel.enableWrapText = false; - } - }, - - _createBackgroundSprite () { - let background = this._background; - if (!background) { - let node = this.node.getChildByName('BACKGROUND_SPRITE'); - if (!node) { - node = new cc.Node('BACKGROUND_SPRITE'); - } - - background = node.getComponent(cc.Sprite); - if (!background) { - background = node.addComponent(cc.Sprite); - } - background.type = cc.Sprite.Type.SLICED; - - node.parent = this.node; - this._background = background; - } - background.spriteFrame = this.backgroundImage; - }, - - _createLabels () { - if (!this._textLabel) { - let node = this.node.getChildByName('TEXT_LABEL'); - if (!node) { - node = new cc.Node('TEXT_LABEL'); - } - node.color = this.fontColor; - node.parent = this.node; - node.setAnchorPoint(0, 1); - - let textLabel = node.getComponent(Label); - if (!textLabel) { - textLabel = node.addComponent(Label); - } - textLabel.overflow = Label.Overflow.CLAMP; - textLabel.fontSize = this.fontSize; - textLabel.lineHeight = this.lineHeight; - this._textLabel = textLabel; - } - - if (!this._placeholderLabel) { - let node = this.node.getChildByName('PLACEHOLDER_LABEL'); - if (!node) { - node = new cc.Node('PLACEHOLDER_LABEL'); - } - node.color = this.placeholderFontColor; - node.parent = this.node; - node.setAnchorPoint(0, 1); - - let placeholderLabel = node.getComponent(Label); - if (!placeholderLabel) { - placeholderLabel = node.addComponent(Label); - } - placeholderLabel.overflow = Label.Overflow.CLAMP; - placeholderLabel.fontSize = this.placeholderFontSize; - placeholderLabel.string = this.placeholder; - this._placeholderLabel = placeholderLabel; - } - }, - - _resizeChildNodes () { - let textLabelNode = this._textLabel.node, - placeholderLabelNode = this._placeholderLabel.node, - backgroundNode = this._background.node; - - textLabelNode.x = -this.node.width/2; - textLabelNode.y = this.node.height/2; - textLabelNode.width = this.node.width; - textLabelNode.height = this.node.height; - - placeholderLabelNode.x = -this.node.width/2; - placeholderLabelNode.y = this.node.height/2; - placeholderLabelNode.width = this.node.width; - placeholderLabelNode.height = this.node.height; - - backgroundNode.width = this.node.width; - backgroundNode.height = this.node.height; - }, - - _showLabels () { - let displayText = this._textLabel.string; - this._textLabel.node.active = displayText !== ''; - this._placeholderLabel.node.active = displayText === ''; - }, - - _hideLabels () { - this._textLabel.node.active = false; - this._placeholderLabel.node.active = false; - }, - - _updateString (text) { - let textLabel = this._textLabel; - // Not inited yet - if (!textLabel) { - return; - } - - let displayText = text; - if (displayText) { - displayText = this._updateLabelStringStyle(displayText); - } - - textLabel.string = displayText; - this._impl.setString(text); - if (!this._impl._editing && !this.stayOnTop) { - this._showLabels(); - } - }, - - _updateLabelStringStyle (text, ignorePassword) { - let inputFlag = this.inputFlag; - if (!ignorePassword && inputFlag === InputFlag.PASSWORD) { - let passwordString = ''; - let len = text.length; - for (let i = 0; i < len; ++i) { - passwordString += '\u25CF'; - } - text = passwordString; - } - else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { - text = text.toUpperCase(); - } - else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { - text = capitalize(text); - } - else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) { - text = capitalizeFirstLetter(text); - } - - return text; - }, - - editBoxEditingDidBegan () { - this._hideLabels(); - cc.Component.EventHandler.emitEvents(this.editingDidBegan, this); - this.node.emit('editing-did-began', this); - }, - - editBoxEditingDidEnded () { - if (!this.stayOnTop) { - this._showLabels(); - } - cc.Component.EventHandler.emitEvents(this.editingDidEnded, this); - this.node.emit('editing-did-ended', this); - }, - - editBoxTextChanged (text) { - text = this._updateLabelStringStyle(text, true); - this.string = text; - cc.Component.EventHandler.emitEvents(this.textChanged, text, this); - this.node.emit('text-changed', this); - }, - - editBoxEditingReturn() { - cc.Component.EventHandler.emitEvents(this.editingReturn, this); - this.node.emit('editing-return', this); - }, - - onDestroy () { - this._impl.clear(); - }, - - onEnable () { - this._impl && this._impl.onEnable(); - }, - - onDisable () { - this._impl && this._impl.onDisable(); - }, - - __preload () { - if (!CC_EDITOR) { - this._registerEvent(); - } - this._init(); - }, - - _registerEvent () { - this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); - }, - - _onTouchBegan (event) { - if (this._impl) { - this._impl._onTouchBegan(event.touch); - } - event.stopPropagation(); - }, - - _onTouchCancel (event) { - if (this._impl) { - this._impl._onTouchCancel(); - } - event.stopPropagation(); - }, - - _onTouchEnded (event) { - if (this._impl) { - this._impl._onTouchEnded(); - } - event.stopPropagation(); - }, - - /** - * !#en Let the EditBox get focus - * !#zh 让当前 EditBox 获得焦点 - * @method setFocus - */ - setFocus () { - if(this._impl) { - this._impl.setFocus(); - } - }, - - /** - * !#en Determine whether EditBox is getting focus or not. - * !#zh 判断 EditBox 是否获得了焦点 - * Note: only available on Web at the moment. - * @method isFocused - */ - isFocused () { - let isFocused = false; - if (this._impl) { - isFocused = this._impl.isFocused(); - } - return isFocused; - }, - - update () { - if (this._impl) { - this._impl.update(); - } - } - -}); - -cc.EditBox = module.exports = EditBox; - -/** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event editing-did-began - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - -/** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event editing-did-ended - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - -/** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event text-changed - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - -/** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event editing-return - * @param {Event.EventCustom} event - * @param {EditBox} editbox - The EditBox component. - */ - -/** - * !#en if you don't need the EditBox and it isn't in any running Scene, you should - * call the destroy method on this component or the associated node explicitly. - * Otherwise, the created DOM element won't be removed from web page. - * !#zh - * 如果你不再使用 EditBox,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。 - * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。 - * @example - * editbox.node.parent = null; // or editbox.node.removeFromParent(false); - * // when you don't need editbox anymore - * editbox.node.destroy(); - * @method destroy - * @return {Boolean} whether it is the first time the destroy being called - */ diff --git a/cocos/2d/ui/editbox/CCEditBoxImpl.js b/cocos/2d/ui/editbox/CCEditBoxImpl.js deleted file mode 100644 index f198c565d7..0000000000 --- a/cocos/2d/ui/editbox/CCEditBoxImpl.js +++ /dev/null @@ -1,648 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2012 James Chen - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -const utils = require('../../platform/utils'); -const macro = require('../../platform/CCMacro'); -const Types = require('./types'); -const InputMode = Types.InputMode; -const InputFlag = Types.InputFlag; -const KeyboardReturnType = Types.KeyboardReturnType; - -// https://segmentfault.com/q/1010000002914610 -let SCROLLY = 40; -let LEFT_PADDING = 2; -let DELAY_TIME = 400; -let FOCUS_DELAY_UC = 400; -let FOCUS_DELAY_FIREFOX = 0; - -let math = cc.vmath; -let _matrix = math.mat4.create(); -let _matrix_temp = math.mat4.create(); -let _vec3 = cc.v3(); - -let _currentEditBoxImpl = null; - -// polyfill -let polyfill = { - zoomInvalid: false -}; - -if (cc.sys.OS_ANDROID === cc.sys.os && - (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU || - cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { - polyfill.zoomInvalid = true; -} - -function getKeyboardReturnType (type) { - switch (type) { - case KeyboardReturnType.DEFAULT: - case KeyboardReturnType.DONE: - return 'done'; - case KeyboardReturnType.SEND: - return 'send'; - case KeyboardReturnType.SEARCH: - return 'search'; - case KeyboardReturnType.GO: - return 'go'; - case KeyboardReturnType.NEXT: - return 'next'; - } - return 'done'; -} - -let EditBoxImpl = cc.Class({ - ctor () { - this._delegate = null; - this._inputMode = -1; - this._inputFlag = -1; - this._returnType = KeyboardReturnType.DEFAULT; - this._maxLength = 50; - this._text = ''; - this._placeholderText = ''; - this._alwaysOnTop = false; - this._size = cc.size(); - this._node = null; - this._editing = false; - - this.__eventListeners = {}; - this.__fullscreen = false; - this.__autoResize = false; - this.__rotateScreen = false; - this.__orientationChanged = null; - }, - - onEnable () { - if (!this._edTxt) { - return; - } - if (this._alwaysOnTop) { - this._edTxt.style.display = ''; - } - else { - this._edTxt.style.display = 'none'; - } - }, - - onDisable () { - if (!this._edTxt) { - return; - } - this._edTxt.style.display = 'none'; - }, - - setTabIndex (index) { - if (this._edTxt) { - this._edTxt.tabIndex = index; - } - }, - - setFocus () { - this._beginEditing(); - }, - - isFocused() { - if (this._edTxt) { - return document.activeElement === this._edTxt; - } - cc.warnID(4700); - return false; - }, - - stayOnTop (flag) { - if(this._alwaysOnTop === flag || !this._edTxt) return; - - this._alwaysOnTop = flag; - - if (flag) { - this._edTxt.style.display = ''; - } else { - this._edTxt.style.display = 'none'; - } - }, - - setMaxLength (maxLength) { - if (!isNaN(maxLength)) { - if(maxLength < 0) { - //we can't set Number.MAX_VALUE to input's maxLength property - //so we use a magic number here, it should works at most use cases. - maxLength = 65535; - } - this._maxLength = maxLength; - this._edTxt && (this._edTxt.maxLength = maxLength); - } - }, - - setString (text) { - this._text = text; - this._edTxt && (this._edTxt.value = text); - }, - - getString () { - return this._text; - }, - - setPlaceholderText (text) { - this._placeholderText = text; - }, - - getPlaceholderText () { - return this._placeholderText; - }, - - setDelegate (delegate) { - this._delegate = delegate; - }, - - setInputMode (inputMode) { - if (this._inputMode === inputMode) return; - - this._inputMode = inputMode; - this.createInput(); - - this._updateDomInputType(); - this._updateSize(this._size.width, this._size.height); - }, - - setInputFlag (inputFlag) { - if (this._inputFlag === inputFlag) return; - - this._inputFlag = inputFlag; - this._updateDomInputType(); - - let textTransform = 'none'; - - if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { - textTransform = 'uppercase'; - } - else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { - textTransform = 'capitalize'; - } - - if (this._edTxt) { - this._edTxt.style.textTransform = textTransform; - this._edTxt.value = this._text; - } - }, - - setReturnType (returnType) { - this._returnType = returnType; - this._updateDomInputType(); - }, - - setFontSize (fontSize) { - this._edFontSize = fontSize || this._edFontSize; - this._edTxt && (this._edTxt.style.fontSize = this._edFontSize + 'px'); - }, - - setFontColor (color) { - this._textColor = color; - this._edTxt && (this._edTxt.style.color = color.toCSS('rgba')); - }, - - setSize (width, height) { - this._size.width = width; - this._size.height = height; - this._updateSize(width, height); - }, - - setNode (node) { - this._node = node; - }, - - update () { - // TODO: find better way to update matrix - // if (this._editing) { - this._updateMatrix(); - // } - }, - - clear () { - this._node = null; - this.setDelegate(null); - this.removeDom(); - }, - - _onTouchBegan (touch) { - - }, - - _onTouchEnded () { - this._beginEditing(); - }, - - _beginEditing () { - if (cc.sys.isMobile && !this._editing) { - // Pre adaptation - this._beginEditingOnMobile(); - } - - if (this._edTxt) { - this._edTxt.style.display = ''; - - let self = this; - function startFocus () { - self._edTxt.focus(); - } - - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { - setTimeout(startFocus, FOCUS_DELAY_UC); - } - else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { - setTimeout(startFocus, FOCUS_DELAY_FIREFOX); - } - else { - startFocus(); - } - } - - this._editing = true; - }, - - _endEditing () { - let self = this; - let hideDomInputAndShowLabel = function () { - if (!self._alwaysOnTop && self._edTxt) { - self._edTxt.style.display = 'none'; - } - if (self._delegate && self._delegate.editBoxEditingDidEnded) { - self._delegate.editBoxEditingDidEnded(); - } - }; - if (this._editing) { - if (cc.sys.isMobile) { - // Delay end editing adaptation to ensure virtual keyboard is disapeared - setTimeout(function () { - self._endEditingOnMobile(); - hideDomInputAndShowLabel(); - }, DELAY_TIME); - } - else { - hideDomInputAndShowLabel(); - } - } - this._editing = false; - }, - - _updateDomInputType () { - let inputMode = this._inputMode; - let edTxt = this._edTxt; - if (!edTxt) return; - - if (this._inputFlag === InputFlag.PASSWORD) { - edTxt.type = 'password'; - return; - } - - let type = edTxt.type; - if (inputMode === InputMode.EMAIL_ADDR) { - type = 'email'; - } else if(inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) { - type = 'number'; - } else if(inputMode === InputMode.PHONE_NUMBER) { - type = 'number'; - edTxt.pattern = '[0-9]*'; - } else if(inputMode === InputMode.URL) { - type = 'url'; - } else { - type = 'text'; - - if (this._returnType === KeyboardReturnType.SEARCH) { - type = 'search'; - } - } - - edTxt.type = type; - }, - - _updateSize (newWidth, newHeight) { - let edTxt = this._edTxt; - if (!edTxt) return; - - edTxt.style.width = newWidth + 'px'; - edTxt.style.height = newHeight + 'px'; - }, - - _updateMatrix () { - if (!this._edTxt) return; - - let node = this._node, - scaleX = cc.view._scaleX, scaleY = cc.view._scaleY, - viewport = cc.view._viewportRect, - dpr = cc.view._devicePixelRatio; - - node.getWorldMatrix(_matrix); - let contentSize = node._contentSize; - _vec3.x = -node._anchorPoint.x * contentSize.width; - _vec3.y = -node._anchorPoint.y * contentSize.height; - - math.mat4.translate(_matrix, _matrix, _vec3); - - let camera; - // can't find camera in editor - if (CC_EDITOR) { - camera = cc.Camera.main; - } - else { - camera = cc.Camera.findCamera(node); - } - - camera.getWorldToCameraMatrix(_matrix_temp); - math.mat4.mul(_matrix_temp, _matrix_temp, _matrix); - - scaleX /= dpr; - scaleY /= dpr; - - let container = cc.game.container; - let a = _matrix_temp.m00 * scaleX, b = _matrix.m01, c = _matrix.m04, d = _matrix_temp.m05 * scaleY; - - let offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); - offsetX += viewport.x / dpr; - let offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); - offsetY += viewport.y / dpr; - let tx = _matrix_temp.m12 * scaleX + offsetX, ty = _matrix_temp.m13 * scaleY + offsetY; - - if (polyfill.zoomInvalid) { - this._updateSize(this._size.width * a, this._size.height * d); - a = 1; - d = 1; - } - - let matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; - this._edTxt.style['transform'] = matrix; - this._edTxt.style['-webkit-transform'] = matrix; - this._edTxt.style['transform-origin'] = '0px 100% 0px'; - this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; - }, - - _adjustEditBoxPosition () { - this._node.getWorldMatrix(_matrix); - let y = _matrix.m13; - let windowHeight = cc.visibleRect.height; - let windowWidth = cc.visibleRect.width; - let factor = 0.5; - if (windowWidth > windowHeight) { - factor = 0.7; - } - setTimeout(function() { - if (window.scrollY < SCROLLY && y < windowHeight * factor) { - let scrollOffset = windowHeight * factor - y - window.scrollY; - if (scrollOffset < 35) scrollOffset = 35; - if (scrollOffset > 320) scrollOffset = 320; - window.scrollTo(0, scrollOffset); - } - }, DELAY_TIME); - } -}); - -let _p = EditBoxImpl.prototype; - -_p.createInput = function() { - if (this._inputMode === InputMode.ANY) { - this._createDomTextArea(); - } - else { - this._createDomInput(); - } -}; - -// Called before editbox focus to register cc.view status -_p._beginEditingOnMobile = function () { - let self = this; - this.__orientationChanged = function () { - self._adjustEditBoxPosition(); - }; - window.addEventListener('orientationchange', this.__orientationChanged); - - if (cc.view.isAutoFullScreenEnabled()) { - this.__fullscreen = true; - cc.view.enableAutoFullScreen(false); - cc.screen.exitFullScreen(); - } else { - this.__fullscreen = false; - } - this.__autoResize = cc.view._resizeWithBrowserSize; - cc.view.resizeWithBrowserSize(false); - _currentEditBoxImpl = this; -}; - -// Called after keyboard disappeared to readapte the game view -_p._endEditingOnMobile = function () { - if (this.__rotateScreen) { - cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; - cc.game.container.style.transform = 'rotate(90deg)'; - - let view = cc.view; - let width = view._originalDesignResolutionSize.width; - let height = view._originalDesignResolutionSize.height; - if (width > 0) { - view.setDesignResolutionSize(width, height, view._resolutionPolicy); - } - this.__rotateScreen = false; - } - - window.removeEventListener('orientationchange', this.__orientationChanged); - - if(this.__fullscreen) { - cc.view.enableAutoFullScreen(true); - } - - // In case focus on editBox A from editBox B - // A disable resizeWithBrowserSize - // whilte B enable resizeWithBrowserSize - // Only _currentEditBoxImpl can enable resizeWithBrowserSize - if (this.__autoResize && _currentEditBoxImpl === this) { - cc.view.resizeWithBrowserSize(true); - } -}; - -function _inputValueHandle (input, editBoxImpl) { - if (input.value.length > editBoxImpl._maxLength) { - input.value = input.value.slice(0, editBoxImpl._maxLength); - } - if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxTextChanged) { - if (editBoxImpl._text !== input.value) { - editBoxImpl._text = input.value; - editBoxImpl._delegate.editBoxTextChanged(editBoxImpl._text); - } - } -} - -function registerInputEventListener (tmpEdTxt, editBoxImpl, isTextarea) { - let inputLock = false; - let cbs = editBoxImpl.__eventListeners; - cbs.compositionstart = function () { - inputLock = true; - }; - tmpEdTxt.addEventListener('compositionstart', cbs.compositionstart); - - cbs.compositionend = function () { - inputLock = false; - _inputValueHandle(this, editBoxImpl); - }; - tmpEdTxt.addEventListener('compositionend', cbs.compositionend); - - cbs.input = function () { - if (inputLock) { - return; - } - _inputValueHandle(this, editBoxImpl); - }; - tmpEdTxt.addEventListener('input', cbs.input); - - cbs.focus = function () { - this.style.fontSize = editBoxImpl._edFontSize + 'px'; - this.style.color = editBoxImpl._textColor.toCSS('rgba'); - // When stayOnTop, input will swallow touch event - if (editBoxImpl._alwaysOnTop) { - editBoxImpl._editing = true; - } - - if (cc.sys.isMobile) { - editBoxImpl._beginEditingOnMobile(); - } - - if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingDidBegan) { - editBoxImpl._delegate.editBoxEditingDidBegan(); - } - - }; - tmpEdTxt.addEventListener('focus', cbs.focus); - - cbs.keypress = function (e) { - if (e.keyCode === macro.KEY.enter) { - e.stopPropagation(); - - if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingReturn) { - editBoxImpl._delegate.editBoxEditingReturn(); - } - if (!isTextarea) { - editBoxImpl._text = this.value; - editBoxImpl._endEditing(); - cc.game.canvas.focus(); - } - } - }; - tmpEdTxt.addEventListener('keypress', cbs.keypress); - - cbs.blur = function () { - editBoxImpl._text = this.value; - editBoxImpl._endEditing(); - }; - tmpEdTxt.addEventListener('blur', cbs.blur); - - editBoxImpl._addDomToGameContainer(); -} - -_p._createDomInput = function () { - this.removeDom(); - - let tmpEdTxt = this._edTxt = document.createElement('input'); - tmpEdTxt.type = 'text'; - tmpEdTxt.style.fontSize = this._edFontSize + 'px'; - tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = 0; - tmpEdTxt.style.background = 'transparent'; - tmpEdTxt.style.width = '100%'; - tmpEdTxt.style.height = '100%'; - tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = 'medium'; - tmpEdTxt.style.padding = '0'; - tmpEdTxt.style.textTransform = 'uppercase'; - tmpEdTxt.style.display = 'none'; - tmpEdTxt.style.position = "absolute"; - tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = LEFT_PADDING + "px"; - tmpEdTxt.style['-moz-appearance'] = 'textfield'; - tmpEdTxt.style.className = "cocosEditBox"; - tmpEdTxt.style.fontFamily = 'Arial'; - - registerInputEventListener(tmpEdTxt, this); - - return tmpEdTxt; -}; - -_p._createDomTextArea = function () { - this.removeDom(); - - let tmpEdTxt = this._edTxt = document.createElement('textarea'); - tmpEdTxt.type = 'text'; - tmpEdTxt.style.fontSize = this._edFontSize + 'px'; - tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = 0; - tmpEdTxt.style.background = 'transparent'; - tmpEdTxt.style.width = '100%'; - tmpEdTxt.style.height = '100%'; - tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = 'medium'; - tmpEdTxt.style.padding = '0'; - tmpEdTxt.style.resize = 'none'; - tmpEdTxt.style.textTransform = 'uppercase'; - tmpEdTxt.style.overflow_y = 'scroll'; - tmpEdTxt.style.display = 'none'; - tmpEdTxt.style.position = "absolute"; - tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = LEFT_PADDING + "px"; - tmpEdTxt.style.className = "cocosEditBox"; - tmpEdTxt.style.fontFamily = 'Arial'; - - registerInputEventListener(tmpEdTxt, this, true); - - return tmpEdTxt; -}; - -_p._addDomToGameContainer = function () { - cc.game.container.appendChild(this._edTxt); -}; - -_p.removeDom = function () { - let edTxt = this._edTxt; - if (edTxt) { - // Remove listeners - let cbs = this.__eventListeners; - edTxt.removeEventListener('compositionstart', cbs.compositionstart); - edTxt.removeEventListener('compositionend', cbs.compositionend); - edTxt.removeEventListener('input', cbs.input); - edTxt.removeEventListener('focus', cbs.focus); - edTxt.removeEventListener('keypress', cbs.keypress); - edTxt.removeEventListener('blur', cbs.blur); - cbs.compositionstart = null; - cbs.compositionend = null; - cbs.input = null; - cbs.focus = null; - cbs.keypress = null; - cbs.blur = null; - - let hasChild = utils.contains(cc.game.container, edTxt); - if (hasChild) { - cc.game.container.removeChild(edTxt); - } - } - this._edTxt = null; -}; - -module.exports = EditBoxImpl; diff --git a/cocos/3d/assets/animation-clip.js b/cocos/3d/assets/animation-clip.js deleted file mode 100644 index 1050517473..0000000000 --- a/cocos/3d/assets/animation-clip.js +++ /dev/null @@ -1,398 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -// @ts-check -import { _decorator } from "../../core/data/index"; -const { ccclass, property } = _decorator; -import Asset from "../../assets/CCAsset"; -import vec3 from "../../core/vmath/vec3"; -import quat from "../../core/vmath/quat"; -import { clamp } from "../../core/vmath/utils"; - -/** - * @typedef {import("../framework/skeleton-instance").SkeletonMask} SkeletonMask - * @typedef {import("../../scene-graph/node").default} Node - */ - -let tmpvec3 = vec3.create(0, 0, 0); -let tmpquat = quat.create(); - -function _binaryIndexOf(array, key) { - let lo = 0; - let hi = array.length - 1; - let mid; - - while (lo <= hi) { - mid = ((lo + hi) >> 1); - let val = array[mid]; - - if (val < key) { - lo = mid + 1; - } else if (val > key) { - hi = mid - 1; - } else { - return mid; - } - } - - return lo; -} - -@ccclass('cc.AnimationChannel') -export class AnimationChannel { - /** - * Target node's path into virtual hierarchy. - * @type {string} - */ - @property - target = ""; - - /** - * Target node's position animation curve. - * @type {cc.Vec3[]} - */ - @property - positionCurve = []; - - /** - * Target node's scale animation curve. - * @type {cc.Vec3[]} - */ - @property - scaleCurve = []; - - /** - * Target node's rotation animation curve. - * @type {cc.Quat[]} - */ - @property - rotationCurve = []; -} -cc.AnimationChannel = AnimationChannel; - -@ccclass('cc.AnimationFrame') -export class AnimationFrame { - @property - _name = ""; - - /** - * @type {AnimationChannel[]} - */ - @property - _channels = []; - - /** - * @type {number[]} - */ - @property - _times = []; - - get channels() { - return this._channels; - } - - get times() { - return this._times; - } -} -cc.AnimationFrame = AnimationFrame; - -@ccclass('cc.AnimationClip') -export default class AnimationClip extends Asset { - /** - * @type {AnimationFrame[]} - */ - @property - _frames = []; - - /** - * @type {number} - */ - @property - _length = 0.0; - - get frames() { - return this._frames; - } - - get length() { - return this._length; - } -} -cc.AnimationClip = AnimationClip; - -export class AnimationTarget { - constructor() { - /** - * @type {Node[]} - */ - this._nodes = []; - - /** - * @type {Map} - */ - this._pathMap = new Map(); - } - - add(path, node) { - if (this._pathMap.has(path)) { - return; - } - const index = this._nodes.length; - this._nodes.push(node); - this._pathMap.set(path, index); - } - - get(path) { - return this._pathMap.get(path); - } - - get nodes() { - return this._nodes; - } - - getDefaultPosition(nodeIndex) { - return this._nodes[nodeIndex].getPosition(); - //return this._defaultPositions[nodeIndex]; - } - - getDefaultScale(nodeIndex) { - return this._nodes[nodeIndex].getScale(); - //return this._defaultScales[nodeIndex]; - } - - getDefaultRotation(nodeIndex) { - return this._nodes[nodeIndex].getRotation(); - //return this._defaultRotations[nodeIndex]; - } - - // _saveDefaultTRS() { - // this._defaultPositions = new Array(this._nodes.length); - // this._defaultScales = new Array(this._nodes.length); - // this._defaultRotations = new Array(this._nodes.length); - // this._nodes.forEach((node, index) => { - // this._defaultPositions[index] = node.getPosition(); - // this._defaultScales[index] = node.getScale(); - // this._defaultRotations[index] = node.getRotation(); - // }); - // } -} - -/** - * The AnimationTarget class represents the progress of blended sampling. - */ -export class AnimationSampler { - /** - * - * @param {AnimationTarget} animationTarget - */ - constructor(animationTarget) { - /** - * @type {AnimationTarget} - */ - this._animationTarget = animationTarget; - - const targetNodes = this._animationTarget.nodes; - /** - * @type {NodeSamplingState[]} - */ - this._nodeSamplingStates = new Array(targetNodes.length); - this._animationTarget.nodes.forEach((targetNode, index) => { - this._nodeSamplingStates[index] = new NodeSamplingState( - targetNode, - this._animationTarget.getDefaultPosition(index), - this._animationTarget.getDefaultScale(index), - this._animationTarget.getDefaultRotation(index)); - }); - } - - /** - * Resets this state to get sampling start. - */ - reset() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.reset()); - } - - /** - * Updates the sampling result. - */ - apply() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.apply()); - } - - /** Sample data of this animation clip in a specific time and blend that data - * with a weight together with previous data(if exist, or blank if not exists) sampled before. - * - * @param {AnimationClip} clip - * @param {Number} t The time. - * @param {Number} weight The weight. - * @param {SkeletonMask} [mask] The skeleton mask. - */ - sample(clip, t, weight, mask) { - t = clamp(t, 0, clip.length); - - const getState = /** @param {AnimationChannel} [channel] */(channel) => { - return this._nodeSamplingStates[this._animationTarget.get(channel.target)]; - }; - - clip.frames.forEach((frame) => { - let idx = 0; - if (frame.times.length != 1) - idx = _binaryIndexOf(frame.times, t); - if (idx == 0) { - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - nodeSamlingState.blendPosition(channel.positionCurve[0], weight); - } - if (channel.rotationCurve.length != 0) { - nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); - } - if (channel.scaleCurve.length != 0) { - nodeSamlingState.blendScale(channel.scaleCurve[0], weight); - } - }); - } - else { - let loIdx = Math.max(idx - 1, 0); - let hiIdx = Math.min(idx, frame.times.length); - let ratio = (t - frame.times[loIdx]) / (frame.times[hiIdx] - frame.times[loIdx]); - - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - let a = channel.positionCurve[loIdx]; - let b = channel.positionCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendPosition(tmpvec3, weight); - } - if (channel.rotationCurve.length != 0) { - let a = channel.rotationCurve[loIdx]; - let b = channel.rotationCurve[hiIdx]; - quat.slerp(tmpquat, a, b, ratio); - nodeSamlingState.blendRotation(tmpquat, weight); - } - if (channel.scaleCurve.length != 0) { - let a = channel.scaleCurve[loIdx]; - let b = channel.scaleCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendScale(tmpvec3, weight); - } - }); - } - }); - } -} - -class NodeSamplingState { - /** - * - * @param {Node} target - * @param {cc.Vec3} defaultPosition - * @param {cc.Vec3} defaultScale - * @param {cc.Quat} defaultRotation - */ - constructor(target, defaultPosition, defaultScale, defaultRotation) { - /** - * @type {Node} - */ - this._target = target; - - /** - * @type {cc.Vec3} - */ - this._defaultPosition = defaultPosition; - - /** - * @type {cc.Vec3} - */ - this._defaultScale = defaultScale; - - /** - * @type {cc.Quat} - */ - this._defaultRotation = defaultRotation; - } - - reset() { - /** - * @type {Number} - */ - this._sumPosWeight = 0.0; - - /** - * @type {Number} - */ - this._sumScaleWeight = 0.0; - - /** - * @type {Number} - */ - this._sumRotWeight = 0.0; - this._target.setPosition(0, 0, 0); - this._target.setScale(0, 0, 0); - this._target.setRotation(0, 0, 0, 1); - } - - blendPosition(pos, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lpos, pos, weight); - this._target.setPosition(tmpvec3); - this._sumPosWeight += weight; - } - - blendScale(scale, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lscale, scale, weight); - this._target.setScale(tmpvec3); - this._sumScaleWeight += weight; - } - - /** - * Inspired by: - * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions - */ - blendRotation(rot, weight) { - let t = weight / (this._sumRotWeight + weight); - quat.slerp(tmpquat, this._target._lrot, rot, t); - this._target.setRotation(tmpquat); - this._sumRotWeight += weight; - } - - apply() { - if (this._sumPosWeight < 1.0) - this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); - if (this._sumScaleWeight < 1.0) - this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); - if (this._sumRotWeight < 1.0) - this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); - } -} \ No newline at end of file diff --git a/cocos/3d/assets/animation-clip.ts b/cocos/3d/assets/animation-clip.ts new file mode 100644 index 0000000000..321ff63aaf --- /dev/null +++ b/cocos/3d/assets/animation-clip.ts @@ -0,0 +1,319 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ + +// @ts-check +import { _decorator } from '../../core/data/index'; +const { ccclass, property } = _decorator; +import { Asset } from '../../assets/asset'; +import { Quat, Vec3 } from '../../core/value-types'; +import quat from '../../core/vmath/quat'; +import { clamp } from '../../core/vmath/utils'; +import vec3 from '../../core/vmath/vec3'; +import { Node } from '../../scene-graph/node'; + +const tmpvec3 = new Vec3(); +const tmpquat = new Quat(); + +function _binaryIndexOf (array: number[], key: number) { + let lo = 0; + let hi = array.length - 1; + while (lo <= hi) { + const mid = ((lo + hi) >> 1); + const val = array[mid]; + if (val < key) { + lo = mid + 1; + } else if (val > key) { + hi = mid - 1; + } else { + return mid; + } + } + return lo; +} + +export interface IAnimationChannel { + /** + * Target node's path in scene graph. + */ + target: string; + + /** + * Target node's position animation curve. + */ + positionCurve: Vec3[]; + + /** + * Target node's scale animation curve. + */ + scaleCurve: Vec3[]; + + /** + * Target node's rotation animation curve. + */ + rotationCurve: Quat[]; +} + +@ccclass('cc.AnimationClip') +export default class AnimationClip extends Asset { + @property + private _channels: IAnimationChannel[] = []; + + @property + private _times: number[] = []; + + @property + private _length: number = 0.0; + + get times () { + return this._times; + } + + get channels () { + return this._channels; + } + + get length () { + return this._length; + } +} +cc.AnimationClip = AnimationClip; + +export class AnimationTarget { + private _nodes: Node[] = []; + private _pathMap: Map = new Map(); + + public add (path: string, node: Node) { + if (this._pathMap.has(path)) { + return; + } + const index = this._nodes.length; + this._nodes.push(node); + this._pathMap.set(path, index); + } + + public get (path: string) { + return this._pathMap.get(path); + } + + get nodes () { + return this._nodes; + } + + public getDefaultPosition (nodeIndex: number) { + return this._nodes[nodeIndex].getPosition(); + // return this._defaultPositions[nodeIndex]; + } + + public getDefaultScale (nodeIndex: number) { + return this._nodes[nodeIndex].getScale(); + // return this._defaultScales[nodeIndex]; + } + + public getDefaultRotation (nodeIndex: number) { + return this._nodes[nodeIndex].getRotation(); + // return this._defaultRotations[nodeIndex]; + } + + // _saveDefaultTRS() { + // this._defaultPositions = new Array(this._nodes.length); + // this._defaultScales = new Array(this._nodes.length); + // this._defaultRotations = new Array(this._nodes.length); + // this._nodes.forEach((node, index) => { + // this._defaultPositions[index] = node.getPosition(); + // this._defaultScales[index] = node.getScale(); + // this._defaultRotations[index] = node.getRotation(); + // }); + // } +} + +/** + * The AnimationTarget class represents the progress of blended sampling. + */ +export class AnimationSampler { + private _animationTarget: AnimationTarget; + private _nodeSamplingStates: NodeSamplingState[]; + + constructor (animationTarget: AnimationTarget) { + this._animationTarget = animationTarget; + + const targetNodes = this._animationTarget.nodes; + this._nodeSamplingStates = new Array(targetNodes.length); + this._animationTarget.nodes.forEach((targetNode, index) => { + this._nodeSamplingStates[index] = new NodeSamplingState( + targetNode, + this._animationTarget.getDefaultPosition(index), + this._animationTarget.getDefaultScale(index), + this._animationTarget.getDefaultRotation(index)); + }); + } + + /** + * Resets this state to get sampling start. + */ + public reset () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.reset()); + } + + /** + * Updates the sampling result. + */ + public apply () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.apply()); + } + + /** Sample data of this animation clip in a specific time and blend that data + * with a weight together with previous data(if exist, or blank if not exists) sampled before. + * + * @param clip + * @param t The time. + * @param weight The weight. + * @param [mask] The skeleton mask. + */ + public sample (clip: AnimationClip, t: number, weight: number, mask?: any) { + t = clamp(t, 0, clip.length); + + const getState = (channel: IAnimationChannel) => { + const iNode = this._animationTarget.get(channel.target); + if (!iNode) { + return null; + } + return this._nodeSamplingStates[iNode]; + }; + + let idx = 0; + if (clip.times.length !== 1) { + idx = _binaryIndexOf(clip.times, t); + } + if (idx === 0) { + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + nodeSamlingState.blendPosition(channel.positionCurve[0], weight); + } + if (channel.rotationCurve.length !== 0) { + nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); + } + if (channel.scaleCurve.length !== 0) { + nodeSamlingState.blendScale(channel.scaleCurve[0], weight); + } + }); + } else { + const loIdx = Math.max(idx - 1, 0); + const hiIdx = Math.min(idx, clip.times.length); + const ratio = (t - clip.times[loIdx]) / (clip.times[hiIdx] - clip.times[loIdx]); + + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + const a = channel.positionCurve[loIdx]; + const b = channel.positionCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendPosition(tmpvec3, weight); + } + if (channel.rotationCurve.length !== 0) { + const a = channel.rotationCurve[loIdx]; + const b = channel.rotationCurve[hiIdx]; + quat.slerp(tmpquat, a, b, ratio); + nodeSamlingState.blendRotation(tmpquat, weight); + } + if (channel.scaleCurve.length !== 0) { + const a = channel.scaleCurve[loIdx]; + const b = channel.scaleCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendScale(tmpvec3, weight); + } + }); + } + } +} + +class NodeSamplingState { + private _target: Node; + private _defaultPosition: Vec3; + private _defaultScale: Vec3; + private _defaultRotation: Quat; + private _sumPosWeight = 0; + private _sumScaleWeight = 0; + private _sumRotWeight = 0; + + constructor (target: Node, defaultPosition: Vec3, defaultScale: Vec3, defaultRotation: Quat) { + this._target = target; + this._defaultPosition = defaultPosition; + this._defaultScale = defaultScale; + this._defaultRotation = defaultRotation; + } + + public reset () { + this._sumPosWeight = 0.0; + this._sumScaleWeight = 0.0; + this._sumRotWeight = 0.0; + this._target.setPosition(0, 0, 0); + this._target.setScale(0, 0, 0); + this._target.setRotation(0, 0, 0, 1); + } + + public blendPosition (position: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getPosition(), position, weight); + this._target.setPosition(tmpvec3); + this._sumPosWeight += weight; + } + + public blendScale (scale: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getScale(), scale, weight); + this._target.setScale(tmpvec3); + this._sumScaleWeight += weight; + } + + /** + * Inspired by: + * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions + */ + public blendRotation (rotation: Quat, weight: number) { + const t = weight / (this._sumRotWeight + weight); + quat.slerp(tmpquat, this._target.getRotation(), rotation, t); + this._target.setRotation(tmpquat); + this._sumRotWeight += weight; + } + + public apply () { + if (this._sumPosWeight < 1.0) { + this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); + } + if (this._sumScaleWeight < 1.0) { + this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); + } + if (this._sumRotWeight < 1.0) { + this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); + } + } +} diff --git a/cocos/3d/assets/audio-clip.js b/cocos/3d/assets/audio-clip.js index eb7684cd20..b2c73509b1 100644 --- a/cocos/3d/assets/audio-clip.js +++ b/cocos/3d/assets/audio-clip.js @@ -24,7 +24,7 @@ ****************************************************************************/ // @ts-check import { _decorator } from "../../core/data/index"; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import { EventTarget } from "../../core/event/index"; const { ccclass, mixins } = _decorator; @@ -117,4 +117,4 @@ export class AudioClip extends Asset { } } -cc.AudioClip = AudioClip; \ No newline at end of file +cc.AudioClip = AudioClip; diff --git a/cocos/3d/assets/bitmap-font.js b/cocos/3d/assets/bitmap-font.js index 343aa2381c..668669542d 100644 --- a/cocos/3d/assets/bitmap-font.js +++ b/cocos/3d/assets/bitmap-font.js @@ -27,7 +27,7 @@ import { _decorator } from "../../core/data/index"; const { ccclass, property } = _decorator; import Font from "./font"; import vec2 from "../../core/vmath/vec2"; -import Texture2D from "../../assets/texture-2d"; +import { Texture2D } from "../../assets/texture-2d"; @ccclass('cc.BitmapFont') export class BitmapFont extends Font { diff --git a/cocos/3d/assets/effect-asset.js b/cocos/3d/assets/effect-asset.js deleted file mode 100644 index af5ae4aecd..0000000000 --- a/cocos/3d/assets/effect-asset.js +++ /dev/null @@ -1,46 +0,0 @@ -import Asset from "../../assets/CCAsset"; -import { property, ccclass } from "../../core/data/class-decorator"; - -@ccclass('cc.EffectAsset') -class EffectAsset extends Asset { - @property - techniques = []; - - @property - properties = {}; - - @property - shaders = []; - - onLoaded() { - let lib = cc.game._renderer._programLib; - this.shaders.forEach(s => lib.define(s)); - EffectAsset.register(this); - } -} - -let effects = EffectAsset._effects = {}; -EffectAsset.register = function(asset) { - effects[asset.name] = asset; -}; -EffectAsset.remove = function(name) { - if (effects[name]) { delete effects[name]; return; } - for (let n in effects) { - if (effects[n]._uuid === name) { - delete effects[n]; - return; - } - } -}; -EffectAsset.get = function(name) { - if (effects[name]) return effects[name]; - for (let n in effects) - if (effects[n]._uuid === name) - return effects[n]; -}; -EffectAsset.getAll = function() { - return effects; -}; - -export default EffectAsset; -cc.EffectAsset = EffectAsset; diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts new file mode 100644 index 0000000000..3cb9b4e16d --- /dev/null +++ b/cocos/3d/assets/effect-asset.ts @@ -0,0 +1,108 @@ +import { Asset } from '../../assets/asset'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { GFXDynamicState, GFXPrimitiveMode, GFXType } from '../../gfx/define'; +import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; +import { IGFXSamplerInfo } from '../../gfx/sampler'; +import { RenderPassStage } from '../../pipeline/define'; +import { programLib } from '../../renderer/core/program-lib'; + +export interface IPropertyInfo { + type: number; // auto-extracted if not specified + value?: number[] | string; + displayName?: string; + sampler?: IGFXSamplerInfo; +} +export interface IPassInfo { + program: string; + // effect-writer part + priority?: number; + primitive?: GFXPrimitiveMode; + stage?: RenderPassStage; + rasterizerState?: GFXRasterizerState; + depthStencilState?: GFXDepthStencilState; + blendState?: GFXBlendState; + dynamics?: GFXDynamicState[]; + properties?: Record; +} +export interface ITechniqueInfo { + passes: IPassInfo[]; + queue?: number; + priority?: number; + lod?: number; +} + +export interface IBlockMember { + name: string; + type: GFXType; + count: number; + size: number; +} +export interface IBlockInfo { + name: string; + binding: number; + defines: string[]; + members: IBlockMember[]; + size: number; +} +export interface ISamplerInfo { + name: string; + binding: number; + defines: string[]; + type: GFXType; + count: number; +} +export interface IDefineInfo { + name: string; + type: string; + range?: number[]; + defines: string[]; +} +export interface IShaderInfo { + name: string; + vert: string; + frag: string; + defines: IDefineInfo[]; + blocks: IBlockInfo[]; + samplers: ISamplerInfo[]; + dependencies: Record; +} + +const effects: Record = {}; + +@ccclass('cc.EffectAsset') +export class EffectAsset extends Asset { + public static register (asset: EffectAsset) { effects[asset.name] = asset; } + public static remove (name: string) { + if (effects[name]) { delete effects[name]; return; } + for (const n in effects) { + if (effects[n]._uuid === name) { + delete effects[n]; + return; + } + } + } + public static get (name: string) { + if (effects[name]) { return effects[name]; } + for (const n in effects) { + if (effects[n]._uuid === name) { + return effects[n]; + } + } + return null; + } + public static getAll () { return effects; } + protected static _effects: Record = {}; + + @property + public techniques: ITechniqueInfo[] = []; + + @property + public shaders: IShaderInfo[] = []; + + public onLoaded () { + this.shaders.forEach((s) => programLib.define(s)); + EffectAsset.register(this); + } +} + +cc.EffectAsset = EffectAsset; diff --git a/cocos/3d/assets/font.js b/cocos/3d/assets/font.js index 319bacfd94..3d0891759b 100644 --- a/cocos/3d/assets/font.js +++ b/cocos/3d/assets/font.js @@ -25,13 +25,13 @@ // @ts-check import { _decorator } from "../../core/data/index"; const {ccclass} = _decorator; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; @ccclass('cc.Font') export default class Font extends Asset { - /** Font size. - * @type {number} - */ + /** Font size. + * @type {number} + */ _size = 32; /** Font type. @@ -46,7 +46,7 @@ export default class Font extends Asset { _lineHeight = 32; /** - * + * * @type {boolean} */ _useKerning = false; @@ -78,4 +78,4 @@ export default class Font extends Asset { } } -cc.Font = Font; \ No newline at end of file +cc.Font = Font; diff --git a/cocos/3d/assets/index.js b/cocos/3d/assets/index.js index 6393ed3b4f..4cc366051f 100644 --- a/cocos/3d/assets/index.js +++ b/cocos/3d/assets/index.js @@ -4,7 +4,7 @@ http://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, + 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 @@ -14,7 +14,7 @@ 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 + 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 @@ -27,9 +27,9 @@ export { default as AnimationClip } from "./animation-clip"; export { AudioClip } from "./audio-clip"; export { DOMAudioClip } from "./dom-audio-clip"; export { BitmapFont } from "./bitmap-font"; -export { default as EffectAsset } from "./effect-asset"; -export { default as Material } from "./material"; -export { default as Mesh } from "./mesh"; +export { EffectAsset } from "./effect-asset"; +export { Material } from "./material"; +export { Mesh } from "./mesh"; export { default as OpentypeFont } from "./opentype-font"; export { default as Skeleton } from "./skeleton"; export { default as Sprite } from "./sprite"; diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js deleted file mode 100644 index 64e59e5c6a..0000000000 --- a/cocos/3d/assets/material.js +++ /dev/null @@ -1,149 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ -// @ts-check -import { ccclass, property } from "../../core/data/class-decorator"; -import Asset from "../../assets/CCAsset"; -import TextureBase from '../../assets/texture-base'; -import Effect from '../../renderer/core/effect'; -import EffectAsset from './effect-asset'; - -@ccclass('cc.Material') -class Material extends Asset { - /** - * @type {Object} - */ - @property - _defines = {}; - - /** - * @type {Object} - */ - @property - _props = {}; - - /** - * @type {EffectAsset} - */ - @property(EffectAsset) - _effectAsset = null; - - @property - set effectAsset(val) { - if (this.effectName !== val.name) this._setEffect(val); - } - get effectAsset() { - return this._effectAsset; - } - - // helper setter - @property - set effectName(val) { - if (this.effectName !== val) this._setEffect(val); - } - get effectName() { - return this._effectAsset ? this._effectAsset.name : ''; - } - - /** - * @type {Effect} - */ - _effect = null; - - /** - * @type {Effect} - */ - get effect() { - return this._effect; - } - - /** - * - * @param {Material} mat - */ - copy(mat) { - Object.assign(this._props, mat._props); - Object.assign(this._defines, mat._defines); - this._setEffect(mat.effectAsset); - this._uuid = mat._uuid; - } - - /** - * - * @param {string} name - * @param {*} val - */ - setProperty(name, val) { - this._props[name] = val; - if (this._effect) { - if (val instanceof TextureBase) this._effect.setProperty(name, val._texture); - else this._effect.setProperty(name, val); - } - } - - /** - * - * @param {string} name - * @param {*} val - */ - define(name, val) { - this._defines[name] = val; - if (this._effect) this._effect.define(name, val); - } - - onLoaded() { - this._setEffect(this.effectAsset); - } - - _setEffect(val) { - let effectAsset = val; - if (typeof val === 'string' && !(effectAsset = cc.EffectAsset.get(val))) { - console.warn(`no effect named '${val}' found`); - return; - } - this._effectAsset = effectAsset; - if (!effectAsset) return; - this._effect = Effect.parseEffect(effectAsset); - for (let def in this._defines) - this._effect.define(def, this._defines[def]); - for (let prop in this._props) - this.setProperty(prop, this._props[prop]); - } - - static getInstantiatedMaterial(mat, rndCom) { - if (mat._owner === rndCom) { - return mat; - } - else { - let instance = new Material(); - instance.copy(mat); - instance._native = mat._native + ' (Instance)'; - instance._owner = rndCom; - return instance; - } - } -} - -export default Material; -cc.Material = Material; diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts new file mode 100644 index 0000000000..e84b52fcee --- /dev/null +++ b/cocos/3d/assets/material.ts @@ -0,0 +1,247 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { Asset } from '../../assets/asset'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; +import { GFXBindingType } from '../../gfx/define'; +import { GFXTextureView } from '../../gfx/texture-view'; +import { Effect, IDefineMap } from '../../renderer/core/effect'; +import { Pass, PassOverrides } from '../../renderer/core/pass'; +import { RenderableComponent } from '../framework/renderable-component'; +import { EffectAsset } from './effect-asset'; + +export interface IMaterialInfo { + technique?: number; + defines?: IDefineMap | IDefineMap[]; + effectName?: string; +} + +@ccclass('cc.Material') +export class Material extends Asset { + public static getInstantiatedMaterial (mat: Material, rndCom: RenderableComponent, inEditor: boolean) { + if (mat._owner === rndCom) { + return mat; + } else { + const instance = new Material(); + instance.copy(mat); + instance._native = mat._native + ' (Instance)'; + instance._owner = rndCom; + if (inEditor) { + instance._uuid = mat._uuid; + } + return instance; + } + } + + @property(EffectAsset) + protected _effectAsset: EffectAsset | null = null; + @property + protected _techIdx = 0; + @property + protected _defines: IDefineMap[] = []; + @property + protected _props: Array> = []; + + protected _passes: Pass[] = []; + protected _owner: RenderableComponent | null = null; + protected _hash = 0; + + constructor (info?: IMaterialInfo) { + super(); + if (info) { + if (info.technique) { this._techIdx = info.technique; } + if (info.defines) { this.setDefines(info.defines); } + if (info.effectName) { this.effectName = info.effectName; } + } + } + + @property + set effectAsset (val: EffectAsset | null) { + if (!val || this.effectName !== val.name) { this.update(val, false); } + } + get effectAsset () { + return this._effectAsset; + } + // helper setter + @property + set effectName (val) { + if (this.effectName !== val) { this.update(val, false); } + } + get effectName () { + return this._effectAsset ? this._effectAsset.name : ''; + } + + @property + set technique (val: number) { + this._techIdx = val; + if (val !== this._techIdx) { + this._techIdx = val; + this.update(); + } + } + get technique () { + return this._techIdx; + } + + get passes () { + return this._passes; + } + + get hash () { + return this._hash; + } + + public setDefines (defines: IDefineMap | IDefineMap[]) { + this._defines = Array.isArray(defines) ? defines : [defines]; + this.update(); + } + + /** + * Convenient setter provided for quick material setup. + * pass.setUniform should be used instead + * if you need to do per-frame property update. + */ + public setProperty (name: string, val: any, passIdx?: number) { + let success = false; + if (passIdx === undefined) { // set property for all applicable passes + const passes = this._passes; + const len = passes.length; + for (let i = 0; i < len; i++) { + const pass = passes[i]; + if (this._uploadProperty(pass, name, val)) { + this._props[i][name] = val; + success = true; + } + } + } else { + if (passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } + const pass = this._passes[passIdx]; + if (this._uploadProperty(pass, name, val)) { + this._props[passIdx][name] = val; + success = true; + } + } + if (!success) { console.warn(`illegal property name: ${name}.`); return; } + } + + public copy (mat: Material) { + this._techIdx = mat._techIdx; + this._props.length = mat._props.length; + this._props.fill({}); + for (let i = 0; i < mat._props.length; i++) { + Object.assign(this._props[i], mat._props[i]); + } + Object.assign(this._defines, mat._defines); + this.update(mat.effectAsset); + this._uuid = mat._uuid; + } + + public onLoaded () { + this.update(); + } + + public overridePipelineStates (overrides: PassOverrides, passIdx?: number) { + if (!this._passes || !this._effectAsset) { return; } + const passInfos = Effect.getPassInfos(this._effectAsset, this._techIdx); + if (passIdx === undefined) { + for (let i = 0; i < this._passes.length; i++) { + this._passes[i].overridePipelineStates(passInfos[i], overrides); + } + } else { + this._passes[passIdx].overridePipelineStates(passInfos[passIdx], overrides); + } + this.onPassChange(); + } + + public update (asset: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) { + // get effect asset + if (typeof asset === 'string') { + this._effectAsset = EffectAsset.get(asset); + if (!this._effectAsset) { + console.warn(`no effect named '${asset}' found`); + return; + } + } else { + this._effectAsset = asset; + } + if (!this._effectAsset) { return; } + // create passes + this._passes = Effect.parseEffect(this._effectAsset, { + techIdx: this._techIdx, + defines: this._defines, + }); + // handle property values + this._props.length = this._passes.length; + if (keepProps) { + this._passes.forEach((pass, i) => { + let props = this._props[i]; + if (!props) { props = this._props[i] = {}; } + for (const p of Object.keys(props)) { + const val = props[p]; + if (!val) { continue; } + this._uploadProperty(pass, p, props[p]); + } + }); + } else { + this._props.fill({}); + } + this.onPassChange(); + } + + protected _uploadProperty (pass: Pass, name: string, val: any) { + const handle = pass.getHandle(name); + if (handle === undefined) { return false; } + const bindingType = Pass.getBindingTypeFromHandle(handle); + if (bindingType === GFXBindingType.UNIFORM_BUFFER) { + if (Array.isArray(val)) { + pass.setUniformArray(handle, val); + } else { + pass.setUniform(handle, val); + } + } else if (bindingType === GFXBindingType.SAMPLER) { + const textureView = val instanceof GFXTextureView ? val : val.getGFXTextureView(); + if (!textureView) { console.warn('texture asset incomplete!'); return false; } + const binding = Pass.getBindingFromHandle(handle); + pass.bindTextureView(binding, textureView); + } + return true; + } + + protected onPassChange () { + let str = ''; + for (const pass of this._passes) { + str += pass.serializePipelineStates(); + } + this._hash = murmurhash2_32_gc(str, 666); + if (this._owner) { + const comp = this._owner; + const index = comp.sharedMaterials.findIndex((m) => m === this); + // @ts-ignore + if (index >= 0) { comp._onRebuildPSO(index, this); } + } + } +} + +cc.Material = Material; diff --git a/cocos/3d/assets/mesh.js b/cocos/3d/assets/mesh.js deleted file mode 100644 index 35a2de09dd..0000000000 --- a/cocos/3d/assets/mesh.js +++ /dev/null @@ -1,272 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -// @ts-check -import { _decorator } from "../../core/data/index"; -const { ccclass, property } = _decorator; -import Asset from "../../assets/CCAsset"; -import gfx from "../../renderer/gfx"; -import { enums as gfxEnums } from "../../renderer/gfx/enums"; -import InputAssembler from "../../renderer/core/input-assembler"; -import BufferRange from "./utils/buffer-range"; -import { Vec3 } from "../../core/value-types"; - -/** - * A vertex bundle describes a serials of vertex attributes. - * These vertex attributes occupy a range of the buffer and - * are interleaved, no padding bytes, in the range. - */ -@ccclass("cc.VertexBundle") -export class VertexBundle { - /** - * The data range of this bundle. - * This range of data is essentially mapped to a GPU vertex buffer. - * @type {BufferRange} - */ - @property(BufferRange) - _data = null; - - /** - * This bundle's vertices count. - * @type {number} - */ - @property(Number) - _verticesCount = 0; - - /** - * The attributes's formats. - * @type {{name: string, type: number, num: number, normalize: boolean}[]} - */ - @property - _formats = []; -} -cc.VertexBundle = VertexBundle; - -/** - * A primitive is a geometry constituted with a list of - * same topology primitive graphic(such as points, lines or triangles). - */ -@ccclass("cc.Primitive") -export class Primitive { - - /** - * The vertex bundles that this primitive use. - * @type {number[]} - */ - @property([Number]) - _vertexBundelIndices = []; - - /** - * The indices data range of this primitive. - * @type {BufferRange} - */ - @property(BufferRange) - _indices = null; - - /** - * The type of this primitive's indices. - * @type {number} - */ - @property(Number) - _indexUnit = gfxEnums.INDEX_FMT_UINT16; - - /** - * This primitive's topology. - * @type {number} - */ - @property(Number) - _topology = gfxEnums.PT_TRIANGLES; -} -cc.Primitive = Primitive; - -@ccclass('cc.Mesh') -export default class Mesh extends Asset { - /** - * The vertex bundles that this mesh owns. - * @type {VertexBundle[]} - */ - @property([VertexBundle]) - _vertexBundles = []; - - /** - * @type {Primitive[]} - */ - @property([Primitive]) - _primitives = []; - - /** - * The min position of this mesh's vertices. - */ - @property(Vec3) - _minPosition = null; - - /** - * The max position of this mesh's vertices. - */ - @property(Vec3) - _maxPosition = null; - - constructor() { - super(); - - /** - * @type {InputAssembler[]} - */ - this._subMeshes = null; - - /** - * @type {Uint8Array} - */ - this._data = null; - } - - get _nativeAsset() { - return this._data; - } - - set _nativeAsset(value) { - this._data = value; - } - - /** - * - */ - _lazyInitRenderResources() { - if (this._subMeshes != null) { - return; - } - - this._subMeshes = []; - - if (this._data === null) { - return; - } - const buffer = this._getBuffer(); - const vertexBuffers = this._vertexBundles.map((vertexBundle) => { - return new gfx.VertexBuffer( - cc.game._renderContext, - new gfx.VertexFormat(vertexBundle._formats), - gfx.USAGE_STATIC, - new Uint8Array(buffer, vertexBundle._data._offset, vertexBundle._data._length), - vertexBundle._verticesCount); - }); - this._subMeshes = this._primitives.map((primitive) => { - if (primitive._vertexBundelIndices.length === 0) { - return null; - } - - // Currently, an IA only has one vertex buffer. - const vertexBuffer = vertexBuffers[primitive._vertexBundelIndices[0]]; - - const indexBuffer = new gfx.IndexBuffer( - cc.game._renderContext, - primitive._indexUnit, - gfx.USAGE_STATIC, - new DataView(buffer, primitive._indices._offset, primitive._indices._length), - primitive._indices._length / this._getIndexUnitSize(primitive._indexUnit) - ); - - return new InputAssembler(vertexBuffer, indexBuffer); - }); - } - - /** - * !#en - * Destory this mesh and immediately release its video memory. - */ - destroy() { - if (this._subMeshes !== null) { - // Destroy vertex buffer - this._subMeshes[0]._vertexBuffer.destroy(); - // Destroy index buffers - for (let i = 0; i < this._subMeshes.length; ++i) { - this._subMeshes[i]._indexBuffer.destroy(); - } - this._subMeshes = null; - } - - return super.destroy(); - } - - /** - * !#en - * Submeshes count of this mesh. - * @type {number} - */ - get subMeshCount() { - this._lazyInitRenderResources(); - return this._subMeshes.length; - } - - /** - * !#en - * Gets the specified submesh. - * @param {number} index Index of the specified submesh. - */ - getSubMesh(index) { - this._lazyInitRenderResources(); - return this._subMeshes[index]; - } - - get minPosition() { - return this._minPosition; - } - - get maxPosition() { - return this._maxPosition; - } - - // TODO - // updateData () { - // // store the data - // if (this._persist) { - // if (this._data) { - // this._data.set(data, offset); - // } else { - // this._data = data; - // } - // } - // } - - /** - * @return {ArrayBuffer} - */ - _getBuffer() { - return this._data.buffer; - } - - _getIndexUnitSize(indexUnit) { - switch (indexUnit) { - case gfxEnums.INDEX_FMT_UINT8: - return 1; - case gfxEnums.INDEX_FMT_UINT16: - return 2; - case gfxEnums.INDEX_FMT_UINT32: - return 3; - } - return 1; - } -} -cc.Mesh = Mesh; diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts new file mode 100644 index 0000000000..a6135dc2d5 --- /dev/null +++ b/cocos/3d/assets/mesh.ts @@ -0,0 +1,530 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { Asset } from '../../assets/asset'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Vec3 } from '../../core/value-types'; +import { ccenum } from '../../core/value-types/enum'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXInputAssembler, IGFXInputAssemblerInfo, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { IBufferRange } from './utils/buffer-range'; + +export enum AttributeBaseType { + /** + * 8 bits signed integer. + */ + INT8, + + /** + * 8 bits unsigned integer. + */ + UINT8, + + /** + * 16 bits signed integer. + */ + INT16, + + /** + * 16 bits unsigned integer. + */ + UINT16, + + /** + * 32 bits signed integer. + */ + INT32, + + /** + * 32 bits unsigned integer. + */ + UINT32, + + /** + * 32 bits floating number. + */ + FLOAT32, +} + +ccenum(AttributeBaseType); + +export enum AttributeType { + /** + * Scalar. + */ + SCALAR, + + /** + * 2 components vector. + */ + VEC2, + + /** + * 3 components vector. + */ + VEC3, + + /** + * 4 components vector. + */ + VEC4, +} + +ccenum(AttributeType); + +export enum IndexUnit { + /** + * 8 bits unsigned integer. + */ + UINT8, + + /** + * 8 bits unsigned integer. + */ + UINT16, + + /** + * 8 bits unsigned integer. + */ + UINT32, +} + +ccenum(IndexUnit); + +function getIndexUnitStride (indexUnit: IndexUnit) { + switch (indexUnit) { + case IndexUnit.UINT8: return 1; + case IndexUnit.UINT16: return 2; + case IndexUnit.UINT32: return 3; + } + return 1; +} + +function getIndexUnitCtor (indexUnit: IndexUnit) { + switch (indexUnit) { + case IndexUnit.UINT8: return Uint8Array; + case IndexUnit.UINT16: return Uint16Array; + case IndexUnit.UINT32: return Uint32Array; + } + return Uint8Array; +} + +export interface IVertexAttribute { + /** + * Attribute Name. + */ + name: string; + + /** + * Attribute base type. + */ + baseType: AttributeBaseType; + + /** + * Attribute type. + */ + type: AttributeType; + + /** + * Whether normalize. + */ + normalize: boolean; +} + +function toGFXAttributeType (vertexAttribute: IVertexAttribute) { + let formatName = ''; + switch (vertexAttribute.type) { + case AttributeType.SCALAR: + formatName = 'R'; + break; + case AttributeType.VEC2: + formatName = 'RG'; + break; + case AttributeType.VEC3: + formatName = 'RGB'; + break; + case AttributeType.VEC4: + formatName = 'RGBA'; + break; + } + switch (vertexAttribute.baseType) { + case AttributeBaseType.INT8: + formatName += '8I'; + break; + case AttributeBaseType.UINT8: + formatName += '8UI'; + break; + case AttributeBaseType.INT16: + formatName += '16I'; + break; + case AttributeBaseType.UINT16: + formatName += '16UI'; + break; + case AttributeBaseType.INT32: + formatName += '32I'; + break; + case AttributeBaseType.UINT32: + formatName += '32UI'; + break; + case AttributeBaseType.FLOAT32: + formatName += '32F'; + break; + } + + const resultFormat = GFXFormat[formatName]; + if (resultFormat !== undefined) { + return resultFormat; + } + + return GFXFormat.R8UI; +} + +export interface IVertexBundle { + /** + * The data range of this bundle. + * This range of data is essentially mapped to a GPU vertex buffer. + */ + data: IBufferRange; + + /** + * This bundle's vertices count. + */ + verticesCount: number; + + /** + * Attributes. + */ + attributes: IVertexAttribute[]; +} + +/** + * A primitive is a geometry constituted with a list of + * same topology primitive graphic(such as points, lines or triangles). + */ +export interface IPrimitive { + /** + * The vertex bundles that this primitive use. + */ + vertexBundelIndices: number[]; + + /** + * This primitive's topology. + */ + primitiveMode: GFXPrimitiveMode; + + indices?: { + /** + * The indices data range of this primitive. + */ + range: IBufferRange; + + /** + * The type of this primitive's indices. + */ + indexUnit: IndexUnit; + }; + + /** + * Geometric info for raycast purposes. + */ + geometricInfo?: { + doubleSided?: boolean; + range: IBufferRange; + }; +} + +/** + * Describes a mesh. + */ +export interface IMeshStruct { + /** + * The vertex bundles that this mesh owns. + */ + vertexBundles: IVertexBundle[]; + + /** + * The primitives that this mesh owns. + */ + primitives: IPrimitive[]; + + /** + * The min position of this mesh's vertices. + */ + minPosition?: Vec3; + + /** + * The max position of this mesh's vertices. + */ + maxPosition?: Vec3; +} + +// for raycast purpose +export type IBArray = Uint8Array | Uint16Array | Uint32Array; +export interface IGeometricInfo { + positions: Float32Array; + indices: IBArray; + doubleSided?: boolean; +} + +export interface IRenderingSubmesh { + vertexBuffers: GFXBuffer[]; + indexBuffer: GFXBuffer; + indirectBuffer?: GFXBuffer; + attributes: IGFXInputAttribute[]; + primitiveMode: GFXPrimitiveMode; + geometricInfo?: IGeometricInfo; +} + +export class RenderingMesh { + public constructor ( + private _subMeshes: Array, + private _vertexBuffers: GFXBuffer[], + private _indexBuffers: GFXBuffer[]) { + + } + + public get subMeshCount () { + return this._subMeshes.length; + } + + public getSubmesh (index: number) { + return this._subMeshes[index]; + } + + public destroy () { + this._vertexBuffers.forEach((vertexBuffer) => { + vertexBuffer.destroy(); + }); + this._vertexBuffers.length = 0; + + this._indexBuffers.forEach((indexBuffer) => { + indexBuffer.destroy(); + }); + this._indexBuffers.length = 0; + this._subMeshes.length = 0; + } +} + +@ccclass('cc.Mesh') +export class Mesh extends Asset { + + get _nativeAsset () { + return this._data; + } + + set _nativeAsset (value) { + this._data = value; + } + + /** + * Submeshes count of this mesh. + * @deprecated Use this.renderingMesh.subMeshCount instead. + */ + get subMeshCount () { + const renderingMesh = this.renderingMesh; + return renderingMesh ? renderingMesh.subMeshCount : 0; + } + + /** + * Min position of this mesh. + * @deprecated Use this.struct.minPosition instead. + */ + get minPosition () { + return this.struct.minPosition; + } + + /** + * Max position of this mesh. + * @deprecated Use this.struct.maxPosition instead. + */ + get maxPosition () { + return this.struct.maxPosition; + } + + get struct () { + return this._struct; + } + + get data () { + return this._data; + } + + @property + private _struct: IMeshStruct = { + vertexBundles: [], + primitives: [], + }; + + private _data: Uint8Array | null = null; + + private _initialized = false; + + private _renderingMesh: RenderingMesh | null = null; + + constructor () { + super(); + } + + /** + * Destory this mesh and immediately release its GPU resources. + */ + public destroy () { + this._tryDestroyRenderingMesh(); + return super.destroy(); + } + + /** + * Assigns new mesh struct to this. + * @param struct The new mesh's struct. + * @param data The new mesh's data. + */ + public assign (struct: IMeshStruct, data: Uint8Array) { + this._struct = struct; + this._data = data; + this._tryDestroyRenderingMesh(); + } + + /** + * Gets the rendering mesh. + */ + public get renderingMesh () { + this._deferredInit(); + return this._renderingMesh; + } + + /** + * !#en + * Gets the specified submesh. + * @param index Index of the specified submesh. + * @deprecated Use this.renderingMesh.getSubmesh(index).inputAssembler instead. + */ + public getSubMesh (index: number) { + const renderingSubmesh = this.renderingMesh ? this.renderingMesh.getSubmesh(index) : null; + return renderingSubmesh; + } + + private _deferredInit () { + if (this._initialized) { + return; + } + + this._initialized = true; + + if (this._data === null) { + return; + } + + const buffer = this._data.buffer; + + const gfxDevice = cc.director.root.device as GFXDevice; + + const vertexBuffers = this._createVertexBuffers(gfxDevice, buffer); + + const indexBuffers: GFXBuffer[] = []; + + const renderingSubmeshes = this._struct.primitives.map((primitive) => { + if (primitive.vertexBundelIndices.length === 0) { + return null; + } + + let indexBuffer: GFXBuffer | null = null; + let ib: any = null; + if (primitive.indices) { + const indices = primitive.indices; + + indexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: indices.range.length, + stride: getIndexUnitStride(indices.indexUnit), + }); + indexBuffers.push(indexBuffer); + + ib = new (getIndexUnitCtor(indices.indexUnit))(buffer, indices.range.offset, + indices.range.length / getIndexUnitStride(indices.indexUnit)); + indexBuffer.update(ib); + } + + const gfxAttributes: IGFXInputAttribute[] = []; + primitive.vertexBundelIndices.forEach((iVertexBundle) => { + const vertexBundle = this._struct.vertexBundles[iVertexBundle]; + vertexBundle.attributes.forEach((attribute) => { + const gfxAttribute: IGFXInputAttribute = { + name: attribute.name, + format: toGFXAttributeType(attribute), + stream: iVertexBundle, + }; + if ('normalize' in attribute) { + gfxAttribute.isNormalized = attribute.normalize; + } + gfxAttributes.push(gfxAttribute); + }); + }); + + const vbReference = primitive.vertexBundelIndices.map( + (i) => vertexBuffers[i]); + + const geomInfo: any = primitive.geometricInfo; + if (geomInfo) { + geomInfo.indices = ib; + geomInfo.positions = new Float32Array(buffer, geomInfo.range.offset, geomInfo.range.length / 4); + } + + return { + primitiveMode: primitive.primitiveMode, + vertexBuffers: vbReference, + indexBuffer, + attributes: gfxAttributes, + geometricInfo: geomInfo, + } as IRenderingSubmesh; + }); + + this._renderingMesh = new RenderingMesh(renderingSubmeshes, vertexBuffers, indexBuffers); + } + + private _createVertexBuffers (gfxDevice: GFXDevice, data: ArrayBuffer): GFXBuffer[] { + return this._struct.vertexBundles.map((vertexBundle) => { + const vertexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: vertexBundle.data.length, + stride: vertexBundle.data.length / vertexBundle.verticesCount, + }); + vertexBuffer.update(new Uint8Array(data, vertexBundle.data.offset, vertexBundle.data.length)); + return vertexBuffer; + }); + } + + private _tryDestroyRenderingMesh () { + if (this._renderingMesh) { + this._renderingMesh.destroy(); + this._renderingMesh = null; + this._initialized = false; + } + } +} +cc.Mesh = Mesh; diff --git a/cocos/3d/assets/opentype-font.js b/cocos/3d/assets/opentype-font.js index bcf867b98b..12ac748ac5 100644 --- a/cocos/3d/assets/opentype-font.js +++ b/cocos/3d/assets/opentype-font.js @@ -23,13 +23,12 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import { _decorator } from "../../core/data/index"; -const {ccclass} = _decorator; +import { ccclass } from "../../core/data/class-decorator"; import Font from "./font"; -import vec2 from "../../core/vmath/vec2"; +import { vec2 } from "../../core/vmath"; import ShelfPack from "./utils/shelf-pack"; -import ImageAsset from "../../assets/image-asset"; -import Texture2D from "../../assets/texture-2d"; +import { ImageAsset } from "../../assets/image-asset"; +import { Texture2D } from "../../assets/texture-2d"; @ccclass('cc.OpentypeFont') export default class OpentypeFont extends Font { diff --git a/cocos/3d/assets/physics/material.ts b/cocos/3d/assets/physics/material.ts index accaa91ba0..6e7d6293f2 100644 --- a/cocos/3d/assets/physics/material.ts +++ b/cocos/3d/assets/physics/material.ts @@ -2,7 +2,7 @@ // @ts-check import CANNON from 'cannon'; -import Asset from '../../../assets/CCAsset'; +import { Asset } from '../../../assets/asset'; import { ccclass, property } from '../../../core/data/class-decorator'; @ccclass('cc.PhysicalMaterial') diff --git a/cocos/3d/assets/skeleton.js b/cocos/3d/assets/skeleton.ts similarity index 67% rename from cocos/3d/assets/skeleton.js rename to cocos/3d/assets/skeleton.ts index 3efca75a9d..e3d9d5806d 100644 --- a/cocos/3d/assets/skeleton.js +++ b/cocos/3d/assets/skeleton.ts @@ -23,11 +23,10 @@ THE SOFTWARE. ****************************************************************************/ -// @ts-check -import { _decorator } from "../../core/data"; +import { _decorator } from '../../core/data'; const { ccclass, property } = _decorator; -import Asset from "../../assets/CCAsset"; -import { Mat4 } from "../../core/value-types"; +import { Asset } from '../../assets/asset'; +import { Mat4 } from '../../core/value-types'; /** * CLASS Skeleton @@ -40,42 +39,46 @@ import { Mat4 } from "../../core/value-types"; */ @ccclass('cc.Skeleton') export default class Skeleton extends Asset { - /** - * The path of joints. - * @type {string[]} - */ - @property([String]) - _joints = []; + /** + * The path of joints. + */ + @property([String]) + private _joints: string[] = []; - /** - * The inverse bind matrices of joints. - * @type {Mat4[]} - */ - @property([Mat4]) - _inverseBindMatrices = []; + /** + * The inverse bind matrices of joints. + */ + @property([Mat4]) + private _inverseBindMatrices: Mat4[] = []; - /** - * Gets the bind pose matrices of joints. - * @type {Mat4[]} - */ - get bindposes() { - return this._inverseBindMatrices; - } + /** + * Gets the bind pose matrices of joints. + */ + get bindposes () { + return this._inverseBindMatrices; + } - /** - * Sets the bind pose matrices of joints. - * @type {Mat4[]} - */ - set bindposes(value) { - this._inverseBindMatrices = value; - } + /** + * Sets the bind pose matrices of joints. + */ + set bindposes (value) { + this._inverseBindMatrices = value; + } - /** - * Gets the paths of joints. - * @type {string[]} - */ - get joints() { - return this._joints; - } + /** + * Gets the paths of joints. + */ + get joints () { + return this._joints; + } + + /** + * Sets the paths of joints. + */ + set joints (value) { + this._joints = value; + } } -cc.Skeleton = Skeleton; \ No newline at end of file + +// tslint:disable-next-line +cc['Skeleton'] = Skeleton; diff --git a/cocos/3d/assets/sprite.js b/cocos/3d/assets/sprite.js index 93c544ea7b..48144fa563 100644 --- a/cocos/3d/assets/sprite.js +++ b/cocos/3d/assets/sprite.js @@ -25,7 +25,7 @@ // @ts-check import { _decorator } from "../../core/data/index"; const { ccclass } = _decorator; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import { vec3, mat4 } from '../../core/vmath/index'; let _t_tmp = vec3.create(0, 0, 0); @@ -200,4 +200,4 @@ export default class Sprite extends Asset { } } -cc.Sprite = Sprite; \ No newline at end of file +cc.Sprite = Sprite; diff --git a/cocos/3d/assets/texture-cube.js b/cocos/3d/assets/texture-cube.js deleted file mode 100644 index 8b22687e16..0000000000 --- a/cocos/3d/assets/texture-cube.js +++ /dev/null @@ -1,285 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ -// @ts-check -import GFXTextureCube from '../../renderer/gfx/texture-cube'; -import TextureBase from '../../assets/texture-base'; -import { ccclass, property } from '../../core/data/class-decorator'; -import ImageAsset from '../../assets/image-asset'; - -/** - * @typedef {import("../../assets/texture-2d")} Texture2D - * @typedef {import("../../assets/texture-base").ImageSource} ImageSource - * @typedef {import("../../assets/texture-base").TextureUpdateOpts} TextureUpdateOpts - * @typedef {import("../../assets/texture-base").HTMLImageSource} HTMLImageSource - * @typedef {{front: HTMLImageSource, back: HTMLImageSource, left: HTMLImageSource, right: HTMLImageSource, top: HTMLImageSource, bottom: HTMLImageSource}} MipmapHTMLImageSource - * @typedef {{front: ImageAsset, back: ImageAsset, left: ImageAsset, right: ImageAsset, top: ImageAsset, bottom: ImageAsset}} Mipmap - */ - -/** - * @enum {number} - */ -const FaceIndex = cc.Enum({ - right: 0, - left: 1, - top: 2, - bottom: 3, - front: 4, - back: 5 -}); - -@ccclass('cc.TextureCube') -export default class TextureCube extends TextureBase { - /** - * @type {Mipmap[]} - */ - @property - _mipmaps = []; - - constructor() { - super(); - - /** - * @type {GFXTextureCube} - */ - this._texture = null; - } - - /** - * Gets the mipmap images. - * Note that the result do not contains the auto generated mipmaps. - * @type {Mipmap[]} - */ - get mipmaps() { - return this._mipmaps; - } - - /** - * Sets the mipmaps images. - * @type {Mipmap[]} - */ - set mipmaps(value) { - this._setMipmaps(value); - } - - /** - * Gets the mipmap image at level 0. - * @type {Mipmap} - */ - get image() { - return this._mipmaps.length === 0 ? null : this._mipmaps[0]; - } - - /** - * Sets the mipmap images as a single mipmap image. - * @type {Mipmap} - */ - set image(value) { - this.mipmaps = [value]; - } - - /** - * Gets the underlying texture object. - */ - getImpl () { - return this._texture; - } - - /** - * !#en - * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
- * After destroy, this object is not usable any more. - * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. - * !#zh - * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
- * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @method destroy - * @return {Boolean} inherit from the CCObject - */ - destroy () { - this.releaseTexture(); - // TODO cc.textureUtil ? - // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url - return super.destroy(); - } - - /** - * !#en - * Release texture, please use destroy instead. - * !#zh 释放纹理,请使用 destroy 替代。 - * @method releaseTexture - * @deprecated since v2.0 - */ - releaseTexture () { - this._setMipmaps([]); - this._texture && this._texture.destroy(); - } - - /** - * Sets the _mipmaps to specified value, and updates the width and height accordingly. - * If available, synchronize the mipmap data to underlying texture. - * @param {Mipmap[]} mipmaps - */ - _setMipmaps(mipmaps) { - this._mipmaps = mipmaps; - if (mipmaps.length === 0) { - super.update({ - width: 0, - height: 0 - }); - } else { - super.update({ - width: this._mipmaps[0].front.width, - height: this._mipmaps[0].front.height, - format: this._mipmaps[0].front._format - }); - } - - let counter = 0; - const inc = () => { - ++counter; - if (counter === this._mipmaps.length * 6) { - this._updateMipmaps(this._mipmaps.map(mipmap => TextureCube._toMipmapArray(mipmap))); - } - }; - mipmaps.forEach(mipmap => { - TextureCube._forEachFace(mipmap, face => { - if (face.loaded) { - inc(); - } else { - face.addEventListener("load", () => inc()); - } - }); - }); - } - - /** - * Updates mipmaps of the underlying texture. - * @param {ImageSource[][]} mipmapSources - */ - _updateMipmaps(mipmapSources) { - const opts = this._getOpts(); - opts.images = mipmapSources; - if (!this._texture) { - this._texture = new GFXTextureCube(cc.game._renderContext, opts); - } else { - this._texture.update(opts); - } - } - - /** - * Update texture options, not available in Canvas render mode. - * image, format, premultiplyAlpha can not be updated in native. - * @method update - */ - update (options) { - if (!options) return; - - super.update(options); - - // TODO: options.image - - if (this._texture) { - this._texture.update(options); - } - } - - /** - * @param {Mipmap} mipmap - * @return {ImageSource[]} - */ - static _toMipmapArray(mipmap) { - /** @type {ImageSource[]} */ - const result = new Array(); - result[FaceIndex.front] = mipmap.front.data; - result[FaceIndex.back] = mipmap.back.data; - result[FaceIndex.left] = mipmap.left.data; - result[FaceIndex.right] = mipmap.right.data; - result[FaceIndex.top] = mipmap.top.data; - result[FaceIndex.bottom] = mipmap.bottom.data; - return result; - } - - /** - * @param {Mipmap} mipmap - * @param {(face: ImageAsset) => void} callback - */ - static _forEachFace(mipmap, callback) { - for (let face in mipmap) { - callback(mipmap[face]); - } - } - - /** - * @param {Texture2D[]} textures - */ - static fromTexture2DArray(textures, out) { - let res = [], mips = textures.length / 6; - for (let i = 0; i < mips; i++) { - res.push(textures.splice(0, 6).reduce((acc, img, i) => { - acc[FaceIndex[i]] = img.image; - return acc; - }, {})); - } - if (!out) out = new TextureCube(); - out.mipmaps = res; - return out; - } - - _serialize() { - return { - base: super._serialize(), - mipmaps: this._mipmaps.map(mipmap => {return { - front: mipmap.front._uuid, - back: mipmap.back._uuid, - left: mipmap.left._uuid, - right: mipmap.right._uuid, - top: mipmap.top._uuid, - bottom: mipmap.bottom._uuid, - };}) - }; - } - - _deserialize (data, handle) { - super._deserialize(data.base); - - this._mipmaps = new Array(data.mipmaps.length); - this._mipmaps.fill({}); - for (let i = 0; i < data.mipmaps.length; ++i) { - const mipmap = data.mipmaps[i]; - handle.result.push(this._mipmaps[i], `front`, mipmap.front); - handle.result.push(this._mipmaps[i], `back`, mipmap.back); - handle.result.push(this._mipmaps[i], `left`, mipmap.left); - handle.result.push(this._mipmaps[i], `right`, mipmap.right); - handle.result.push(this._mipmaps[i], `top`, mipmap.top); - handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom); - } - } - - onLoaded() { - this.mipmaps = this._mipmaps; - } -} - -cc.TextureCube = TextureCube; diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts new file mode 100644 index 0000000000..22073f3130 --- /dev/null +++ b/cocos/3d/assets/texture-cube.ts @@ -0,0 +1,225 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ +// @ts-check +import { Texture2D } from '../../assets'; +import { ImageAsset } from '../../assets/image-asset'; +import { TextureBase } from '../../assets/texture-base'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { GFXTextureFlagBit, GFXTextureViewType } from '../../gfx/define'; + +interface ITextureCubeMipmap { + front: ImageAsset; + back: ImageAsset; + left: ImageAsset; + right: ImageAsset; + top: ImageAsset; + bottom: ImageAsset; +} + +@ccclass('cc.TextureCube') +export class TextureCube extends TextureBase { + /** + * Gets the mipmap images. + * Note that the result do not contains the auto generated mipmaps. + */ + get mipmaps () { + return this._mipmaps; + } + + /** + * Sets the mipmaps images. + */ + set mipmaps (value) { + this._mipmaps = value; + this.create( + value.length === 0 ? 0 : value[0].front.width, + value.length === 0 ? 0 : value[0].front.height, + undefined, + this._mipmaps.length); + this._mipmaps.forEach((mipmap, level) => { + _forEachFace(mipmap, (face, faceIndex) => { + this._assignImage(face, level, faceIndex); + }); + }); + } + + /** + * Gets the mipmap image at level 0. + */ + get image () { + return this._mipmaps.length === 0 ? null : this._mipmaps[0]; + } + + /** + * Sets the mipmap images as a single mipmap image. + */ + set image (value) { + this.mipmaps = value ? [value] : []; + } + + /** + * @param textures + * @deprecated Manually assign to mipmaps property instead. + */ + public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) { + const mipmaps: ITextureCubeMipmap[] = []; + const nMipmaps = textures.length / 6; + for (let i = 0; i < nMipmaps; i++) { + const x = i * 6; + mipmaps.push({ + front: textures[x + FaceIndex.front].image!, + back: textures[x + FaceIndex.back].image!, + left: textures[x + FaceIndex.left].image!, + right: textures[x + FaceIndex.right].image!, + top: textures[x + FaceIndex.top].image!, + bottom: textures[x + FaceIndex.bottom].image!, + }); + } + if (!out) { out = new TextureCube(); } + out.mipmaps = mipmaps; + return out; + } + + @property + public _mipmaps: ITextureCubeMipmap[] = []; + + constructor () { + super(); + } + + /** + * !#en + * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
+ * After destroy, this object is not usable any more. + * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. + * !#zh + * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
+ * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + */ + public destroy () { + this._mipmaps = []; + return super.destroy(); + } + + /** + * !#en + * Release texture, please use destroy instead. + * !#zh 释放纹理,请使用 destroy 替代。 + * @deprecated Since v2.0. + */ + public releaseTexture () { + this.mipmaps = []; + } + + public _serialize () { + return { + base: super._serialize(), + mipmaps: this._mipmaps.map((mipmap) => {return { + front: mipmap.front._uuid, + back: mipmap.back._uuid, + left: mipmap.left._uuid, + right: mipmap.right._uuid, + top: mipmap.top._uuid, + bottom: mipmap.bottom._uuid, + }; }), + }; + } + + public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) { + const data = serializedData as ITextureCubeSerializeData; + super._deserialize(data.base, handle); + + this._mipmaps = new Array(data.mipmaps.length); + for (let i = 0; i < data.mipmaps.length; ++i) { + // Prevent resource load failed + this._mipmaps[i] = { + front: new ImageAsset(), + back: new ImageAsset(), + left: new ImageAsset(), + right: new ImageAsset(), + top: new ImageAsset(), + bottom: new ImageAsset(), + }; + const mipmap = data.mipmaps[i]; + handle.result.push(this._mipmaps[i], `front`, mipmap.front); + handle.result.push(this._mipmaps[i], `back`, mipmap.back); + handle.result.push(this._mipmaps[i], `left`, mipmap.left); + handle.result.push(this._mipmaps[i], `right`, mipmap.right); + handle.result.push(this._mipmaps[i], `top`, mipmap.top); + handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom); + } + } + + protected _getTextureCreateInfo () { + const result = super._getTextureCreateInfo(); + result.arrayLayer = 6; + result.flags = (result.flags || 0) | GFXTextureFlagBit.CUBEMAP; + return result; + } + + protected _getTextureViewCreateInfo () { + const result = super._getTextureViewCreateInfo(); + result.type = GFXTextureViewType.CUBE; + result.layerCount = 6; + return result; + } +} + +/* tslint:disable:no-string-literal */ +cc['TextureCube'] = TextureCube; + +interface ITextureCubeSerializeData { + base: string; + mipmaps: Array<{ + front: string; + back: string; + left: string; + right: string; + top: string; + bottom: string; + }>; +} + +enum FaceIndex { + right = 0, + left = 1, + top = 2, + bottom = 3, + front = 4, + back = 5, +} + +/** + * @param {Mipmap} mipmap + * @param {(face: ImageAsset) => void} callback + */ +function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void) { + callback(mipmap.front, FaceIndex.front); + callback(mipmap.back, FaceIndex.back); + callback(mipmap.left, FaceIndex.left); + callback(mipmap.right, FaceIndex.right); + callback(mipmap.top, FaceIndex.top); + callback(mipmap.bottom, FaceIndex.bottom); +} diff --git a/cocos/3d/assets/texture-sprite.js b/cocos/3d/assets/texture-sprite.js index 1bc29e5e1b..50fc175f66 100644 --- a/cocos/3d/assets/texture-sprite.js +++ b/cocos/3d/assets/texture-sprite.js @@ -23,9 +23,8 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import { _decorator } from "../../core/data/index"; -const { ccclass, property } = _decorator; -import Texture2D from '../../assets/texture-2d'; +import { ccclass, property } from "../../core/data/class-decorator"; +import { Texture2D } from '../../assets/texture-2d'; import Sprite from "./sprite"; @ccclass('cc.TextureSprite') diff --git a/cocos/2d/renderer/webgl/assemblers/index.js b/cocos/3d/assets/utils/buffer-range.ts similarity index 73% rename from cocos/2d/renderer/webgl/assemblers/index.js rename to cocos/3d/assets/utils/buffer-range.ts index 65a9b28071..25f2f386ed 100644 --- a/cocos/2d/renderer/webgl/assemblers/index.js +++ b/cocos/3d/assets/utils/buffer-range.ts @@ -5,11 +5,11 @@ 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 + 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. + 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. @@ -23,8 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -require('./sprite'); -require('./mask-assembler'); -require('./graphics'); -require('./label'); -require('./motion-streak'); +export interface IBufferRange { + offset: number; + length: number; +} diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 9e58c5f82d..81f033dd9e 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,54 +1,106 @@ +// absolute essential effects export default [ { - "name": "builtin-effect-unlit", - "techniques": [{"queue":0,"lod":100,"passes":[{"stage":1,"cullMode":1029,"depthTest":true,"depthWrite":true,"program":"aa204b4f36b7a4b0c9e10806d01c41a2dcdfba410236f788b8f97fc9"}],"priority":0}], - "properties": {"color":{"type":9,"value":[1,1,1,1]},"mainTiling":{"type":5,"value":[1,1]},"mainOffset":{"type":5,"value":[0,0]},"mainTexture":{"type":13,"value":null}}, + "name": "builtin-effect-particle-add", + "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":1, "blendSrcAlpha":2, "blendDstAlpha":1}]}, "program":"builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs", "properties":{"mainTexture":{"type":29, "value":"grey"}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "frameTile":{"type":14, "value":[1, 1]}, "velocityScale":{"type":13, "value":[0]}, "lengthScale":{"type":13, "value":[0]}, "tintColor":{"type":17, "value":[0.5, 0.5, 0.5, 0.5]}}}]}], "shaders": [ { - "name": "aa204b4f36b7a4b0c9e10806d01c41a2dcdfba410236f788b8f97fc9", - "vert": "\nattribute vec3 a_position;\nuniform mat4 _model;\nuniform mat4 _viewProj;\n#if USE_TEXTURE\n attribute vec2 a_uv0;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if USE_JOINTS_TEXTURE\nuniform sampler2D _u_jointsTexture;\nuniform float _u_jointsTextureSize;\nmat4 getBoneMatrix(const in float i) {\n float size = _u_jointsTextureSize;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(_u_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(_u_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(_u_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(_u_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nuniform mat4 _u_jointMatrices[128];\nmat4 getBoneMatrix(const in float i) {\n return _u_jointMatrices[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w\n ;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_SKINNING\n pos = skinMatrix() * pos;\n #endif\n pos = _viewProj * _model * pos;\n #if USE_TEXTURE\n uv0 = a_uv0 * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n", + "name": "builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs", + "vert": "\n uniform vec2 frameTile;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n uniform float velocityScale;\n uniform float lengthScale;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n \n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos\n , velocity\n , velocityScale\n , lengthScale\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile) * mainTiling + mainOffset;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n", + "frag": "\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n varying vec2 uv;\n varying vec4 color;\n void main () {\n \n gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n }\n", "defines": [ - {"name": "USE_TEXTURE", "type": "boolean"}, - {"name": "USE_SKINNING", "type": "boolean"}, - {"name": "USE_JOINTS_TEXTURE", "type": "boolean"}, - {"name": "USE_COLOR", "type": "boolean"} + {"name":"USE_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_STRETCHED_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_HORIZONTAL_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_VERTICAL_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_WORLD_SPACE", "type":"boolean", "defines":[]} ], - "uniforms": [ - {"name": "mainTiling", "type": 5, "defines": ["USE_TEXTURE"]}, - {"name": "mainOffset", "type": 5, "defines": ["USE_TEXTURE"]}, - {"name": "mainTexture", "type": 13, "defines": ["USE_TEXTURE"]}, - {"name": "color", "type": 7, "defines": ["USE_COLOR"]} + "blocks": [ + {"name": "Constants", "size": 32, "defines": [], "binding": 0, "members": [ + {"name":"frameTile", "type":14, "count":1, "size":8}, + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8}, + {"name":"velocityScale", "type":13, "count":1, "size":4}, + {"name":"lengthScale", "type":13, "count":1, "size":4} + ]}, + {"name": "FragConstants", "size": 16, "defines": [], "binding": 1, "members": [ + {"name":"tintColor", "type":16, "count":1, "size":16} + ]} ], - "attributes": [ - {"name": "a_position", "type": 6, "defines": []}, - {"name": "a_uv0", "type": 5, "defines": ["USE_TEXTURE"]}, - {"name": "a_weights", "type": 7, "defines": ["USE_SKINNING"]}, - {"name": "a_joints", "type": 7, "defines": ["USE_SKINNING"]} + "samplers": [ + {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":2} ], - "extensions": [] + "dependencies": {} } ] }, { "name": "builtin-effect-skybox", - "techniques": [{"queue":0,"lod":200,"passes":[{"stage":1,"cullMode":0,"program":"c4056e849fac08f88d82336386873a650bc636f4349623fecbf96c52"}],"priority":-1000}], - "properties": {"cubeMap":{"type":14,"value":null}}, + "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}], "shaders": [ { - "name": "c4056e849fac08f88d82336386873a650bc636f4349623fecbf96c52", - "vert": "\n attribute vec3 a_position;\n uniform mat4 _view;\n uniform mat4 _proj;\n varying vec3 viewDir;\n void main() {\n mat4 rotView = mat4(mat3(_view));\n vec4 clipPos = _proj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\n viewDir = a_position;\n }\n", + "name": "builtin-effect-skybox|sky-vs|sky-fs", + "vert": "\n attribute vec3 a_position;\n \n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n varying vec3 viewDir;\n void main() {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\n viewDir = a_position;\n }\n", "frag": "\n varying vec3 viewDir;\n uniform samplerCube cubeMap;\n \nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n \nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n void main() {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = linearToGammaSpaceRGB(c / (1.0 + c));\n gl_FragColor = vec4(c, 1.0);\n #else\n gl_FragColor = textureCube(cubeMap, viewDir);\n #endif\n }\n", "defines": [ - {"name": "USE_RGBE_CUBEMAP", "type": "boolean"} + {"name":"USE_RGBE_CUBEMAP", "type":"boolean", "defines":[]} ], - "uniforms": [ - {"name": "cubeMap", "type": 14, "defines": []} + "blocks": [], + "samplers": [ + {"name":"cubeMap", "type":32, "count":1, "defines":[], "binding":0} ], - "attributes": [ - {"name": "a_position", "type": 6, "defines": []} + "dependencies": {} + } + ] + }, + { + "name": "builtin-effect-sprite", + "techniques": [{"passes":[{"depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "program":"builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", "properties":{"u_texSampler":{"type":29, "value":"default", "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0, "addressU":2, "addressV":2}}}}]}], + "shaders": [ + { + "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matViewProj;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 vert () {\n vec4 pos = cc_matViewProj * vec4(a_position, 1);\n v_uv0 = a_texCoord;\n v_color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nuniform sampler2D u_texSampler;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 frag () {\n return texture2D(u_texSampler, v_uv0) * v_color;\n \n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [], + "blocks": [ + {"name": "UI", "size": 64, "defines": [], "binding": 0, "members": [ + {"name":"cc_matViewProj", "type":26, "count":1, "size":64} + ]} ], - "extensions": [] + "samplers": [ + {"name":"u_texSampler", "type":29, "count":1, "defines":[], "binding":1} + ], + "dependencies": {} + } + ] + }, + { + "name": "builtin-effect-unlit", + "techniques": [{"passes":[{"program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}}]}], + "shaders": [ + { + "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", + "vert": "\nattribute vec3 a_position;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint[128];\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"USE_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, + {"name":"USE_COLOR", "type":"boolean", "defines":[]} + ], + "blocks": [ + {"name": "TexCoords", "size": 16, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8} + ]}, + {"name": "Constant", "size": 16, "defines": ["USE_COLOR"], "binding": 1, "members": [ + {"name":"color", "type":16, "count":1, "size":16} + ]} + ], + "samplers": [ + {"name":"mainTexture", "type":29, "count":1, "defines":["USE_TEXTURE"], "binding":2} + ], + "dependencies": {} } ] } diff --git a/cocos/3d/builtin/index.js b/cocos/3d/builtin/index.js deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cocos/3d/builtin/index.ts b/cocos/3d/builtin/index.ts new file mode 100644 index 0000000000..e0ce4607f2 --- /dev/null +++ b/cocos/3d/builtin/index.ts @@ -0,0 +1,3 @@ + +export * from './init'; +export { default as effects } from './effects'; diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js deleted file mode 100644 index 6cc622f6f0..0000000000 --- a/cocos/3d/builtin/init.js +++ /dev/null @@ -1,112 +0,0 @@ -import Texture2D from '../../assets/texture-2d'; -import TextureCube from '../assets/texture-cube'; -import ImageAsset from '../../assets/image-asset'; -import Material from '../assets/material'; -import EffectAsset from '../assets/effect-asset'; -import effects from './effects'; - -let builtinResMgr = { - // this should be called after renderer initialized - initBuiltinRes: function(device) { - builtinResMgr.device = device; - let canvas = document.createElement('canvas'); - let context = canvas.getContext('2d'); - - // ============================ - // builtin textures - // ============================ - - // default texture canvas fill - canvas.width = canvas.height = 128; - context.fillStyle = '#ddd'; - context.fillRect(0, 0, 128, 128); - context.fillStyle = '#555'; - context.fillRect(0, 0, 64, 64); - context.fillStyle = '#555'; - context.fillRect(64, 64, 64, 64); - - const canvasImage = new ImageAsset(canvas); - - // default-texture - let defaultTexture = new Texture2D(); - defaultTexture.setMipFilter(Texture2D.Filter.LINEAR); - defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR); - defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - defaultTexture._uuid = 'default-texture'; - defaultTexture.image = canvasImage; - - // default-texture-cube - let defaultTextureCube = new TextureCube(); - defaultTextureCube._uuid = 'default-texture-cube'; - defaultTextureCube.image = { - front: canvasImage, - back: canvasImage, - left: canvasImage, - right: canvasImage, - top: canvasImage, - bottom: canvasImage, - }; - - // black texture canvas fill - canvas.width = canvas.height = 2; - context.fillStyle = '#000'; - context.fillRect(0, 0, 2, 2); - - // black-texture - let blackTexture = new Texture2D(); - blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - blackTexture._uuid = 'black-texture'; - defaultTexture.image = canvasImage; - - // white texture canvas fill - canvas.width = canvas.height = 2; - context.fillStyle = '#fff'; - context.fillRect(0, 0, 2, 2); - - // white-texture - let whiteTexture = new Texture2D(); - blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - whiteTexture._uuid = 'white-texture'; - defaultTexture.image = canvasImage; - - // essential builtin effects - let efxs = effects.map(e => { - let effect = Object.assign(new EffectAsset(), e); - effect.onLoaded(); return effect; - }); - - // default material - let defaultMtl = new Material(); - defaultMtl._uuid = 'default-material'; - defaultMtl.effectAsset = efxs[0]; - defaultMtl.define('USE_COLOR', true); - defaultMtl.setProperty('color', cc.color('#FF00FF')); - - let builtins = { - [defaultTexture._uuid]: defaultTexture, - [defaultTextureCube._uuid]: defaultTextureCube, - [blackTexture._uuid]: blackTexture, - [whiteTexture._uuid]: whiteTexture, - [defaultMtl._uuid]: defaultMtl - }; - return Object.assign(builtinResMgr, builtins); - }, - initEffects(effectUUIDs, OnComplete) { - // ============================ - // async builtin effects - // ============================ - let remainingJobs = effectUUIDs.length; - for (let i = 0; i < effectUUIDs.length; ++i) { - let uuid = effectUUIDs[i]; - cc.AssetLibrary.loadAsset(uuid, err => { - if (err) console.error(err); - if (!--remainingJobs) OnComplete(); - }); - } - } -}; - -cc.BuiltinResMgr = builtinResMgr; -export default builtinResMgr; diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts new file mode 100644 index 0000000000..4ff4440c16 --- /dev/null +++ b/cocos/3d/builtin/init.ts @@ -0,0 +1,138 @@ +import { Asset } from '../../assets/asset'; +import { SpriteFrame } from '../../assets/CCSpriteFrame'; +import { ImageAsset } from '../../assets/image-asset'; +import { Texture2D } from '../../assets/texture-2d'; +import { Rect } from '../../core/value-types'; +import { GFXDevice } from '../../gfx/device'; +import { EffectAsset } from '../assets/effect-asset'; +import { TextureCube } from '../assets/texture-cube'; +import effects from './effects'; + +class BuiltinResMgr { + protected _device: GFXDevice | null = null; + protected _resources: Record = {}; + + // this should be called after renderer initialized + public initBuiltinRes (device: GFXDevice) { + this._device = device; + const resources = this._resources; + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d')!; + const imgAsset = new ImageAsset(canvas); + const l = canvas.width = canvas.height = 2; + const hl = l / 2; + + // ============================ + // builtin textures + // ============================ + + // black texture + context.fillStyle = '#000'; + context.fillRect(0, 0, l, l); + const blackTexture = new Texture2D(); + blackTexture._uuid = 'black-texture'; + blackTexture.image = imgAsset; + resources[blackTexture._uuid] = blackTexture; + + // grey texture + context.fillStyle = '#777'; + context.fillRect(0, 0, l, l); + const greyTexture = new Texture2D(); + greyTexture._uuid = 'grey-texture'; + greyTexture.image = imgAsset; + resources[greyTexture._uuid] = greyTexture; + + // white texture + context.fillStyle = '#fff'; + context.fillRect(0, 0, l, l); + const whiteTexture = new Texture2D(); + whiteTexture._uuid = 'white-texture'; + whiteTexture.image = imgAsset; + resources[whiteTexture._uuid] = whiteTexture; + + // white cube texture + // const whiteCubeTexture = new TextureCube(); + // whiteCubeTexture._uuid = 'white-cube-texture'; + // whiteCubeTexture.image = { + // front: new ImageAsset(canvas), + // back: new ImageAsset(canvas), + // left: new ImageAsset(canvas), + // right: new ImageAsset(canvas), + // top: new ImageAsset(canvas), + // bottom: new ImageAsset(canvas), + // }; + // whiteCubeTexture.onLoaded(); + // resources[whiteCubeTexture._uuid] = whiteCubeTexture; + + // normal texture + context.fillStyle = '#7f7fff'; + context.fillRect(0, 0, l, l); + const normalTexture = new Texture2D(); + normalTexture._uuid = 'normal-texture'; + normalTexture.image = imgAsset; + resources[normalTexture._uuid] = normalTexture; + + // default texture + canvas.width = canvas.height = 16; + context.fillStyle = '#ddd'; + context.fillRect(0, 0, 16, 16); + context.fillStyle = '#555'; + context.fillRect(0, 0, 8, 8); + context.fillStyle = '#555'; + context.fillRect(8, 8, 8, 8); + const defaultTexture = new Texture2D(); + defaultTexture._uuid = 'default-texture'; + defaultTexture.image = imgAsset; + resources[defaultTexture._uuid] = defaultTexture; + + // default cube texture + // const defaultCubeTexture = new TextureCube(); + // defaultCubeTexture._uuid = 'default-cube-texture'; + // defaultCubeTexture.image = { + // front: new ImageAsset(canvas), + // back: new ImageAsset(canvas), + // left: new ImageAsset(canvas), + // right: new ImageAsset(canvas), + // top: new ImageAsset(canvas), + // bottom: new ImageAsset(canvas), + // }; + // defaultCubeTexture.onLoaded(); + // resources.push(defaultCubeTexture); + + const spriteFrame = new SpriteFrame(); + spriteFrame._uuid = 'default-spriteframe'; + spriteFrame.setOriginalSize(cc.size(imgAsset.width, imgAsset.height)); + spriteFrame.setRect(new Rect(0, 0, imgAsset.width, imgAsset.height)); + spriteFrame.image = imgAsset; + spriteFrame.onLoaded(); + resources[spriteFrame._uuid] = spriteFrame; + + // builtin effects + effects.forEach((e: any) => { + const effect = Object.assign(new EffectAsset(), e); + effect.onLoaded(); + }); + + // default material + const defaultMtl = new cc.Material(); + defaultMtl._uuid = 'default-material'; + defaultMtl.setDefines({ USE_COLOR: true }); + defaultMtl.effectName = 'builtin-effect-unlit'; + defaultMtl.setProperty('color', cc.color('#FF00FF')); + resources[defaultMtl._uuid] = defaultMtl; + + // sprite material + const spriteMtl = new cc.Material(); + spriteMtl._uuid = 'sprite-material'; + spriteMtl.effectName = 'builtin-effect-sprite'; + spriteMtl.setProperty('u_texSampler', defaultTexture); + resources[spriteMtl._uuid] = spriteMtl; + } + + public get (uuid: string): T { + return this._resources[uuid] as T; + } +} + +const builtinResMgr = cc.builtinResMgr = new BuiltinResMgr(); +export { builtinResMgr }; diff --git a/cocos/3d/debugger/draw-mng.js b/cocos/3d/debugger/draw-mng.js index e4e211cea3..590b0e53e8 100644 --- a/cocos/3d/debugger/draw-mng.js +++ b/cocos/3d/debugger/draw-mng.js @@ -2,7 +2,7 @@ import { vec3, color3, mat4 } from '../vmath'; import { LinkedArray } from '../memop'; import { Node } from '../scene-graph'; import gfx from '../gfx'; -import { renderer } from '../renderer'; +import * as renderer from '../renderer'; import { sphere, wireframe } from '../primitives'; let _right = vec3.create(1, 0, 0); diff --git a/cocos/3d/debugger/index.js b/cocos/3d/debugger/index.js index 0cf5cfbaf5..eb7518cfe3 100644 --- a/cocos/3d/debugger/index.js +++ b/cocos/3d/debugger/index.js @@ -1,4 +1,4 @@ -import { renderer } from '../../renderer'; +import * as renderer from '../../renderer'; import OrbitCamera from './orbit-camera'; import DrawMng from './draw-mng'; import { createGrid } from './utils'; diff --git a/cocos/3d/debugger/utils.js b/cocos/3d/debugger/utils.js index d42febdbca..a84285605f 100644 --- a/cocos/3d/debugger/utils.js +++ b/cocos/3d/debugger/utils.js @@ -1,4 +1,4 @@ -import { renderer } from '../renderer'; +import * as renderer from '../renderer'; import { vec3, color3 } from '../vmath'; import { Node } from '../scene-graph'; diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js deleted file mode 100644 index 961ad8488e..0000000000 --- a/cocos/3d/framework/animation-component.js +++ /dev/null @@ -1,495 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import Component from '../../components/CCComponent'; -import { ccclass, property, executionOrder, menu, executeInEditMode } from '../../core/data/class-decorator'; -import Enum from '../../core/value-types/enum'; -import AnimationClip, { AnimationTarget, AnimationSampler } from '../assets/animation-clip'; - -/** - * !#en Animation State Class - * - * !#ch 动画状态类 - * @class AnimationState - */ -class AnimationState { - constructor(clip) { - /** - * !#en An animation clip that is played through this state - * - * !#ch 通过此状态播放的动画剪辑 - * @property clip - * @type {AnimationClip} - */ - this.clip = clip; - - /** - * !#en Blend mode - * - * !#ch 混合模式 - * @property blendMode - * @type {String} - */ - this.blendMode = AnimationState.BlendMode.Blend; - - /** - * !#en Wrapping mode - * - * !#ch 循环模式 - * @property wrapMode - * @type {String} - */ - this.wrapMode = AnimationState.WrapMode.Loop; - - /** - * !#en The playback speed - * - * !#ch 播放速度 - * @property speed - * @type {Number} - */ - this.speed = 1.0; - - /** - * !#en The current time of the animation. - * - * !#ch 当前动画播放时间 - * @property time - * @type {Number} - */ - this.time = 0.0; - - /** - * !#en The weight of animation. - * - * !#ch 动画权重 - * @property weight - * @type {Number} - */ - this.weight = 1.0; - } - - /** - * !#en The blend mode of animation state - * - * !#ch 动画状态的混合模式 - * @static - * @enum AnimationState.BlendMode - */ - static BlendMode = Enum({ - /** - * !#en Animations will be blended. - * - * !#ch 动画将被混合 - * @property Blend - * @readonly - * @type {String} - */ - Blend: 'blend', - /** - * !#en Animations will be added. - * - * !#ch 动画将被附加 - * @property Additive - * @readonly - * @type {String} - */ - Additive: 'additive' - }); - - /** - * !#en Wrapping mode of the animation. - * - * !#ch 动画状态的循环模式 - * @static - * @enum AnimationState.WrapMode - */ - static WrapMode = Enum({ - /** - * !#en Only once - * - * !#ch 只播放一次 - * @property Once - * @readonly - * @type {String} - */ - Once: 'once', - /** - * !#en Loop - * - * !#ch 循环播放 - * @property Additive - * @readonly - * @type {String} - */ - Loop: 'loop', - /** - * !#en Ping Pong - * - * !#ch 乒乓模式播放 - * @property PinpPong - * @readonly - * @type {String} - */ - PinpPong: 'ping-pong', - /** - * !#en Plays back the animation. The last frame is played until the end. - * - * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 - * @property Clamp - * @readonly - * @type {String} - */ - Clamp: 'clamp' - }); -} - -/** - * !#en Animation Controller - * - * !#ch 动画控制器 - * @class AnimationCtrl - */ -class AnimationCtrl { - constructor() { - /** - * @type {AnimationTarget} - */ - this._animationTarget = null; - - /** - * @type {AnimationSampler} - */ - this._animationSampler = null; - - this._current = null; - - this._next = null; - - this._blendTime = 0.0; - - this._blendDuration = 0.3; - } - - /** - * !#en Set up the animation target - * - * !#ch 设置动画目标 - * @param {AnimationTarget} animationTarget - */ - setAnimationTarget(animationTarget) { - this._animationTarget = animationTarget; - if (this._animationTarget) { - this._animationSampler = new AnimationSampler(this._animationTarget); - } - this._nodeIndexers = new Map(); - } - - /** - * !#en Animation fades in and out - * - * !#ch 动画的淡入淡出功能 - * @param {AnimationState} to - * @param {Number} duration - */ - crossFade(to, duration) { - if (this._current && duration > 0.0) { - this._next = to; - this._blendTime = 0.0; - this._blendDuration = duration; - } else { - this._current = to; - this._next = null; - } - } - - tick(dt) { - if (!this._animationSampler) { - return; - } - - this._animationSampler.reset(); - - // handle blend - if (this._current && this._next) { - let t0 = this._getTime(this._current); - let t1 = this._getTime(this._next); - - let alpha = this._blendTime / this._blendDuration; - - this._current.time += dt; - this._next.time += dt; - this._blendTime += dt; - - if (alpha > 1.0) { - this._current = this._next; - this._next = null; - this._animationSampler.sample(this._current.clip, t1, 1.0); - } else { - this._animationSampler.sample(this._current.clip, t0, alpha); - this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); - } - } - - // handle playing - if (this._current) { - let t0 = this._getTime(this._current); - this._animationSampler.sample(this._current.clip, t0, 1.0); - this._current.time += dt; - } - - this._animationSampler.apply(); - } - - /** - * !#en Get the play time of an animation clip in current animation state - * - * !#ch 返回当前动画状态下的动画剪辑播放时间 - * @param {AnimationState} state - Specify animation status - */ - _getTime(state) { - let t = state.time; - let length = state.clip.length; - t *= state.speed; - - if (state.wrapMode === 'once') { - if (t > length) { - t = 0.0; - } - } else if (state.wrapMode === 'loop') { - t %= length; - } else if (state.wrapMode === 'ping-pong') { - let order = Math.floor(t / length); - if (order % 2 === 1) { - t = length - t % length; - } - } - - return t; - } -} - -/** - * !#en - * Basic animation component for playing animation - * - * !#ch - * 基础动画组件用于动画播放 - * @class AnimationComponent - * @extends Component - */ -@ccclass('cc.AnimationComponent') -@executionOrder(99) -@executeInEditMode -@menu('Components/AnimationComponent') -export default class AnimationComponent extends Component { - /** - * @type {AnimationClip[]} - */ - @property - _clips = []; - - /** - * !#en Current clip - * - * !#ch 当前动画剪辑 - * @property currentClip - * @type {AnimationClip} - */ - @property({type:AnimationClip}) - currentClip = null; - - /** - * !#en Whether to start the animation automatically - * - * !#ch 是否启动时自动播放动画 - * @property playAutomatically - * @type {Boolean} - */ - @property - playAutomatically = false; - - _preview = false; - - @property({type: Boolean}) - get preview() { - return this._preview; - } - - set preview(value) { - this._preview = value; - if (value) { - if (this.currentClip) { - cc.engine.animatingInEditMode = true; - this.play(this.currentClip.name); - } - } else { - cc.engine.animatingInEditMode = false; - this._animCtrl.crossFade(null, 0); - } - } - - /** - * !#en Animation state - * - * !#ch 动画状态列表 - * @type {Object} - */ - _name2states = {}; - - constructor() { - super(); - - /** - * @type {AnimationTarget} - */ - this._target = null; - - /** - * !#en Animation controller - * - * !#ch 动画控制器 - * @type {AnimationCtrl} - */ - this._animCtrl = new AnimationCtrl(); - } - - /** - * !#en Clip required for animation playback - * - * !#ch 动画剪辑列表 - * @property clips - * @type {AnimationClip[]} - */ - @property([AnimationClip]) - get clips() { - return this._clips; - } - - set clips(val) { - this._clips = val; - } - - onLoad() { - this._clips.forEach(clip => { - this._name2states[clip.name] = new AnimationState(clip); - }); - - this._resetTarget(); - - if (this.playAutomatically != undefined && - this.playAutomatically && - this.currentClip != undefined && - this.currentClip) { - this.play(this.currentClip.name); - } - } - - update(dt) { - this._animCtrl.tick(dt); - } - - onDestroy() { - } - - onEnable() { - } - - onDisable() { - this._target = null; - this._animCtrl.setAnimationTarget(null); - } - - /** - * !#en Add an animation clip to the animation status list - * - * !#ch 添加动画剪辑到动画状态列表 - * @param {String} name - The name of animation clip - * @param {AnimationClip} animClip - Animation clip - */ - addClip(name, animClip) { - if (this._name2states[name]) { - console.warn(`Failed to add clip ${name}, the name already exsits.`); - return; - } - - this._clips.push(animClip); - this._name2states[name] = new AnimationState(animClip); - } - - /** - * !#en Get the animation state through the animation clip name - * - * !#ch 返回动画剪辑相对应的动画状态 - * @param {String} name - The name of animation clip - */ - getState(name) { - return this._name2states[name]; - } - - /** - * !#en Play the name of the animation clip - * - * !#ch 播放相对应名字的动画剪辑 - * @param {String} name - The name of animation clip - * @param {Number} fadeDuration - Fade duration - */ - play(name, fadeDuration = 0.3) { - if (!this._target) { - return; - } - - if (!this._name2states[name]) { - console.warn(`Failed to play animation ${name}, not found.`); - return; - } - - let animState = this._name2states[name]; - animState.time = 0.0; - - this._animCtrl.crossFade(animState, fadeDuration); - } - - _resetTarget() { - this._target = new AnimationTarget(); - this._clips.forEach(clip => { - clip.frames.forEach(frame => { - frame.channels.forEach(channel => { - const targetPath = channel.target; - if (this._target.get(targetPath)) { - return; - } - const targetNode = this.node.getChildByPath(targetPath); - if (!targetNode) { - console.warn(`Animation target ${targetPath} not found in scene graph.`); - return; - } - this._target.add(targetPath, targetNode); - }); - }); - }); - this._animCtrl.setAnimationTarget(this._target); - } -} diff --git a/cocos/3d/framework/animation-component.ts b/cocos/3d/framework/animation-component.ts new file mode 100644 index 0000000000..c308fb1f82 --- /dev/null +++ b/cocos/3d/framework/animation-component.ts @@ -0,0 +1,426 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +// @ts-check +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { ccenum } from '../../core/value-types/enum'; +import AnimationClip, { AnimationSampler, AnimationTarget } from '../assets/animation-clip'; + +enum BlendMode { + /** + * !#en Animations will be blended. + * + * !#ch 动画将被混合 + */ + Blend = 'blend', + /** + * !#en Animations will be added. + * + * !#ch 动画将被附加 + */ + Additive = 'additive', +} + +ccenum(BlendMode); + +enum WrapMode { + /** + * !#en Only once + * + * !#ch 只播放一次 + */ + Once = 'once', + + /** + * !#en Loop + * + * !#ch 循环播放 + */ + Loop = 'loop', + + /** + * !#en Ping Pong + * + * !#ch 乒乓模式播放 + */ + PinpPong = 'ping-pong', + + /** + * !#en Plays back the animation. The last frame is played until the end. + * + * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 + */ + Clamp = 'clamp', +} + +ccenum(WrapMode); + +/** + * !#en Animation State Class + * + * !#ch 动画状态类 + */ +class AnimationState { + /** + * !#en The blend mode of animation state. + * + * !#ch 动画状态的混合模式 + */ + public static BlendMode = BlendMode; + + /** + * !#en Wrapping mode of the animation. + * + * !#ch 动画状态的循环模式 + */ + public static WrapMode = WrapMode; + + /** + * !#en An animation clip that is played through this state + * + * !#ch 通过此状态播放的动画剪辑 + */ + public clip: AnimationClip; + + /** + * !#en Blend mode + * + * !#ch 混合模式 + */ + public blendMode: BlendMode = BlendMode.Blend; + + /** + * !#en Wrapping mode + * + * !#ch 循环模式 + */ + public wrapMode: WrapMode = WrapMode.Loop; + + /** + * !#en The playback speed + * + * !#ch 播放速度 + */ + public speed = 1.0; + + /** + * !#en The current time of the animation. + * + * !#ch 当前动画播放时间 + */ + public time: number = 0.0; + + /** + * !#en The weight of animation. + * + * !#ch 动画权重 + */ + public weight: number = 1.0; + + constructor (clip: AnimationClip) { + this.clip = clip; + } +} + +/** + * !#en Animation Controller + * + * !#ch 动画控制器 + */ +class AnimationCtrl { + private _animationTarget: AnimationTarget | null = null; + private _animationSampler: AnimationSampler | null = null; + private _current: AnimationState | null = null; + private _next: AnimationState | null = null; + private _blendTime = 0.0; + private _blendDuration = 0.3; + + /** + * !#en Set up the animation target + * + * !#ch 设置动画目标 + */ + public setAnimationTarget (animationTarget: AnimationTarget | null) { + this._animationTarget = animationTarget; + if (this._animationTarget) { + this._animationSampler = new AnimationSampler(this._animationTarget); + } + } + + /** + * !#en Animation fades in and out + * + * !#ch 动画的淡入淡出功能 + * @param to + * @param duration + */ + public crossFade (to: AnimationState | null, duration: number) { + if (this._current && duration > 0.0) { + this._next = to; + this._blendTime = 0.0; + this._blendDuration = duration; + } else { + this._current = to; + this._next = null; + } + } + + public tick (deltaTime: number) { + if (!this._animationSampler) { + return; + } + + this._animationSampler.reset(); + + // handle blend + if (this._current && this._next) { + const t0 = this._getTime(this._current); + const t1 = this._getTime(this._next); + + const alpha = this._blendTime / this._blendDuration; + + this._current.time += deltaTime; + this._next.time += deltaTime; + this._blendTime += deltaTime; + + if (alpha > 1.0) { + this._current = this._next; + this._next = null; + this._animationSampler.sample(this._current.clip, t1, 1.0); + } else { + this._animationSampler.sample(this._current.clip, t0, alpha); + this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); + } + } + + // handle playing + if (this._current) { + const t0 = this._getTime(this._current); + this._animationSampler.sample(this._current.clip, t0, 1.0); + this._current.time += deltaTime; + } + + this._animationSampler.apply(); + } + + /** + * !#en Get the play time of an animation clip in current animation state + * + * !#ch 返回当前动画状态下的动画剪辑播放时间 + * @param state - Specify animation status + */ + private _getTime (state: AnimationState) { + let t = state.time; + const length = state.clip.length; + t *= state.speed; + + if (state.wrapMode === 'once') { + if (t > length) { + t = 0.0; + } + } else if (state.wrapMode === 'loop') { + t %= length; + } else if (state.wrapMode === 'ping-pong') { + const order = Math.floor(t / length); + if (order % 2 === 1) { + t = length - t % length; + } + } + + return t; + } +} + +/** + * !#en + * Basic animation component for playing animation + * + * !#ch + * 基础动画组件用于动画播放 + */ +@ccclass('cc.AnimationComponent') +@executionOrder(99) +@executeInEditMode +@menu('Components/AnimationComponent') +export default class AnimationComponent extends Component { + @property({ type: [AnimationClip] }) + public _clips: AnimationClip[] = []; + + /** + * !#en Current clip + * + * !#ch 当前动画剪辑 + */ + @property({ type: AnimationClip }) + public currentClip: AnimationClip | null = null; + + /** + * !#en Whether to start the animation automatically + * + * !#ch 是否启动时自动播放动画 + */ + @property + public playAutomatically: boolean = false; + + private _preview = false; + + private _animationController: AnimationCtrl = new AnimationCtrl(); + + private _name2states: { [x: string]: AnimationState | undefined; } = {}; + + private _animationTarget: AnimationTarget | null = null; + + @property({ type: Boolean }) + get preview () { + return this._preview; + } + + set preview (value) { + this._preview = value; + if (value) { + if (this.currentClip) { + cc.engine.animatingInEditMode = true; + this.play(this.currentClip.name); + } + } else { + cc.engine.animatingInEditMode = false; + this._animationController.crossFade(null, 0); + } + } + + constructor () { + super(); + } + + /** + * !#en Clip required for animation playback + * + * !#ch 动画剪辑列表 + */ + @property({ type: [AnimationClip] }) + get clips () { + return this._clips; + } + + set clips (val) { + this._clips = val; + } + + public onLoad () { + this._clips.forEach((clip) => { + this._name2states[clip.name] = new AnimationState(clip); + }); + + this._resetTarget(); + + if (!CC_EDITOR && this.playAutomatically && this.currentClip) { + this.play(this.currentClip.name); + } + } + + public update (deltaTime: number) { + this._animationController.tick(deltaTime); + } + + public onDestroy () { + } + + public onEnable () { + } + + public onDisable () { + this._animationTarget = null; + this._animationController.setAnimationTarget(null); + } + + /** + * !#en Add an animation clip to the animation status list + * + * !#ch 添加动画剪辑到动画状态列表 + * @param name - The name of animation clip + * @param animationClip - Animation clip + */ + public addClip (name: string, animationClip: AnimationClip) { + if (this._name2states[name]) { + console.warn(`Failed to add clip ${name}, the name already exsits.`); + return; + } + + this._clips.push(animationClip); + this._name2states[name] = new AnimationState(animationClip); + } + + /** + * !#en Get the animation state through the animation clip name + * + * !#ch 返回动画剪辑相对应的动画状态 + * @param name - The name of animation clip + */ + public getState (name: string) { + return this._name2states[name]; + } + + /** + * !#en Play the name of the animation clip + * + * !#ch 播放相对应名字的动画剪辑 + * @param name - The name of animation clip + * @param fadeDuration - Fade duration + */ + public play (name: string, fadeDuration = 0.3) { + if (!this._animationTarget) { + return; + } + + const state = this._name2states[name]; + if (!state) { + console.warn(`Failed to play animation ${name}, not found.`); + return; + } + + state.time = 0.0; + this._animationController.crossFade(state, fadeDuration); + } + + public _resetTarget () { + const animationTarget = new AnimationTarget(); + this._clips.forEach((clip) => { + clip.channels.forEach((channel) => { + const targetPath = channel.target; + if (animationTarget.get(targetPath)) { + return; + } + const targetNode = this.node.getChildByPath(targetPath); + if (!targetNode) { + console.warn(`Animation target ${targetPath} not found in scene graph.`); + return; + } + animationTarget.add(targetPath, targetNode); + }); + }); + this._animationTarget = animationTarget; + this._animationController.setAnimationTarget(this._animationTarget); + } +} diff --git a/cocos/3d/framework/animation-system.js b/cocos/3d/framework/animation-system.js deleted file mode 100644 index c68d3b8165..0000000000 --- a/cocos/3d/framework/animation-system.js +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import System from '../ecs/system'; -import { FixedArray } from '../memop'; -/** - * @typedef {import('./animation-component').default} AnimationComponent - */ - -export default class AnimationSystem extends System { - constructor() { - super(); - - this._anims = new FixedArray(200); - } - - add(comp) { - this._anims.push(comp); - } - - remove(comp) { - this._anims.fastRemove(this._anims.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._anims.length; ++i) { -// let anim = this._anims.data[i]; -// if (!anim.enabled) { -// continue; -// } -// if (!anim.skeleton) { -// // console.error(`Animation component depends on skinning model component.`); -// let skeleton = findSkeleton(anim._entity); -// anim.skeleton = skeleton; -// } -// if (anim.skeleton) { -// anim._animCtrl.tick(this._app.deltaTime); -// } -// } -// } -} diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.ts similarity index 54% rename from cocos/3d/framework/camera-component.js rename to cocos/3d/framework/camera-component.ts index b2d516fe65..f3fc42378d 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.ts @@ -22,17 +22,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -// @ts-check -import RenderSystemActor from './renderSystemActor'; -import { renderer } from '../../renderer/index'; -import { toRadian } from '../../core/vmath'; -import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; -import { Color, Enum, Rect } from '../../core/value-types'; -import enums from '../../renderer/enums'; - -/** - * @typedef {import('../../core/value-types/index').Color} Color - */ +import { ray } from '../../3d/geom-utils'; +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { Enum, Rect, Vec3 } from '../../core/value-types'; +import { color4, toRadian } from '../../core/vmath'; +import { GFXClearFlag } from '../../gfx/define'; +import { Camera } from '../../renderer'; /** * !#en The light source type @@ -41,7 +37,7 @@ import enums from '../../renderer/enums'; * @static * @enum CameraComponent.Projection */ -let CameraProjection = Enum({ +const ProjectionType = Enum({ /** * !#en The orthogonal camera * @@ -59,14 +55,14 @@ let CameraProjection = Enum({ * @readonly * @type {Number} */ - PERSPECTIVE: 1 + PERSPECTIVE: 1, }); -let CameraClearFlag = Enum({ - SKYBOX: enums.CLEAR_SKYBOX | enums.CLEAR_DEPTH | enums.CLEAR_STENCIL, - SOLID_COLOR: enums.CLEAR_COLOR | enums.CLEAR_DEPTH | enums.CLEAR_STENCIL, - DEPTH_ONLY: enums.CLEAR_DEPTH | enums.CLEAR_STENCIL, - DONT_CLEAR: 0 +const CameraClearFlag = Enum({ + SKYBOX: GFXClearFlag.SKYBOX | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, + SOLID_COLOR: GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, + DEPTH_ONLY: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, + DONT_CLEAR: GFXClearFlag.NONE, }); /** @@ -74,44 +70,44 @@ let CameraClearFlag = Enum({ * * !#ch 相机组件 * @class CameraComponent - * @extends RenderSystemActor + * @extends Component */ @ccclass('cc.CameraComponent') @menu('Components/CameraComponent') @executeInEditMode -export default class CameraComponent extends RenderSystemActor{ - @property - _projection = CameraProjection.PERSPECTIVE; +export class CameraComponent extends Component { + public static ProjectionType = ProjectionType; @property - _priority = 0; - + protected _projection = ProjectionType.PERSPECTIVE; @property - _fov = 45; - + protected _priority = 0; @property - _orthoHeight = 10; - + protected _fov = 45; @property - _near = 0.01; - + protected _orthoHeight = 10; @property - _far = 1000.0; - + protected _near = 0.01; @property - _color = cc.color('#334C78'); - + protected _far = 1000.0; @property - _depth = 1; - + protected _color = cc.color('#334C78'); @property - _stencil = 0; - + protected _depth = 1; @property - _clearFlags = CameraClearFlag.SOLID_COLOR; - + protected _stencil = 0; @property - _rect = new Rect(0, 0, 1, 1); + protected _clearFlags = CameraClearFlag.SOLID_COLOR; + @property + protected _rect = new Rect(0, 0, 1, 1); + @property + protected _targetDisplay = 0; + + protected _camera: Camera | null = null; + + constructor () { + super(); + } /** * !#en The projection type of the camera @@ -120,36 +116,15 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property({ - type: CameraProjection + type: ProjectionType, }) - get projection() { + get projection () { return this._projection; } - set projection(val) { + set projection (val) { this._projection = val; - - let type = renderer.PROJ_PERSPECTIVE; - if (this._projection === CameraProjection.Ortho) { - type = renderer.PROJ_ORTHO; - } - this._camera.setType(type); - } - - /** - * !#en The camera priority - * - * !#ch 相机的优先级,优先级低的优先渲染 - * @type {Number} - */ - @property - get priority() { - return this._priority; - } - - set priority(val) { - this._priority = val; - this._camera.setPriority(val); + if (this._camera) { this._camera.projectionType = val; } } /** @@ -159,13 +134,13 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property - get fov() { + get fov () { return this._fov; } - set fov(val) { + set fov (val) { this._fov = val; - this._camera.setFov(toRadian(val)); + if (this._camera) { this._camera.fov = toRadian(val); } } /** @@ -175,13 +150,13 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property - get orthoHeight() { + get orthoHeight () { return this._orthoHeight; } - set orthoHeight(val) { + set orthoHeight (val) { this._orthoHeight = val; - this._camera.setOrthoHeight(val); + if (this._camera) { this._camera.orthoHeight = val; } } /** @@ -191,13 +166,13 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property - get near() { + get near () { return this._near; } - set near(val) { + set near (val) { this._near = val; - this._camera.setNear(val); + if (this._camera) { this._camera.nearClip = val; } } /** @@ -207,13 +182,13 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property - get far() { + get far () { return this._far; } - set far(val) { + set far (val) { this._far = val; - this._camera.setFar(val); + if (this._camera) { this._camera.farClip = val; } } /** @@ -223,13 +198,15 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Color} */ @property - get color() { + get color () { return this._color; } - set color(val) { + set color (val) { this._color = val; - this._camera.setColor(val.r / 255, val.g / 255, val.b / 255, val.a / 255); + if (this._camera) { this._camera.clearColor = + color4.create(val.r / 255, val.g / 255, val.b / 255, val.a / 255); + } } /** @@ -239,13 +216,13 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property - get depth() { + get depth () { return this._depth; } - set depth(val) { + set depth (val) { this._depth = val; - this._camera.setDepth(val); + if (this._camera) { this._camera.clearDepth = val; } } /** @@ -255,13 +232,13 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property - get stencil() { + get stencil () { return this._stencil; } - set stencil(val) { + set stencil (val) { this._stencil = val; - this._camera.setStencil(val); + if (this._camera) { this._camera.clearStencil = val; } } /** @@ -271,15 +248,15 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Number} */ @property({ - type: CameraClearFlag + type: CameraClearFlag, }) - get clearFlags() { + get clearFlags () { return this._clearFlags; } - set clearFlags(val) { + set clearFlags (val) { this._clearFlags = val; - this._camera.setClearFlags(val); + if (this._camera) { this._camera.clearFlag = val; } } /** @@ -289,55 +266,55 @@ export default class CameraComponent extends RenderSystemActor{ * @type {Rect} */ @property - get rect() { + get rect () { return this._rect; } - set rect(val) { + set rect (val) { this._rect = val; - this._camera.setRect(val.x, val.y, val.width, val.height); + if (this._camera) { this._camera.viewport = val; } } - static Projection = CameraProjection; - - constructor() { - super(); - this._camera = new renderer.Camera(); + @property + get targetDisplay () { + return this._targetDisplay; + } + set targetDisplay (val) { + this._targetDisplay = val; + if (this._camera) { this._camera.changeTargetDisplay(val); } } - onLoad() { - this.projection = this._projection; - this.priority = this._priority; - this.fov = this._fov; - this.orthoHeight = this._orthoHeight; - this.near = this._near; - this.far = this._far; - this.color = this._color; - this.depth = this._depth; - this.stencil = this._stencil; - this.clearFlags = this._clearFlags; - this.rect = this._rect; - this._camera.setStages(renderer.PassStage.DEFAULT | renderer.PassStage.FORWARD); - this._camera.setNode(this.node); + public onLoad () { + } - onEnable() { - this.scene.addCamera(this._camera); + public onEnable () { + this._camera = this._getRenderScene().createCamera(this); } - onDisable() { - this.scene.removeCamera(this._camera); + public onDisable () { + if (this._camera) { this._getRenderScene().destroyCamera(this._camera); } } - /** - * transform a screen position to world space - * @param out the resulting vector - * @param screenPos the screen position to be transformed - * @param width framebuffer width - * @param height framebuffer height - * @returns the resulting vector - */ - screenToWorld(out, screenPos, width, height) { - return this._camera.screenToWorld(out, screenPos, width, height); + public onDestroy () { + + } + + public screenPointToRay (x: number, y: number, out?: ray) { + if (!out) { out = ray.create(); } + if (this._camera) { this._camera.screenPointToRay(out, x, y); } + return out; + } + + public worldToScreen (worldPos: Vec3, out?: Vec3) { + if (!out) { out = new Vec3(); } + if (this._camera) { this._camera.worldToScreen(out, worldPos); } + return out; + } + + public screenToWorld (screenPos: Vec3, out?: Vec3) { + if (!out) { out = this.node.getWorldPosition(); } + if (this._camera) { this._camera.screenToWorld(out, screenPos); } + return out; } } diff --git a/cocos/3d/framework/index.js b/cocos/3d/framework/index.js index eeaeffaafe..cfabdc8433 100644 --- a/cocos/3d/framework/index.js +++ b/cocos/3d/framework/index.js @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ -import CameraComponent from './camera-component'; +import { CameraComponent } from './camera-component'; import AnimationComponent from './animation-component'; import LightComponent from './light-component'; -import ModelComponent from './model-component'; +import { ModelComponent } from './model-component'; import SkinningModelComponent from './skinning-model-component'; import SkyboxComponent from './skybox-component'; import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component'; diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js deleted file mode 100644 index 853118b51d..0000000000 --- a/cocos/3d/framework/light-component.js +++ /dev/null @@ -1,443 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import RenderSystemActor from './renderSystemActor'; -import { renderer } from '../../renderer/index'; -import { Color, Enum } from '../../core/value-types'; -import { toRadian } from '../../core/vmath'; -import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; - -/** - * !#en The light source type - * - * !#ch 光源类型 - * @static - * @enum LightComponent.Type - */ -const LightType = Enum({ - /** - * !#en The direction of light - * - * !#ch 平行光 - * @property Directional - * @readonly - * @type {Number} - */ - Directional: 0, - /** - * !#en The point of light - * - * !#ch 点光源 - * @property Point - * @readonly - * @type {Number} - */ - Point: 1, - /** - * !#en The spot of light - * - * !#ch 聚光灯 - * @property Spot - * @readonly - * @type {Number} - */ - Spot: 2, -}); - -/** - * !#en The shadow type - * - * !#ch 阴影类型 - * @static - * @enum LightComponent.ShadowType - */ -const LightShadowType = Enum({ - /** - * !#en No shadows - * - * !#ch 阴影关闭 - * @property None - * @readonly - * @type {Number} - */ - None: 0, - /** - * !#en Soft shadows - * - * !#ch 软阴影 - * @property Soft - * @readonly - * @type {Number} - */ - Soft: 1, - /** - * !#en Hard shadows - * - * !#ch 阴硬影 - * @property Hard - * @readonly - * @type {Number} - */ - Hard: 2, -}); - -/** - * !#en The Light Component - * - * !#ch 光源组件 - * @class LightComponent - * @extends RenderSystemActor - */ -@ccclass('cc.LightComponent') -@menu('Components/LightComponent') -@executeInEditMode -export default class LightComponent extends RenderSystemActor { - @property - _type = LightType.Directional; - - @property - _color = Color.WHITE; - - @property - _intensity = 1; - - @property - _range = 1; - - @property - _spotAngle = 60; - - @property - _spotExp = 1; - - @property - _shadowType = LightShadowType.None; - - @property - _shadowResolution = 1024; - - @property - _shadowDarkness = 0.5; - - @property - _shadowMinDepth = 1; - - @property - _shadowMaxDepth = 1000; - - @property - _shadowDepthScale = 250; - - @property - _shadowFrustumSize = 50; - - @property - _shadowBias = 0.0005; - - /** - * !#en The light source type - * - * !#ch 光源类型 - * - * @type {Number} - */ - @property({ - type: LightType - }) - get type() { - return this._type; - } - - set type(val) { - this._type = val; - - let type = renderer.LIGHT_DIRECTIONAL; - if (this._type === LightType.Point) { - type = renderer.LIGHT_POINT; - } else if (this._type === LightType.Spot) { - type = renderer.LIGHT_SPOT; - } - this._light.setType(type); - } - - /** - * !#en The light source color - * - * !#ch 光源颜色 - * @type {Color} - */ - @property - get color() { - return this._color; - } - - set color(val) { - this._color = val; - this._light.setColor(val.r / 255, val.g / 255, val.b / 255); - } - - /** - * !#en The light source intensity - * - * !#ch 光源强度 - * @type {Number} - */ - @property - get intensity() { - return this._intensity; - } - - set intensity(val) { - this._intensity = val; - this._light.setIntensity(val); - } - - /** - * !#en The light range, used for spot and point light - * - * !#ch 针对聚光灯和点光源设置光源范围 - * @type {Number} - */ - @property - get range() { - return this._range; - } - - set range(val) { - this._range = val; - this._light.setRange(val); - } - - /** - * !#en The spot light cone angle - * - * !#ch 聚光灯锥角 - * @type {Number} - */ - @property - get spotAngle() { - return this._spotAngle; - } - - set spotAngle(val) { - this._spotAngle = val; - this._light.setSpotAngle(toRadian(val)); - } - - /** - * !#en The spot light exponential - * - * !#ch 聚光灯指数 - * @type {Number} - */ - @property - get spotExp() { - return this._spotExp; - } - - set spotExp(val) { - this._spotExp = val; - this._light.setSpotExp(val); - } - - /** - * !#en The shadow type - * - * !#ch 阴影类型 - * @type {Number} shadowType - */ - @property({ - type: LightShadowType - }) - get shadowType() { - return this._shadowType; - } - - set shadowType(val) { - this._shadowType = val; - - let type = renderer.SHADOW_NONE; - if (val === LightShadowType.Hard) { - type = renderer.SHADOW_HARD; - } else if (val === LightShadowType.Soft) { - type = renderer.SHADOW_SOFT; - } - this._light.setShadowType(type); - } - - /** - * !#en The shadow resolution - * - * !#ch 阴影分辨率 - * - * @type {Number} - */ - @property - get shadowResolution() { - return this._shadowResolution; - } - - set shadowResolution(val) { - this._shadowResolution = val; - this._light.setShadowResolution(val); - } - - /** - * !#en The shadow darkness - * - * !#ch 阴影灰度值 - * - * @type {Number} - */ - @property - get shadowDarkness() { - return this._shadowDarkness; - } - - set shadowDarkness(val) { - this._shadowDarkness = val; - this._light.setShadowDarkness(val); - } - - /** - * !#en The shadow min depth - * - * !#ch 阴影最小深度 - * - * @type {Number} - */ - @property - get shadowMinDepth() { - return this._shadowMinDepth; - } - - set shadowMinDepth(val) { - this._shadowMinDepth = val; - this._light.setShadowMinDepth(val); - } - - /** - * !#en The shadow max depth - * - * !#ch 阴影最大深度 - * - * @type {Number} - */ - @property - get shadowMaxDepth() { - return this._shadowMaxDepth; - } - - set shadowMaxDepth(val) { - this._shadowMaxDepth = val; - this._light.setShadowMaxDepth(val); - } - - /** - * !#en The shadow depth scale - * - * !#ch 阴影深度比例 - * - * @type {Number} - */ - @property - get shadowDepthScale() { - return this._shadowDepthScale; - } - - set shadowDepthScale(val) { - this._shadowDepthScale = val; - this._light.setShadowDepthScale(val); - } - - /** - * !#en The shadow frustum size - * - * !#ch 阴影截锥体大小 - * - * @type {Number} - */ - @property - get shadowFrustumSize() { - return this._shadowFrustumSize; - } - - set shadowFrustumSize(val) { - this._shadowFrustumSize = val; - this._light.setShadowFrustumSize(val); - } - - /** - * !#en The shadow bias - * - * !#ch 阴影偏移量 - * - * @type {Number} - */ - @property - get shadowBias() { - return this._shadowBias; - } - - set shadowBias(val) { - this._shadowBias = val; - this._light.setShadowBias(val); - } - - static Type = LightType; - - static ShadowType = LightShadowType; - - constructor() { - super(); - - this._light = new renderer.Light(); - } - - onLoad() { - this._light.setNode(this.node); - this.type = this._type; - this.color = this._color; - this.intensity = this._intensity; - this.range = this._range; - this.spotAngle = this._spotAngle; - this.spotExp = this._spotExp; - this.shadowType = this._shadowType; - this.shadowResolution = this._shadowResolution; - this.shadowDarkness = this._shadowDarkness; - this.shadowMaxDepth = this._shadowMaxDepth; - this.shadowDepthScale = this._shadowDepthScale; - this.shadowFrustumSize = this._shadowFrustumSize; - this.shadowBias = this._shadowBias; - } - - onEnable() { - this.scene.addLight(this._light); - } - - onDisable() { - this.scene.removeLight(this._light); - } -} diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts new file mode 100644 index 0000000000..56de33dff6 --- /dev/null +++ b/cocos/3d/framework/light-component.ts @@ -0,0 +1,306 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { Color, Enum } from '../../core/value-types'; +import { toRadian } from '../../core/vmath'; +import { Light, LightType } from '../../renderer/scene/light'; +import { PointLight } from '../../renderer/scene/point-light'; +import { SpotLight } from '../../renderer/scene/spot-light'; + +/** + * !#en The light source type + * + * !#ch 光源类型 + * @static + * @enum LightComponent.Type + */ +const Type = Enum({ + /** + * !#en The direction of light + * + * !#ch 平行光 + * @property Directional + * @readonly + * @type {Number} + */ + DIRECTIONAL: LightType.DIRECTIONAL, + /** + * !#en The point of light + * + * !#ch 点光源 + * @property Point + * @readonly + * @type {Number} + */ + POINT: LightType.POINT, + /** + * !#en The spot of light + * + * !#ch 聚光灯 + * @property Spot + * @readonly + * @type {Number} + */ + SPOT: LightType.SPOT, +}); + +/** + * !#en The shadow type + * + * !#ch 阴影类型 + * @static + * @enum LightComponent.ShadowType + */ +const LightShadowType = Enum({ + /** + * !#en No shadows + * + * !#ch 阴影关闭 + * @property None + * @readonly + * @type {Number} + */ + None: 0, + /** + * !#en Soft shadows + * + * !#ch 软阴影 + * @property Soft + * @readonly + * @type {Number} + */ + Soft: 1, + /** + * !#en Hard shadows + * + * !#ch 阴硬影 + * @property Hard + * @readonly + * @type {Number} + */ + Hard: 2, +}); + +/** + * !#en The Light Component + * + * !#ch 光源组件 + * @class LightComponent + * @extends Component + */ +@ccclass('cc.LightComponent') +@menu('Components/LightComponent') +@executeInEditMode +export default class LightComponent extends Component { + + public static Type = Type; + public static ShadowType = LightShadowType; + + @property + protected _type = Type.DIRECTIONAL; + @property + protected _color = Color.WHITE; + @property + protected _intensity = 1; + @property + protected _range = 10; + @property + protected _spotAngle = 60; + + // @property + // protected _shadowType = LightShadowType.None; + // @property + // protected _shadowResolution = 1024; + // @property + // protected _shadowDarkness = 0.5; + // @property + // protected _shadowMinDepth = 1; + // @property + // protected _shadowMaxDepth = 1000; + // @property + // protected _shadowDepthScale = 250; + // @property + // protected _shadowFrustumSize = 50; + // @property + // protected _shadowBias = 0.0005; + + protected _light: Light | null = null; + protected _colorData = [1, 1, 1]; + + /** + * !#en The light source type + * + * !#ch 光源类型 + * + * @type {Number} + */ + @property({ + type: Type, + }) + get type () { + return this._type; + } + + set type (val) { + this._destroyLight(); + this._type = parseInt(val); + this._createLight(); + } + + /** + * !#en The light source color + * + * !#ch 光源颜色 + * @type {Color} + */ + @property + get color () { + return this._color; + } + + set color (val) { + this._color = val; + const scale = this._intensity / 255; + this._colorData[0] = val.r * scale; + this._colorData[1] = val.g * scale; + this._colorData[2] = val.b * scale; + if (this._light) { + this._light.color = this._colorData; + } + } + + /** + * !#en The light source intensity + * + * !#ch 光源强度 + * @type {Number} + */ + @property + get intensity () { + return this._intensity; + } + + set intensity (val) { + this._intensity = val; + const scale = val / 255; + this._colorData[0] = this._color.r * scale; + this._colorData[1] = this._color.g * scale; + this._colorData[2] = this._color.b * scale; + if (this._light) { + this._light.color = this._colorData; + } + } + + /** + * !#en The light range, used for spot and point light + * + * !#ch 针对聚光灯和点光源设置光源范围 + * @type {Number} + */ + @property + get range () { + return this._range; + } + + set range (val) { + this._range = val; + if (this._light && this._light instanceof PointLight || this._light instanceof SpotLight) { + this._light.range = val; + } + } + + /** + * !#en The spot light cone angle + * + * !#ch 聚光灯锥角 + * @type {Number} + */ + @property + get spotAngle () { + return this._spotAngle; + } + + set spotAngle (val) { + this._spotAngle = val; + if (this._light && this._light instanceof SpotLight) { + this._light.spotAngle = toRadian(val); + } + } + + public onEnable () { + this._createLight(); + if (this._light) { this._light.enabled = true; return; } + } + + public onDisable () { + if (this._light) { this._light.enabled = false; } + } + + public onDestroy () { + this._destroyLight(); + } + + protected _createLight () { + if (!this.node._scene || this._light) { return; } + const scene = this._getRenderScene(); + switch (this._type) { + case Type.DIRECTIONAL: + this._light = scene.createDirectionalLight(this.name, this.node); + break; + case Type.POINT: + this._light = scene.createPointLight(this.name, this.node); + this.range = this._range; + break; + case Type.SPOT: + this._light = scene.createSpotLight(this.name, this.node); + this.range = this._range; + this.spotAngle = this._spotAngle; + break; + default: + console.warn(`illegal light type ${this._type}`); + return; + } + if (!this._light) { console.warn('we don\'t support this many lights in forward pipeline.'); } + this.color = this._color; + } + + protected _destroyLight () { + if (!this.node._scene || !this._light) { return; } + const scene = this._getRenderScene(); + switch (this._type) { + case Type.DIRECTIONAL: + scene.destroyDirectionalLight(this._light); + break; + case Type.POINT: + scene.destroyPointLight(this._light); + break; + case Type.SPOT: + scene.destroySpotLight(this._light); + break; + } + this._light = null; + } +} diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js deleted file mode 100644 index cd656e6650..0000000000 --- a/cocos/3d/framework/model-component.js +++ /dev/null @@ -1,281 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import Model from '../../renderer/scene/model'; -import { ccclass, property, menu, executionOrder, executeInEditMode } from '../../core/data/class-decorator'; -import Mesh from '../assets/mesh'; -import Enum from '../../core/value-types/enum'; -import RenderableComponent from './renderable-component'; -/** - * @typedef {import('../assets/material').default} Material - */ - -/** - * !#en Shadow projection mode - * - * !#ch 阴影投射方式 - * @static - * @enum ModelComponent.ShadowCastingMode - */ -let ModelShadowCastingMode = Enum({ - /** - * !#en - * - * !#ch 关闭阴影投射 - * @property Off - * @readonly - * @type {Number} - */ - Off: 0, - /** - * !#en - * - * !#ch 开启阴影投射,当阴影光产生的时候 - * @property On - * @readonly - * @type {Number} - */ - On: 1, - /** - * !#en - * - * !#ch 可以从网格的任意一遍投射出阴影 - * @property TwoSided - * @readonly - * @type {Number} - */ - TwoSided: 2, - /** - * !#en - * - * !#ch 只显示阴影 - * @property ShadowsOnly - * @readonly - * @type {Number} - */ - ShadowsOnly: 3, -}); - -/** - * !#en The Model Component - * - * !#ch 模型组件 - * @class ModelComponent - * @extends RenderableComponent - */ -@ccclass('cc.ModelComponent') -@executionOrder(100) -@menu('Components/ModelComponent') -@executeInEditMode -export default class ModelComponent extends RenderableComponent { - - /** - * @type {Mesh} - */ - @property - _mesh = null; - - @property - _shadowCastingMode = ModelShadowCastingMode.Off; - - @property - _receiveShadows = false; - - /** - * @type {Material} - */ - static _builtinMaterial = null; - - /** - * !#en The mesh of the model - * - * !#ch 模型网格 - * @type {Mesh} - */ - @property({ - type: Mesh - }) - get mesh() { - return this._mesh; - } - - set mesh(val) { - this._mesh = val; - this._updateModels(); - } - - /** - * !#en The shadow casting mode - * - * !#ch 投射阴影方式 - * @type {Number} - */ - @property({ - type: ModelShadowCastingMode - }) - get shadowCastingMode() { - return this._shadowCastingMode; - } - - set shadowCastingMode(val) { - this._shadowCastingMode = val; - this._updateCastShadow(); - } - - /** - * !#en Does this model receive shadows? - * - * !#ch 是否接受阴影? - * @type {Boolean} - */ - @property - get receiveShadows() { - return this._receiveShadows; - } - - set receiveShadows(val) { - this._receiveShadows = val; - this._updateReceiveShadow(); - } - - static ShadowCastingMode = ModelShadowCastingMode; - - constructor() { - super(); - /** - * @type {Model[]} - */ - this._models = []; - } - - onLoad() { - this._updateModels(); - this._updateCastShadow(); - this._updateReceiveShadow(); - } - - onEnable() { - for (let i = 0; i < this._models.length; ++i) { - this.scene.addModel(this._models[i]); - } - } - - onDisable() { - for (let i = 0; i < this._models.length; ++i) { - this.scene.removeModel(this._models[i]); - } - } - - _updateModels() { - let meshCount = this._mesh ? this._mesh.subMeshCount : 0; - let oldModels = this._models; - - this._models = new Array(meshCount); - for (let i = 0; i < meshCount; ++i) { - let model = this._createModel(); - model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); - this._models[i] = model; - } - - this._updateModelParams(); - - if (this.enabled) { - for (let i = 0; i < oldModels.length; ++i) { - this.scene.removeModel(oldModels[i]); - } - for (let i = 0; i < this._models.length; ++i) { - this.scene.addModel(this._models[i]); - } - } - } - - _createModel() { - return new Model(); - } - - _updateModelParams() { - this.node._hasChanged = true; - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; - let material = this.getSharedMaterial(i); - let inputAssembler = this._mesh.getSubMesh(i); - - model.setInputAssembler(inputAssembler); - model.setNode(this.node); - this._updateModelMaterial(model, material); - } - } - - _onMaterialModified(idx, material) { - if (idx < this._models.length) { - this._updateModelMaterial(this._models[idx], material); - } - } - - _clearMaterials() { - for (let i = 0; i < this._models.length; ++i) { - this._onMaterialModified(i, null); - } - } - - /** - * - * @param {Model} model - * @param {Material} material - */ - _updateModelMaterial(model, material) { - model.setEffect((material ? material.effect : null) || this._getBuiltinMaterial().effect); - } - - _updateCastShadow() { - if (this._shadowCastingMode === ModelShadowCastingMode.Off) { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; - model._castShadow = false; - } - } else if (this._shadowCastingMode === ModelShadowCastingMode.On) { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; - model._castShadow = true; - } - } else { - console.warn(`ShadowCastingMode ${this._shadowCastingMode} is not supported.`); - } - } - - _updateReceiveShadow() { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; - if (model._defines['_USE_SHADOW_MAP'] != undefined) { - this.getMaterial(i).define('_USE_SHADOW_MAP', this._receiveShadows); - } - } - } - - _getBuiltinMaterial() { - // classic ugly pink indicating missing material - return cc.BuiltinResMgr['default-material']; - } -} diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts new file mode 100644 index 0000000000..2063beb14c --- /dev/null +++ b/cocos/3d/framework/model-component.ts @@ -0,0 +1,289 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import { builtinResMgr } from '../../3d/builtin'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import Enum from '../../core/value-types/enum'; +import { Model } from '../../renderer/scene/model'; +import { Material } from '../assets/material'; +import { Mesh } from '../assets/mesh'; +import { RenderableComponent } from './renderable-component'; + +/** + * !#en Shadow projection mode + * + * !#ch 阴影投射方式 + * @static + * @enum ModelComponent.ShadowCastingMode + */ +const ModelShadowCastingMode = Enum({ + /** + * !#en + * + * !#ch 关闭阴影投射 + * @property Off + * @readonly + * @type {Number} + */ + Off: 0, + /** + * !#en + * + * !#ch 开启阴影投射,当阴影光产生的时候 + * @property On + * @readonly + * @type {Number} + */ + On: 1, + /** + * !#en + * + * !#ch 可以从网格的任意一遍投射出阴影 + * @property TwoSided + * @readonly + * @type {Number} + */ + TwoSided: 2, + /** + * !#en + * + * !#ch 只显示阴影 + * @property ShadowsOnly + * @readonly + * @type {Number} + */ + ShadowsOnly: 3, +}); + +/** + * !#en The Model Component + * + * !#ch 模型组件 + * @class ModelComponent + * @extends RenderableComponent + */ +@ccclass('cc.ModelComponent') +@executionOrder(100) +@menu('Components/ModelComponent') +@executeInEditMode +export class ModelComponent extends RenderableComponent { + + /** + * !#en The mesh of the model + * + * !#ch 模型网格 + * @type {Mesh} + */ + @property({ + type: Mesh, + }) + get mesh () { + return this._mesh; + } + + set mesh (val) { + this._mesh = val; + this._updateModels(); + } + + /** + * !#en The shadow casting mode + * + * !#ch 投射阴影方式 + * @type {Number} + */ + @property({ + type: ModelShadowCastingMode, + }) + get shadowCastingMode () { + return this._shadowCastingMode; + } + + set shadowCastingMode (val) { + this._shadowCastingMode = val; + this._updateCastShadow(); + } + + /** + * !#en Does this model receive shadows? + * + * !#ch 是否接受阴影? + * @type {Boolean} + */ + @property + get receiveShadows () { + return this._receiveShadows; + } + + set receiveShadows (val) { + this._receiveShadows = val; + this._updateReceiveShadow(); + } + + get model () { + return this._model; + } + + public static ShadowCastingMode = ModelShadowCastingMode; + + protected _model: Model | null = null; + + @property + private _mesh: Mesh | null = null; + + @property + private _shadowCastingMode = ModelShadowCastingMode.Off; + + @property + private _receiveShadows = false; + + constructor () { + super(); + } + + public onLoad () { + super.onLoad(); + } + + public onEnable () { + if (!this._model) { this._updateModels(); } + this._updateCastShadow(); + this._updateReceiveShadow(); + if (this._model) { + this._model.enabled = true; + } + } + + public onDisable () { + if (this._model) { + this._model.enabled = false; + } + } + + public onDestroy () { + if (this._model) { + this._getRenderScene().destroyModel(this._model); + } + } + + protected _updateModels () { + if (!this.enabledInHierarchy || !this.node._scene || !this._mesh) { + return; + } + + if (this._model) { + this._model.destroy(); + } else { + this._model = this._createModel(); + } + + this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); + + this._updateModelParams(); + + if (this._model) { + this._model.enabled = true; + } + } + + protected _createModel () { + return this._getRenderScene().createModel(Model, this.node); + } + + protected _updateModelParams () { + this.node._hasChanged = true; + if (!this._mesh || !this._model) { + return; + } + const meshCount = this._mesh ? this._mesh.subMeshCount : 0; + for (let i = 0; i < meshCount; ++i) { + const material = this.getSharedMaterial(i); + const renderingMesh = this._mesh.renderingMesh; + if (renderingMesh) { + const subMeshData = renderingMesh.getSubmesh(i); + if (subMeshData) { + this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial()); + } + } + } + } + + protected _onMaterialModified (idx: number, material: Material | null) { + if (this._model == null) { + return; + } + this._onRebuildPSO(idx, material || this._getBuiltinMaterial()); + } + + protected _onRebuildPSO (idx: number, material: Material) { + if (this._model) { + this._model.setSubModelMaterial(idx, material); + } + } + + protected _clearMaterials () { + if (this._model == null) { + return; + } + for (let i = 0; i < this._model.subModelNum; ++i) { + this._onMaterialModified(i, null); + } + } + + private _updateCastShadow () { + if (!this.enabledInHierarchy || !this._model) { + return; + } + if (this._shadowCastingMode === ModelShadowCastingMode.Off) { + for (let i = 0; i < this._model.subModelNum; ++i) { + const subModel = this._model.getSubModel(i); + subModel.castShadow = false; + } + } else if (this._shadowCastingMode === ModelShadowCastingMode.On) { + for (let i = 0; i < this._model.subModelNum; ++i) { + const subModel = this._model.getSubModel(i); + subModel.castShadow = true; + } + } else { + console.warn(`ShadowCastingMode ${this._shadowCastingMode} is not supported.`); + } + } + + private _updateReceiveShadow () { + if (!this.enabledInHierarchy || !this._model) { + return; + } + // for (let i = 0; i < this._model.subModelNum; ++i) { + // const subModel = this._model.getSubModel(i); + // if (subModel._defines['CC_USE_SHADOW_MAP'] != undefined) { + // this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows); + // } + // } + } + + private _getBuiltinMaterial () { + // classic ugly pink indicating missing material + return builtinResMgr.get('default-material'); + } +} diff --git a/cocos/3d/framework/particle/animator/color-overtime.js b/cocos/3d/framework/particle/animator/color-overtime.ts similarity index 78% rename from cocos/3d/framework/particle/animator/color-overtime.js rename to cocos/3d/framework/particle/animator/color-overtime.ts index 0076e83137..082de437cb 100644 --- a/cocos/3d/framework/particle/animator/color-overtime.js +++ b/cocos/3d/framework/particle/animator/color-overtime.ts @@ -2,6 +2,9 @@ import { color4, pseudoRandom } from '../../../../core/vmath'; import { CCClass } from '../../../../core/data'; import GradientRange from './gradient-range'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import Particle from '../particle'; + +// tslint:disable: max-line-length const COLOR_OVERTIME_RAND_OFFSET = 91041; @@ -9,14 +12,14 @@ const COLOR_OVERTIME_RAND_OFFSET = 91041; export default class ColorOvertimeModule { @property - enable = false; + public enable = false; @property({ - type: GradientRange + type: GradientRange, }) - color = new GradientRange(); + public color = new GradientRange(); - animate(particle) { + public animate (particle: Particle) { if (this.enable) { color4.multiply(particle.color, particle.startColor01, this.color.evaluate(1.0 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + COLOR_OVERTIME_RAND_OFFSET))); } diff --git a/cocos/3d/framework/particle/animator/curve-range.js b/cocos/3d/framework/particle/animator/curve-range.ts similarity index 76% rename from cocos/3d/framework/particle/animator/curve-range.js rename to cocos/3d/framework/particle/animator/curve-range.ts index 501e516025..dd1e3eb3aa 100644 --- a/cocos/3d/framework/particle/animator/curve-range.js +++ b/cocos/3d/framework/particle/animator/curve-range.ts @@ -8,7 +8,7 @@ const Mode = Enum({ Constant: 0, Curve: 1, TwoCurves: 2, - TwoConstants: 3 + TwoConstants: 3, }); @ccclass('cc.CurveRange') @@ -20,37 +20,37 @@ export default class CurveRange { mode = Mode.Constant; @property({ - type: AnimationCurve + type: AnimationCurve, }) - curve = new AnimationCurve(); + public curve = new AnimationCurve(); @property({ - type: AnimationCurve + type: AnimationCurve, }) - curveMin = new AnimationCurve(); + public curveMin = new AnimationCurve(); @property({ - type: AnimationCurve + type: AnimationCurve, }) - curveMax = new AnimationCurve(); + public curveMax = new AnimationCurve(); @property - constant = 0; + public constant = 0; @property - constantMin = 0; + public constantMin = 0; @property - constantMax = 0; + public constantMax = 0; @property - multiplier = 1; + public multiplier = 1; - constructor() { + constructor () { } - evaluate(time, rndRatio) { + public evaluate (time: number, rndRatio: number) { switch (this.mode) { case Mode.Constant: return this.constant; diff --git a/cocos/3d/framework/particle/animator/force-overtime.js b/cocos/3d/framework/particle/animator/force-overtime.ts similarity index 50% rename from cocos/3d/framework/particle/animator/force-overtime.js rename to cocos/3d/framework/particle/animator/force-overtime.ts index cd5cac5587..3c3c35068f 100644 --- a/cocos/3d/framework/particle/animator/force-overtime.js +++ b/cocos/3d/framework/particle/animator/force-overtime.ts @@ -4,46 +4,53 @@ import CurveRange from './curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +// tslint:disable: max-line-length const FORCE_OVERTIME_RAND_OFFSET = 212165; @ccclass('cc.ForceOvertimeModule') export default class ForceOvertimeModule { @property - enable = false; + public enable = false; @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); - @property - space = Space.Local; + @property({ + type: Space, + }) + public space = Space.Local; // TODO:currently not supported - randomized = false; + public randomized = false; - constructor() { + private rotation: quat; + private needTransform: boolean; + + constructor () { this.rotation = quat.create(); + this.needTransform = false; } - update(space, worldTransform) { - this.needTransform = calculateTransform(space, this._space, worldTransform, this.rotation); + public update (space, worldTransform) { + this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } - animate(p, dt) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET))); + public animate (p, dt) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET))); if (this.needTransform) { vec3.transformQuat(force, force, this.rotation); } diff --git a/cocos/3d/framework/particle/animator/gradient-range.js b/cocos/3d/framework/particle/animator/gradient-range.ts similarity index 56% rename from cocos/3d/framework/particle/animator/gradient-range.js rename to cocos/3d/framework/particle/animator/gradient-range.ts index d716ba4d82..e32ab1d365 100644 --- a/cocos/3d/framework/particle/animator/gradient-range.js +++ b/cocos/3d/framework/particle/animator/gradient-range.ts @@ -4,6 +4,8 @@ import Gradient from './gradient'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +// tslint:disable: max-line-length + const GRADIENT_MODE_FIX = 0; const GRADIENT_MODE_BLEND = 1; @@ -18,7 +20,7 @@ const Mode = Enum({ Gradient: 1, TwoColors: 2, TwoGradients: 3, - RandomColor: 4 + RandomColor: 4, }); @ccclass('cc.GradientRange') @@ -30,30 +32,30 @@ export default class GradientRange { mode = Mode.Color; @property - color = cc.Color.WHITE; + public color = cc.Color.WHITE; @property - colorMin = cc.Color.WHITE; + public colorMin = cc.Color.WHITE; @property - colorMax = cc.Color.WHITE; + public colorMax = cc.Color.WHITE; @property({ - type: Gradient + type: Gradient, }) - gradient = new Gradient(); + public gradient = new Gradient(); @property({ - type: Gradient + type: Gradient, }) - gradientMin = new Gradient(); + public gradientMin = new Gradient(); @property({ - type: Gradient + type: Gradient, }) - gradientMax = new Gradient(); + public gradientMax = new Gradient(); - evaluate(time, rndRatio) { + public evaluate (time: number, rndRatio: number) { switch (this.mode) { case Mode.Color: return this.color; @@ -84,60 +86,72 @@ export default class GradientRange { // }); export class GradientUniform { - constructor(gr) { + public gr: GradientRange; + public minColor: Float32Array; + public maxColor: Float32Array; + public minColorKeyTime: Float32Array; + public minColorKeyValue: Float32Array; + public minAlphaKeyTime: Float32Array; + public minAlphaKeyValue: Float32Array; + public maxColorKeyTime: Float32Array; + public maxColorKeyValue: Float32Array; + public maxAlphaKeyTime: Float32Array; + public maxAlphaKeyValue: Float32Array; + + constructor (gr: GradientRange) { this.gr = gr; - if (gr._mode == 'color') { + if (gr.mode === 'color') { this.minColor = new Float32Array(4); - color4.array(this.minColor, gr._color); - } else if (gr._mode == 'twoColors') { + color4.array(this.minColor, gr.color); + } else if (gr.mode === 'twoColors') { this.minColor = new Float32Array(4); this.maxColor = new Float32Array(4); - color4.array(this.minColor, gr._colorMin); - color4.array(this.maxColor, gr._colorMax); - } else if (gr._mode == 'gradient') { - this.minColorKeyTime = new Float32Array(gr._gradient._colorKeys.length); + color4.array(this.minColor, gr.colorMin); + color4.array(this.maxColor, gr.colorMax); + } else if (gr.mode === 'gradient') { + this.minColorKeyTime = new Float32Array(gr.gradient.colorKeys.length); this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length); - this.minAlphaKeyTime = new Float32Array(gr._gradient._alphaKeys.length); + this.minAlphaKeyTime = new Float32Array(gr.gradient.alphaKeys.length); this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length); - this.constructor.generateGradientUniform(gr._gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); - } else if (gr._mode == 'twoGradients') { - this.minColorKeyTime = new Float32Array(gr._gradientMin._colorKeys.length); + this.constructor.generateGradientUniform(gr.gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); + } else if (gr.mode === 'twoGradients') { + this.minColorKeyTime = new Float32Array(gr.gradientMin.colorKeys.length); this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length); - this.minAlphaKeyTime = new Float32Array(gr._gradientMin._alphaKeys.length); + this.minAlphaKeyTime = new Float32Array(gr.gradientMin.alphaKeys.length); this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length); - this.constructor.generateGradientUniform(gr._gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); - this.maxColorKeyTime = new Float32Array(gr._gradientMax._colorKeys.length); + this.constructor.generateGradientUniform(gr.gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); + this.maxColorKeyTime = new Float32Array(gr.gradientMax.colorKeys.length); this.maxColorKeyValue = new Float32Array(3 * this.maxColorKeyTime.length); - this.maxAlphaKeyTime = new Float32Array(gr._gradientMax._alphaKeys.length); + this.maxAlphaKeyTime = new Float32Array(gr.gradientMax.alphaKeys.length); this.maxAlphaKeyValue = new Float32Array(this.maxAlphaKeyTime.length); - this.constructor.generateGradientUniform(gr._gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue); + this.constructor.generateGradientUniform(gr.gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue); } } - uploadUniform(device, name) { - if (this.gr._mode == 'color') { + public uploadUniform (device: any, name: string) { + if (this.gr.mode === 'color') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_COLOR); device.setUniform('u_' + name + '_minColor', this.minColor); - } else if (this.gr._mode == 'twoColors') { + } else if (this.gr.mode === 'twoColors') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_COLOR); device.setUniform('u_' + name + '_minColor', this.minColor); device.setUniform('u_' + name + '_maxColor', this.maxColor); - } else if (this.gr._mode == 'gradient') { + } else if (this.gr.mode === 'gradient') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_GRADIENT); - device.setUniform('u_' + name + '_minGradMode', this.gr._gradient._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); + device.setUniform('u_' + name + '_minGradMode', this.gr.gradient.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue); device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime); device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue); device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime); - } else if (this.gr._mode == 'twoGradients') { + } else if (this.gr.mode === 'twoGradients') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_GRADIENT); - device.setUniform('u_' + name + '_minGradMode', this.gr._gradientMin._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); + device.setUniform('u_' + name + '_minGradMode', this.gr.gradientMin.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue); device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime); device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue); device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime); - device.setUniform('u_' + name + '_maxGradMode', this.gr._gradientMax._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); + device.setUniform('u_' + name + '_maxGradMode', this.gr.gradientMax.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); device.setUniform('u_' + name + '_maxColorKeyValue', this.maxColorKeyValue); device.setUniform('u_' + name + '_maxColorKeyTime', this.maxColorKeyTime); device.setUniform('u_' + name + '_maxAlphaKeyValue', this.maxAlphaKeyValue); @@ -145,16 +159,16 @@ export class GradientUniform { } } - static generateGradientUniform(gradient, colorKeyTime, colorKeyValue, alphaKeyTime, alphaKeyValue) { - for (let i = 0; i < gradient._colorKeys.length; i++) { - colorKeyTime[i] = gradient._colorKeys[i]._time; - colorKeyValue[i * 3] = gradient._colorKeys[i]._color.r; - colorKeyValue[i * 3 + 1] = gradient._colorKeys[i]._color.g; - colorKeyValue[i * 3 + 2] = gradient._colorKeys[i]._color.b; + public static generateGradientUniform (gradient: Gradient, colorKeyTime: number, colorKeyValue: Float32Array, alphaKeyTime: number, alphaKeyValue: Float32Array) { + for (let i = 0; i < gradient.colorKeys.length; i++) { + colorKeyTime[i] = gradient.colorKeys[i].time; + colorKeyValue[i * 3] = gradient.colorKeys[i].color.r; + colorKeyValue[i * 3 + 1] = gradient.colorKeys[i].color.g; + colorKeyValue[i * 3 + 2] = gradient.colorKeys[i].color.b; } - for (let i = 0; i < gradient._alphaKeys.length; i++) { - alphaKeyTime[i] = gradient._alphaKeys[i]._time; - alphaKeyValue[i] = gradient._alphaKeys[i]._alpha; + for (let i = 0; i < gradient.alphaKeys.length; i++) { + alphaKeyTime[i] = gradient.alphaKeys[i].time; + alphaKeyValue[i] = gradient.alphaKeys[i].alpha; } } } diff --git a/cocos/3d/framework/particle/animator/gradient.js b/cocos/3d/framework/particle/animator/gradient.ts similarity index 66% rename from cocos/3d/framework/particle/animator/gradient.js rename to cocos/3d/framework/particle/animator/gradient.ts index 2061b768d2..e1d81d01e2 100644 --- a/cocos/3d/framework/particle/animator/gradient.js +++ b/cocos/3d/framework/particle/animator/gradient.ts @@ -1,21 +1,21 @@ import { repeat } from '../../../../core/vmath'; -import { Enum, ValueType } from '../../../../core/value-types'; +import { Enum, ValueType, Color } from '../../../../core/value-types'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; const Mode = Enum({ Blend: 0, - Fixed: 1 + Fixed: 1, }); @ccclass('cc.ColorKey') export class ColorKey { @property - color = cc.Color.WHITE; + public color = cc.Color.WHITE; @property - time = 0; + public time = 0; } // CCClass.fastDefine('cc.ColorKey', ColorKey, { @@ -27,10 +27,10 @@ export class ColorKey { export class AlphaKey { @property - alpha = 1; + public alpha = 1; @property - time = 0; + public time = 0; } // CCClass.fastDefine('cc.AlphaKey', AlphaKey, { @@ -42,24 +42,26 @@ export class AlphaKey { export default class Gradient { @property - colorKeys = []; + public colorKeys = new Array(); @property - alphaKeys = [] + public alphaKeys = new Array(); @property - mode = Mode.Blend; + public mode = Mode.Blend; - constructor() { + private _color: Color; + + constructor () { this._color = cc.Color.WHITE; } - setKeys(colorKeys, alphaKeys) { + public setKeys (colorKeys, alphaKeys) { this.colorKeys = colorKeys; this.alphaKeys = alphaKeys; } - sortKeys() { + public sortKeys () { if (this.colorKeys.length > 1) { this.colorKeys.sort((a, b) => a.time - b.time); } @@ -68,17 +70,17 @@ export default class Gradient { } } - getRGB(time) { + private getRGB (time: number) { if (this.colorKeys.length > 1) { time = repeat(time, 1); for (let i = 1; i < this.colorKeys.length; ++i) { - let preTime = this.colorKeys[i - 1].time; - let curTime = this.colorKeys[i].time; + const preTime = this.colorKeys[i - 1].time; + const curTime = this.colorKeys[i].time; if (time >= preTime && time < curTime) { - if (this._mode === 'fixed') { + if (this.mode === 'fixed') { return this.colorKeys[i].color; } - let factor = (time - preTime) / (curTime - preTime); + const factor = (time - preTime) / (curTime - preTime); this.colorKeys[i - 1].color.lerp(this.colorKeys[i].color, factor, this._color); return this._color; } @@ -96,17 +98,17 @@ export default class Gradient { } } - getAlpha(time) { + private getAlpha (time) { if (this.alphaKeys.length > 1) { time = repeat(time, 1); for (let i = 1; i < this.alphaKeys.length; ++i) { - let preTime = this.alphaKeys[i - 1].time; - let curTime = this.alphaKeys[i].time; + const preTime = this.alphaKeys[i - 1].time; + const curTime = this.alphaKeys[i].time; if (time >= preTime && time < curTime) { - if (this._mode === 'fixed') { + if (this.mode === 'fixed') { return this.alphaKeys[i].alpha; } - let factor = (time - preTime) / (curTime - preTime); + const factor = (time - preTime) / (curTime - preTime); return (this.alphaKeys[i - 1].alpha * (1 - factor) + this.alphaKeys[i].alpha * factor); } } @@ -118,19 +120,19 @@ export default class Gradient { } } - evaluate(time) { + public evaluate (time) { this.getRGB(time); - this._color.a = this.getAlpha(time); + this._color.a = this.getAlpha(time)!; return this._color; } - randomColor() { - let c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)]; - let a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)]; - this._color.r = c.r; - this._color.g = c.g; - this._color.b = c.b; - this._color.a = a; + public randomColor () { + const c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)]; + const a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)]; + this._color.r = c.color.r; + this._color.g = c.color.g; + this._color.b = c.color.b; + this._color.a = a.alpha; return this._color; } } diff --git a/cocos/3d/framework/particle/animator/limit-velocity-overtime.js b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts similarity index 64% rename from cocos/3d/framework/particle/animator/limit-velocity-overtime.js rename to cocos/3d/framework/particle/animator/limit-velocity-overtime.ts index f7307cd5e5..5c7ad59f4a 100644 --- a/cocos/3d/framework/particle/animator/limit-velocity-overtime.js +++ b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts @@ -3,73 +3,78 @@ import { CCClass } from '../../../../core/data'; import { Space } from '../particle-general-function'; import { property, ccclass } from '../../../../core/data/class-decorator'; import CurveRange from './curve-range'; +import Particle from '../particle'; +// tslint:disable: max-line-length const LIMIT_VELOCITY_RAND_OFFSET = 23541; @ccclass('cc.LimitVelocityOvertimeModule') export default class LimitVelocityOvertimeModule { - enable = false; + @property + public enable = false; @property({ - type: CurveRange + type: CurveRange, }) - limitX = new CurveRange(); + public limitX = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - limitY = new CurveRange(); + public limitY = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - limitZ = new CurveRange(); + public limitZ = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - limit = new CurveRange(); + public limit = new CurveRange(); @property - dampen = 0; + public dampen = 0; @property - separateAxes = false; + public separateAxes = false; - @property - space = Space.Local; + @property({ + type: Space, + }) + public space = Space.Local; // TODO:functions related to drag are temporarily not supported - drag = null; + public drag = null; - multiplyDragByParticleSize = false; + public multiplyDragByParticleSize = false; - multiplyDragByParticleVelocity = false; + public multiplyDragByParticleVelocity = false; - constructor() { + constructor () { } - animate(p) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let dampedVel = vec3.create(0, 0, 0); + public animate (p: Particle) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const dampedVel = vec3.create(0, 0, 0); if (this.separateAxes) { vec3.set(dampedVel, - dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen), - dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen), - dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen)); + dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen), + dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen), + dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen)); } else { vec3.normalize(dampedVel, p.ultimateVelocity); - vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen)); + vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen)); } vec3.copy(p.ultimateVelocity, dampedVel); } } -function dampenBeyondLimit(vel, limit, dampen) { - let sgn = Math.sign(vel); +function dampenBeyondLimit (vel: number, limit: number, dampen: number) { + const sgn = Math.sign(vel); let abs = Math.abs(vel); if (abs > limit) { abs = lerp(abs, limit, dampen); diff --git a/cocos/3d/framework/particle/animator/optimized-curve.js b/cocos/3d/framework/particle/animator/optimized-curve.js deleted file mode 100644 index c022c98dbe..0000000000 --- a/cocos/3d/framework/particle/animator/optimized-curve.js +++ /dev/null @@ -1,297 +0,0 @@ -import { OptimizedKey, evalOptCurve } from "../../../geom-utils/curve"; -import { repeat } from "../../../../core/vmath"; - -const CURVE_MODE_CONSTANT = 0; -const CURVE_MODE_RANDOM_CONSTANT = 1; -const CURVE_MODE_CURVE = 2; -const CURVE_MODE_RANDOM_CURVE = 3; - -const UNIFORM_CURVE_KEY_NUM = 8; - -//calculate the coefficience of the first order integral of the curve -function integrateKeyframe(coef) { - coef[0] = coef[0] / 4; - coef[1] = coef[1] / 3; - coef[2] = coef[2] / 2; - coef[3] = coef[3]; - return coef; -} - -//calculate the coefficience of the second order integral of the curve -function integrateKeyframeTwice(coef) { - coef[0] = coef[0] / 20; - coef[1] = coef[1] / 12; - coef[2] = coef[2] / 6; - coef[3] = coef[3] / 2; - return coef; -} - -export class OptimizedCurve { - constructor(constructUniform = false) { - this.optimizedKeys = new Array; //the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve. - this.integral = new Array; //the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored) - this.constructUniform = constructUniform; - } - - buildCurve(animationCurve, multiplier = 1) { - let keyNum = animationCurve.keyFrames.length - 1; - let i = 0; - if (this.optimizedKeys.length < keyNum) { - let keyToAdd = keyNum - this.optimizedKeys.length; - for (i = 0; i < keyToAdd; i++) { - let optKey = new OptimizedKey(); - this.optimizedKeys.push(optKey); - } - } else { - this.optimizedKeys.splice(keyNum); - } - if (animationCurve.keyFrames.length === 1) { - this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value * multiplier; - this.optimizedKeys[0].time = 0; - this.optimizedKeys[0].endTime = 1; - } else { - let keyOffset = 0; - if (animationCurve.keyFrames[0].time !== 0) { - this.optimizedKeys.splice(0, 0, new OptimizedKey()); - this.optimizedKeys[0].time = 0; - this.optimizedKeys[0].endTime = animationCurve.keyFrames[0].time; - this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value; - keyOffset = 1; - } - for (i = 0; i < keyNum; i++) { - animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum)); - this.optimizedKeys[i + keyOffset].index += keyOffset; - } - if (animationCurve.keyFrames[animationCurve.keyFrames.length - 1].time !== 1) { - this.optimizedKeys.push(new OptimizedKey()); - this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames[animationCurve.length - 1].time; - this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1; - this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames[animationCurve.length - 1].value; - } - } - for (i = 0; i < this.optimizedKeys.length; i++) { - this.optimizedKeys[i].coefficient[0] *= multiplier; - this.optimizedKeys[i].coefficient[1] *= multiplier; - this.optimizedKeys[i].coefficient[2] *= multiplier; - this.optimizedKeys[i].coefficient[3] *= multiplier; - } - if (this.constructUniform) { - this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4); - this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM); - this.updateKeyUniform(); - } - } - - evaluate(time) { - time = repeat(time, 1); - for (let i = 1; i < this.optimizedKeys.length; i++) { - if (time < this.optimizedKeys[i].time) { - return this.optimizedKeys[i - 1].evaluate(time); - } - } - return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time); - } - - //calculate first order integral coefficients of all keys - integrateOnce() { - let i = 0; - if (this.integral.length + 1 < this.optimizedKeys.length) { - for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { - this.integral.push(0); - } - } else { - this.integral.splice(this.optimizedKeys.length - 1); - } - for (i = 0; i < this.integral.length; i++) { - integrateKeyframe(this.optimizedKeys[i].coefficient); - let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; - let prevIntegral = i === 0 ? 0 : this.integral[i - 1]; - this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); - } - integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); - if (this.constructUniform) { - this.updateKeyUniform(); - this.updateIntegralUniform(); - } - } - - //get the integral of the curve using calculated coefficients - evaluateIntegral(t, ts = 1) { - t = repeat(t, 1); - for (let i = 1; i < this.optimizedKeys.length; i++) { - if (t < this.optimizedKeys[i].time) { - let prevInt = i === 1 ? 0 : this.integral[i - 2]; - let dt = t - this.optimizedKeys[i - 1].time; - return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); - } - } - let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; - return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); - } - - //calculate second order integral coefficients of all keys - integrateTwice() { - let i = 0; - if (this.integral.length + 1 < this.optimizedKeys.length) { - for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { - this.integral.push(0); - } - } else { - this.integral.splice(this.optimizedKeys.length - 1); - } - for (i = 0; i < this.integral.length; i++) { - integrateKeyframeTwice(this.optimizedKeys[i].coefficient); - let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; - let prevIntegral = i === 0 ? 0 : this.integral[i - 1]; - this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); - } - integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); - if (this.constructUniform) { - this.updateKeyUniform(); - this.updateIntegralUniform(); - } - } - - //get the second order integral of the curve using calculated coefficients - evaluateIntegralTwice(t, ts = 1) { - t = repeat(t, 1); - for (let i = 1; i < this.optimizedKeys.length; i++) { - if (t < this.optimizedKeys[i].time) { - let prevInt = i === 1 ? 0 : this.integral[i - 2]; - let dt = t - this.optimizedKeys[i - 1].time; - return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); - } - } - let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; - return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); - } - - updateKeyUniform() { - for (let i = 0; i < this.optimizedKeys.length; i++) { - this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0]; - this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1]; - this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2]; - this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3]; - this.timeUniform[i] = this.optimizedKeys[i].endTime; - } - } - - updateIntegralUniform() { - this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1); - for (let i = 0; i < this.integral.length; i++) { - this.integralUniform[i] = this.integral[i]; - } - } -} - -export class CurveUniform { - constructCurve(cr) { - this.mode = cr.mode; - switch (cr.mode) { - case 'constant': - this.minConstant = cr.constant; - break; - case 'twoConstants': - this.minConstant = cr.constantMin; - this.maxConstant = cr.constantMax; - break; - case 'curve': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curve, cr.multiplier); - break; - case 'twoCurves': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curveMin, cr.multiplier); - this.maxCurve = new OptimizedCurve(true); - this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); - break; - } - } - - constructCurveIntegral(cr) { - this.mode = cr.mode; - switch (cr.mode) { - case 'constant': - this.minConstant = cr.constant; - break; - case 'twoConstants': - this.minConstant = cr.constantMin; - this.maxConstant = cr.constantMax; - break; - case 'curve': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curve, cr.multiplier); - this.minCurve.integrateOnce(); - break; - case 'twoCurves': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curveMin, cr.multiplier); - this.minCurve.integrateOnce(); - this.maxCurve = new OptimizedCurve(true); - this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); - this.maxCurve.integrateOnce(); - break; - } - } - - constructCurveIntegralTwice(cr) { - this.mode = cr.mode; - switch (cr.mode) { - case 'constant': - this.minConstant = cr.constant; - break; - case 'twoConstants': - this.minConstant = cr.constantMin; - this.maxConstant = cr.constantMax; - break; - case 'curve': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curve, cr.multiplier); - this.minCurve.integrateTwice(); - break; - case 'twoCurves': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curveMin, cr.multiplier); - this.minCurve.integrateTwice(); - this.maxCurve = new OptimizedCurve(true); - this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); - this.maxCurve.integrateTwice(); - break; - } - } - - uploadUniform(device, name) { - switch (this.mode) { - case 'constant': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT); - device.setUniform('u_' + name + '_minConstant', this.minConstant); - break; - case 'twoConstants': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT); - device.setUniform('u_' + name + '_minConstant', this.minConstant); - device.setUniform('u_' + name + '_maxConstant', this.maxConstant); - break; - case 'curve': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE); - device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); - device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); - if (this.minCurve.integralUniform !== undefined) { - device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); - } - break; - case 'twoCurves': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE); - device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); - device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); - if (this.minCurve.integralUniform !== undefined) { - device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); - } - device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform); - device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform); - if (this.minCurve.integralUniform !== undefined) { - device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform); - } - break; - } - } -} diff --git a/cocos/3d/framework/particle/animator/optimized-curve.ts b/cocos/3d/framework/particle/animator/optimized-curve.ts new file mode 100644 index 0000000000..ded36f8cd3 --- /dev/null +++ b/cocos/3d/framework/particle/animator/optimized-curve.ts @@ -0,0 +1,313 @@ +import { OptimizedKey, evalOptCurve, AnimationCurve } from "../../../geom-utils/curve"; +import { repeat } from "../../../../core/vmath"; +import CurveRange from "./curve-range"; + +// tslint:disable: max-line-length + +const CURVE_MODE_CONSTANT = 0; +const CURVE_MODE_RANDOM_CONSTANT = 1; +const CURVE_MODE_CURVE = 2; +const CURVE_MODE_RANDOM_CURVE = 3; + +const UNIFORM_CURVE_KEY_NUM = 8; + +// calculate the coefficience of the first order integral of the curve +function integrateKeyframe (coef: Float32Array) { + coef[0] = coef[0] / 4; + coef[1] = coef[1] / 3; + coef[2] = coef[2] / 2; + coef[3] = coef[3]; + return coef; +} + +// calculate the coefficience of the second order integral of the curve +function integrateKeyframeTwice (coef: Float32Array) { + coef[0] = coef[0] / 20; + coef[1] = coef[1] / 12; + coef[2] = coef[2] / 6; + coef[3] = coef[3] / 2; + return coef; +} + +export class OptimizedCurve { + private optimizedKeys: OptimizedKey[]; + private integral: number[]; + private constructUniform: boolean; + private coefUniform: Float32Array; + private timeUniform: Float32Array; + private integralUniform: Float32Array; + + constructor (constructUniform = false) { + this.optimizedKeys = new Array(); // the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve. + this.integral = new Array(); // the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored) + this.constructUniform = constructUniform; + } + + public buildCurve (animationCurve: AnimationCurve, multiplier: number = 1) { + const keyNum = animationCurve.keyFrames!.length - 1; + let i = 0; + if (this.optimizedKeys.length < keyNum) { + const keyToAdd = keyNum - this.optimizedKeys.length; + for (i = 0; i < keyToAdd; i++) { + const optKey = new OptimizedKey(); + this.optimizedKeys.push(optKey); + } + } else { + this.optimizedKeys.splice(keyNum); + } + if (animationCurve.keyFrames!.length === 1) { + this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value * multiplier; + this.optimizedKeys[0].time = 0; + this.optimizedKeys[0].endTime = 1; + } else { + let keyOffset = 0; + if (animationCurve.keyFrames![0].time !== 0) { + this.optimizedKeys.splice(0, 0, new OptimizedKey()); + this.optimizedKeys[0].time = 0; + this.optimizedKeys[0].endTime = animationCurve.keyFrames![0].time; + this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value; + keyOffset = 1; + } + for (i = 0; i < keyNum; i++) { + animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum)); + this.optimizedKeys[i + keyOffset].index += keyOffset; + } + if (animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time !== 1) { + this.optimizedKeys.push(new OptimizedKey()); + this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time; + this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1; + this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].value; + } + } + for (i = 0; i < this.optimizedKeys.length; i++) { + this.optimizedKeys[i].coefficient[0] *= multiplier; + this.optimizedKeys[i].coefficient[1] *= multiplier; + this.optimizedKeys[i].coefficient[2] *= multiplier; + this.optimizedKeys[i].coefficient[3] *= multiplier; + } + if (this.constructUniform) { + this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4); + this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM); + this.updateKeyUniform(); + } + } + + public evaluate (time: number) { + time = repeat(time, 1); + for (let i = 1; i < this.optimizedKeys.length; i++) { + if (time < this.optimizedKeys[i].time) { + return this.optimizedKeys[i - 1].evaluate(time); + } + } + return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time); + } + + // calculate first order integral coefficients of all keys + public integrateOnce () { + let i = 0; + if (this.integral.length + 1 < this.optimizedKeys.length) { + for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { + this.integral.push(0); + } + } else { + this.integral.splice(this.optimizedKeys.length - 1); + } + for (i = 0; i < this.integral.length; i++) { + integrateKeyframe(this.optimizedKeys[i].coefficient); + const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; + const prevIntegral = i === 0 ? 0 : this.integral[i - 1]; + this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); + } + integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); + if (this.constructUniform) { + this.updateKeyUniform(); + this.updateIntegralUniform(); + } + } + + // get the integral of the curve using calculated coefficients + public evaluateIntegral (t: number, ts: number = 1) { + t = repeat(t, 1); + for (let i = 1; i < this.optimizedKeys.length; i++) { + if (t < this.optimizedKeys[i].time) { + const prevInt = i === 1 ? 0 : this.integral[i - 2]; + const dt = t - this.optimizedKeys[i - 1].time; + return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); + } + } + const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; + return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); + } + + // calculate second order integral coefficients of all keys + public integrateTwice () { + let i = 0; + if (this.integral.length + 1 < this.optimizedKeys.length) { + for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { + this.integral.push(0); + } + } else { + this.integral.splice(this.optimizedKeys.length - 1); + } + for (i = 0; i < this.integral.length; i++) { + integrateKeyframeTwice(this.optimizedKeys[i].coefficient); + const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; + const prevIntegral = i === 0 ? 0 : this.integral[i - 1]; + this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); + } + integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); + if (this.constructUniform) { + this.updateKeyUniform(); + this.updateIntegralUniform(); + } + } + + // get the second order integral of the curve using calculated coefficients + public evaluateIntegralTwice (t: number, ts: number = 1) { + t = repeat(t, 1); + for (let i = 1; i < this.optimizedKeys.length; i++) { + if (t < this.optimizedKeys[i].time) { + const prevInt = i === 1 ? 0 : this.integral[i - 2]; + const dt = t - this.optimizedKeys[i - 1].time; + return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); + } + } + const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; + return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); + } + + public updateKeyUniform () { + for (let i = 0; i < this.optimizedKeys.length; i++) { + this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0]; + this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1]; + this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2]; + this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3]; + this.timeUniform[i] = this.optimizedKeys[i].endTime; + } + } + + public updateIntegralUniform () { + this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1); + for (let i = 0; i < this.integral.length; i++) { + this.integralUniform[i] = this.integral[i]; + } + } +} + +export class CurveUniform { + private mode: number; + private minConstant: number; + private maxConstant: number; + private minCurve: OptimizedCurve; + private maxCurve: OptimizedCurve; + + public constructCurve (cr: CurveRange) { + this.mode = cr.mode; + switch (cr.mode) { + case 'constant': + this.minConstant = cr.constant; + break; + case 'twoConstants': + this.minConstant = cr.constantMin; + this.maxConstant = cr.constantMax; + break; + case 'curve': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curve, cr.multiplier); + break; + case 'twoCurves': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curveMin, cr.multiplier); + this.maxCurve = new OptimizedCurve(true); + this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); + break; + } + } + + public constructCurveIntegral (cr: CurveRange) { + this.mode = cr.mode; + switch (cr.mode) { + case 'constant': + this.minConstant = cr.constant; + break; + case 'twoConstants': + this.minConstant = cr.constantMin; + this.maxConstant = cr.constantMax; + break; + case 'curve': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curve, cr.multiplier); + this.minCurve.integrateOnce(); + break; + case 'twoCurves': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curveMin, cr.multiplier); + this.minCurve.integrateOnce(); + this.maxCurve = new OptimizedCurve(true); + this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); + this.maxCurve.integrateOnce(); + break; + } + } + + public constructCurveIntegralTwice (cr: CurveRange) { + this.mode = cr.mode; + switch (cr.mode) { + case 'constant': + this.minConstant = cr.constant; + break; + case 'twoConstants': + this.minConstant = cr.constantMin; + this.maxConstant = cr.constantMax; + break; + case 'curve': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curve, cr.multiplier); + this.minCurve.integrateTwice(); + break; + case 'twoCurves': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curveMin, cr.multiplier); + this.minCurve.integrateTwice(); + this.maxCurve = new OptimizedCurve(true); + this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); + this.maxCurve.integrateTwice(); + break; + } + } + + public uploadUniform (device: any, name: number) { + switch (this.mode) { + case 'constant': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT); + device.setUniform('u_' + name + '_minConstant', this.minConstant); + break; + case 'twoConstants': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT); + device.setUniform('u_' + name + '_minConstant', this.minConstant); + device.setUniform('u_' + name + '_maxConstant', this.maxConstant); + break; + case 'curve': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE); + device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); + device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); + if (this.minCurve.integralUniform !== undefined) { + device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); + } + break; + case 'twoCurves': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE); + device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); + device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); + if (this.minCurve.integralUniform !== undefined) { + device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); + } + device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform); + device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform); + if (this.minCurve.integralUniform !== undefined) { + device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform); + } + break; + } + } +} diff --git a/cocos/3d/framework/particle/animator/rotation-overtime.js b/cocos/3d/framework/particle/animator/rotation-overtime.ts similarity index 65% rename from cocos/3d/framework/particle/animator/rotation-overtime.js rename to cocos/3d/framework/particle/animator/rotation-overtime.ts index d015e9ceb5..29d1de795a 100644 --- a/cocos/3d/framework/particle/animator/rotation-overtime.js +++ b/cocos/3d/framework/particle/animator/rotation-overtime.ts @@ -2,23 +2,26 @@ import { pseudoRandom } from "../../../../core/vmath"; import { CCClass } from "../../../../core/data"; import CurveRange from "./curve-range"; import { property, ccclass } from "../../../../core/data/class-decorator"; +import Particle from "../particle"; +// tslint:disable: max-line-length const ROTATION_OVERTIME_RAND_OFFSET = 125292; @ccclass('cc.RotationOvertimeModule') export default class RotationOvertimeModule { @property - enable = false; + public enable = false; @property - _separateAxes = false; + private _separateAxes = false; - get separateAxes() { + @property + get separateAxes () { return this._separateAxes; } - set separateAxes(val) { + set separateAxes (val) { if (!val) { this._separateAxes = val; } @@ -28,28 +31,28 @@ export default class RotationOvertimeModule { } @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); - constructor() { + constructor () { } - animate(p, dt) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + public animate (p: Particle, dt: number) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; if (!this._separateAxes) { - p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET)) * dt; + p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET))! * dt; } else { // TODO: separateAxes is temporarily not supported! diff --git a/cocos/3d/framework/particle/animator/size-overtime.js b/cocos/3d/framework/particle/animator/size-overtime.ts similarity index 69% rename from cocos/3d/framework/particle/animator/size-overtime.js rename to cocos/3d/framework/particle/animator/size-overtime.ts index 63f77d09aa..d885bb5521 100644 --- a/cocos/3d/framework/particle/animator/size-overtime.js +++ b/cocos/3d/framework/particle/animator/size-overtime.ts @@ -2,41 +2,43 @@ import { vec3, pseudoRandom } from '../../../../core/vmath'; import CurveRange from './curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import Particle from '../particle'; +// tslint:disable: max-line-length const SIZE_OVERTIME_RAND_OFFSET = 39825; @ccclass('cc.SizeOvertimeModule') export default class SizeOvertimeModule { @property - enable = false; + public enable = false; @property - separateAxes = false; + public separateAxes = false; @property({ - type: CurveRange + type: CurveRange, }) - size = new CurveRange(); + public size = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); - animate(particle) { + public animate (particle: Particle) { if (!this.separateAxes) { - vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET))); + vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET))!); } } } diff --git a/cocos/3d/framework/particle/animator/texture-animation.js b/cocos/3d/framework/particle/animator/texture-animation.ts similarity index 51% rename from cocos/3d/framework/particle/animator/texture-animation.js rename to cocos/3d/framework/particle/animator/texture-animation.ts index 6c04f88d3b..071a112510 100644 --- a/cocos/3d/framework/particle/animator/texture-animation.js +++ b/cocos/3d/framework/particle/animator/texture-animation.ts @@ -3,42 +3,45 @@ import { Enum } from "../../../../core/value-types"; import CurveRange from "./curve-range"; import { CCClass } from "../../../../core/data"; import { property, ccclass } from "../../../../core/data/class-decorator"; +import ParticleSystemComponent from "../particle-system-component"; +import Particle from "../particle"; +// tslint:disable: max-line-length const TEXTURE_ANIMATION_RAND_OFFSET = 90794; const Mode = Enum({ Grid: 0, - Sprites: 1 + Sprites: 1, }); const Animation = Enum({ WholeSheet: 0, - SingleRow: 1 + SingleRow: 1, }); @ccclass('cc.TextureAnimationModule') export default class TextureAnimationModule { @property - _enable = false; + private _enable = false; - get enable() { + get enable () { return this._enable; } - set enable(val) { + set enable (val) { this._enable = val; - this.ps.renderer._updateMaterialParams(); + this.ps!.renderer!._updateMaterialParams(); } @property - _mode = Mode.Grid + private _mode = Mode.Grid; - get mode() { + get mode () { return this._mode; } - set mode(val) { + set mode (val) { if (val === Mode.Sprites) { console.error("particle texture animation's sprites is not supported!"); return; @@ -46,89 +49,91 @@ export default class TextureAnimationModule { } @property - numTilesX = 0; + public numTilesX = 0; @property - numTilesY = 0; + public numTilesY = 0; @property - animation = Animation.WholeSheet; + public animation = Animation.WholeSheet; @property({ - type: CurveRange + type: CurveRange, }) - frameOverTime = new CurveRange(); + public frameOverTime = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startFrame = new CurveRange(); + public startFrame = new CurveRange(); @property - cycleCount = 0; + public cycleCount = 0; @property - _flipU = 0; + private _flipU = 0; - get flipU() { + get flipU () { return this._flipU; } - set flipU(val) { + set flipU (val) { console.error("particle texture animation's flipU is not supported!"); } @property - _flipV = 0; + private _flipV = 0; - get flipV() { + get flipV () { return this._flipV; } - set flipV(val) { + set flipV (val) { console.error("particle texture animation's flipV is not supported!"); } @property - _uvChannelMask = -1 + private _uvChannelMask = -1; - get uvChannelMask() { + get uvChannelMask () { return this._uvChannelMask; } - set uvChannelMask(val) { + set uvChannelMask (val) { console.error("particle texture animation's uvChannelMask is not supported!"); } @property - randomRow = false; + public randomRow = false; @property - rowIndex = 0; + public rowIndex = 0; - onInit(ps) { + private ps: ParticleSystemComponent | null = null; + + public onInit (ps: ParticleSystemComponent) { this.ps = ps; } - animate(p) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) / (this.numTilesX * this.numTilesY); - if (this.animation == Animation.WholeSheet) { - p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1); + public animate (p: Particle) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! / (this.numTilesX * this.numTilesY); + if (this.animation === Animation.WholeSheet) { + p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1); } - else if (this.animation == Animation.SingleRow) { - let rowLength = 1 / this.numTilesY; - if (this._randomRow) { - let f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1); - let startRow = Math.floor(Math.random() * this.numTilesY); - let from = startRow * rowLength; - let to = from + rowLength; + else if (this.animation === Animation.SingleRow) { + const rowLength = 1 / this.numTilesY; + if (this.randomRow) { + const f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1); + const startRow = Math.floor(Math.random() * this.numTilesY); + const from = startRow * rowLength; + const to = from + rowLength; p.frameIndex = lerp(from, to, f); } else { - let from = this.rowIndex * rowLength; - let to = from + rowLength; - p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1)); + const from = this.rowIndex * rowLength; + const to = from + rowLength; + p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1)); } } } diff --git a/cocos/3d/framework/particle/animator/velocity-overtime.js b/cocos/3d/framework/particle/animator/velocity-overtime.ts similarity index 51% rename from cocos/3d/framework/particle/animator/velocity-overtime.js rename to cocos/3d/framework/particle/animator/velocity-overtime.ts index 465aaecb84..90acc40c17 100644 --- a/cocos/3d/framework/particle/animator/velocity-overtime.js +++ b/cocos/3d/framework/particle/animator/velocity-overtime.ts @@ -1,57 +1,66 @@ -import { vec3, quat, pseudoRandom } from '../../../../core/vmath'; +import { vec3, quat, pseudoRandom, mat4 } from '../../../../core/vmath'; import { calculateTransform, Space } from '../particle-general-function'; import CurveRange from './curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import Particle from '../particle'; +// tslint:disable: max-line-length const VELOCITY_OVERTIME_RAND_OFFSET = 197866; @ccclass('cc.VelocityOvertimeModule') export default class VelocityOvertimeModule { @property - enable = false; + public enable = false; @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - speedModifier = new CurveRange(); + public speedModifier = new CurveRange(); - @property - space = Space.Local; + @property({ + type: Space, + }) + public space = Space.Local; - constructor() { + private rotation: quat; + private needTransform: boolean; + + constructor () { this.rotation = quat.create(); + this.speedModifier.constant = 1; + this.needTransform = false; } - update(space, worldTransform) { + public update (space: number, worldTransform: mat4) { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } - animate(p) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))); + public animate (p: Particle) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))); if (this.needTransform) { vec3.transformQuat(vel, vel, this.rotation); } vec3.add(p.animatedVelocity, p.animatedVelocity, vel); vec3.add(p.ultimateVelocity, p.velocity, p.animatedVelocity); - vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))); + vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))!); } } diff --git a/cocos/3d/framework/particle/emitter/shape-module.js b/cocos/3d/framework/particle/emitter/shape-module.ts similarity index 74% rename from cocos/3d/framework/particle/emitter/shape-module.js rename to cocos/3d/framework/particle/emitter/shape-module.ts index 2b7877a368..031824820d 100644 --- a/cocos/3d/framework/particle/emitter/shape-module.js +++ b/cocos/3d/framework/particle/emitter/shape-module.ts @@ -1,12 +1,14 @@ import { randomUnitVector, particleEmitZAxis, randomSortArray, randomSign, randomPointBetweenSphere, randomPointInCube, randomPointBetweenCircleAtFixedAngle, fixedAngleUnitVector2 } from '../particle-general-function'; -import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong } from '../../../../core/vmath'; +import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong, toRadian, toDegree } from '../../../../core/vmath'; import { Enum, Vec3 } from '../../../../core/value-types'; import CurveRange from '../animator/curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import ParticleSystemComponent from '../particle-system-component'; -let _intermediVec = vec3.create(0, 0, 0); -let _intermediArr = new Array(); +// tslint:disable: max-line-length +const _intermediVec = vec3.create(0, 0, 0); +const _intermediArr = new Array(); const _unitBoxExtent = vec3.create(0.5, 0.5, 0.5); const ShapeType = Enum({ @@ -14,126 +16,162 @@ const ShapeType = Enum({ Circle: 1, Cone: 2, Sphere: 3, - Hemisphere: 4 + Hemisphere: 4, }); const EmitLocation = Enum({ Base: 0, Edge: 1, Shell: 2, - Volume: 3 + Volume: 3, }); const ArcMode = Enum({ Random: 0, Loop: 1, - PingPong: 2 + PingPong: 2, }); @ccclass('cc.ShapeModule') export default class ShapeModule { @property - enable = false; + public enable = false; + + @property({ + type: ShapeType, + }) + public shapeType = ShapeType.Box; + + @property({ + type: EmitLocation, + }) + public emitFrom = EmitLocation.Volume; @property - shapeType = ShapeType.Box; + private _position = new Vec3(0, 0, 0); @property - emitFrom = EmitLocation.Base; - - @property - _position = new Vec3(0, 0, 0); - - get position() { + get position () { return this._position; } - set position(val) { + set position (val) { this._position = val; this.constructMat(); } @property - _rotation = new Vec3(0, 0, 0); + private _rotation = new Vec3(0, 0, 0); - get rotation() { + @property + get rotation () { return this._rotation; } - set rotation(val) { + set rotation (val) { this._rotation = val; this.constructMat(); } @property - _scale = new Vec3(0, 0, 0); + private _scale = new Vec3(1, 1, 1); - get scale() { + @property + get scale () { return this._scale; } - set scale(val) { + set scale (val) { this._scale = val; this.constructMat(); } @property - alignToDirection = false; + public alignToDirection = false; @property - randomDirectionAmount = 0; + public randomDirectionAmount = 0; @property - sphericalDirectionAmount = 0; + public sphericalDirectionAmount = 0; @property - randomPositionAmount = 0; + public randomPositionAmount = 0; @property - radius = 0; + public radius = 1; @property - radiusThickness = 1; + public radiusThickness = 1; @property - arc = 0; + private _arc = toRadian(360); @property - arcMode = ArcMode.Random; - - @property - arcSpread = 0; - - @property({ - type: CurveRange - }) - arcSpeed = new CurveRange(); - - @property - angle = 0; - - @property - length = 0; - - @property - boxThickness = new Vec3(0, 0, 0); - - constructor() { - this.mat = mat4.create(); - this.quat = quat.create(); + get arc () { + return toDegree(this._arc); } - onInit(ps) { + set arc (val) { + this._arc = toRadian(val); + } + + @property({ + type: ArcMode, + }) + public arcMode = ArcMode.Random; + + @property + public arcSpread = 0; + + @property({ + type: CurveRange, + }) + public arcSpeed = new CurveRange(); + + @property + private _angle = toRadian(25); + + @property + get angle () { + return toDegree(this._angle); + } + + set angle (val) { + this._angle = toRadian(val); + } + + @property + public length = 0; + + @property + public boxThickness = new Vec3(0, 0, 0); + + private mat: mat4; + private quat: quat; + private particleSystem: ParticleSystemComponent | null; + private lastTime: number; + private totalAngle: number; + + constructor () { + this.mat = mat4.create(); + this.quat = quat.create(); + this.particleSystem = null; + this.lastTime = 0; + this.totalAngle = 0; + } + + public onInit (ps: ParticleSystemComponent) { this.constructMat(); this.particleSystem = ps; this.lastTime = ps._time; this.totalAngle = 0; } - constructMat() { + private constructMat () { quat.fromEuler(this.quat, this._rotation.x, this._rotation.y, this._rotation.z); mat4.fromRTS(this.mat, this.quat, this._position, this._scale); } - emit(p) { + public emit (p) { switch (this.shapeType) { case ShapeType.Box: boxEmit(this.emitFrom, this.boxThickness, p.position, p.velocity); @@ -142,7 +180,7 @@ export default class ShapeModule { circleEmit(this.radius, this.radiusThickness, this.generateArcAngle(), p.position, p.velocity); break; case ShapeType.Cone: - coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this.angle, this.length, p.position, p.velocity); + coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this._angle, this.length, p.position, p.velocity); break; case ShapeType.Sphere: sphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity); @@ -161,31 +199,31 @@ export default class ShapeModule { vec3.transformQuat(p.velocity, p.velocity, this.quat); vec3.transformMat4(p.position, p.position, this.mat); if (this.sphericalDirectionAmount > 0) { - let sphericalVel = vec3.normalize(_intermediVec, p.position); + const sphericalVel = vec3.normalize(_intermediVec, p.position); vec3.lerp(p.velocity, p.velocity, sphericalVel, this.sphericalDirectionAmount); } - this.lastTime = this.particleSystem._time; + this.lastTime = this.particleSystem!._time; } - generateArcAngle() { + private generateArcAngle () { if (this.arcMode === ArcMode.Random) { - return randomRange(0, this.arc); + return randomRange(0, this._arc); } - let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem._time) * (this.particleSystem._time - this.lastTime); + let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem!._time, 1)! * (this.particleSystem!._time - this.lastTime); this.totalAngle = angle; if (this.arcSpread !== 0) { - angle = Math.floor(angle / (this.arc * this.arcSpread)) * this.arc * this.arcSpread; + angle = Math.floor(angle / (this._arc * this.arcSpread)) * this._arc * this.arcSpread; } switch (this.arcMode) { case ArcMode.Loop: - return repeat(angle, this.arc); + return repeat(angle, this._arc); case ArcMode.PingPong: - return pingPong(angle, this.arc); + return pingPong(angle, this._arc); } } } -function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) { +function sphereEmit (emitFrom, radius, radiusThickness, pos, dir) { switch (emitFrom) { case EmitLocation.Volume: randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); @@ -202,7 +240,7 @@ function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) { } } -function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) { +function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) { switch (emitFrom) { case EmitLocation.Volume: randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); @@ -225,7 +263,7 @@ function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) { } } -function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) { +function coneEmit (emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) { switch (emitFrom) { case EmitLocation.Base: randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); @@ -255,7 +293,7 @@ function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, } } -function boxEmit(emitFrom, boxThickness, pos, dir) { +function boxEmit (emitFrom, boxThickness, pos, dir) { switch (emitFrom) { case EmitLocation.Volume: randomPointInCube(pos, _unitBoxExtent); @@ -285,12 +323,12 @@ function boxEmit(emitFrom, boxThickness, pos, dir) { vec3.copy(dir, particleEmitZAxis); } -function circleEmit(radius, radiusThickness, theta, pos, dir) { +function circleEmit (radius, radiusThickness, theta, pos, dir) { randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); vec3.normalize(dir, pos); } -function applyBoxThickness(pos, thickness) { +function applyBoxThickness (pos, thickness) { if (thickness.x > 0) { pos[0] += 0.5 * randomRange(-thickness.x, thickness.x); pos[0] = clamp(pos[0], -0.5, 0.5); diff --git a/cocos/3d/framework/particle/particle-general-function.js b/cocos/3d/framework/particle/particle-general-function.ts similarity index 63% rename from cocos/3d/framework/particle/particle-general-function.js rename to cocos/3d/framework/particle/particle-general-function.ts index 06076406e8..adc6ae69f9 100644 --- a/cocos/3d/framework/particle/particle-general-function.js +++ b/cocos/3d/framework/particle/particle-general-function.ts @@ -7,10 +7,10 @@ export const particleEmitZAxis = vec3.create(0, 0, -1); export const Space = Enum({ World: 0, Local: 1, - Custom: 2 + Custom: 2, }); -export function calculateTransform(systemSpace, moduleSpace, worldTransform, outQuat) { +export function calculateTransform (systemSpace, moduleSpace, worldTransform, outQuat) { if (moduleSpace !== systemSpace) { if (systemSpace === 'world') { mat4.getRotation(outQuat, worldTransform); @@ -27,67 +27,70 @@ export function calculateTransform(systemSpace, moduleSpace, worldTransform, out } } -export function fixedAngleUnitVector2(out, theta) { +export function fixedAngleUnitVector2 (out, theta) { vec2.set(out, Math.cos(theta), Math.sin(theta)); } -export function randomUnitVector2(out) { - let a = randomRange(0, 2 * Math.PI); - let x = Math.cos(a); - let y = Math.sin(a); +export function randomUnitVector2 (out) { + const a = randomRange(0, 2 * Math.PI); + const x = Math.cos(a); + const y = Math.sin(a); vec2.set(out, x, y); } -export function randomUnitVector(out) { - let z = randomRange(-1, 1); - let a = randomRange(0, 2 * Math.PI); - let r = Math.sqrt(1 - z * z); - let x = r * Math.cos(a); - let y = r * Math.sin(a); +export function randomUnitVector (out) { + const z = randomRange(-1, 1); + const a = randomRange(0, 2 * Math.PI); + const r = Math.sqrt(1 - z * z); + const x = r * Math.cos(a); + const y = r * Math.sin(a); vec3.set(out, x, y, z); } -export function randomPointInUnitSphere(out) { +export function randomPointInUnitSphere (out) { randomUnitVector(out); vec3.scale(out, out, random()); } -export function randomPointBetweenSphere(out, minRadius, maxRadius) { +export function randomPointBetweenSphere (out, minRadius, maxRadius) { randomUnitVector(out); vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointInUnitCircle(out) { +export function randomPointInUnitCircle (out) { randomUnitVector2(out); + out.z = 0; vec3.scale(out, out, random()); } -export function randomPointBetweenCircle(out, minRadius, maxRadius) { +export function randomPointBetweenCircle (out, minRadius, maxRadius) { randomUnitVector2(out); + out.z = 0; vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointBetweenCircleAtFixedAngle(out, minRadius, maxRadius, theta) { +export function randomPointBetweenCircleAtFixedAngle (out, minRadius, maxRadius, theta) { fixedAngleUnitVector2(out, theta); + out.z = 0; vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointInCube(out, extents) { +export function randomPointInCube (out, extents) { vec3.set(out, randomRange(-extents.x, extents.x), randomRange(-extents.y, extents.y), randomRange(-extents.z, extents.z)); } -export function randomPointBetweenCube(out, minBox, maxBox) { +export function randomPointBetweenCube (out, minBox, maxBox) { const subscript = ['x', 'y', 'z']; - let edge = randomRangeInt(0, 3); + const edge = randomRangeInt(0, 3); for (let i = 0; i < 3; i++) { if (i === edge) { out[subscript[i]] = randomRange(-maxBox[subscript[i]], maxBox[subscript[i]]); continue; } - let x = random() * 2 - 1; + const x = random() * 2 - 1; if (x < 0) { out[subscript[i]] = -minBox[subscript[i]] + x * (maxBox[subscript[i]] - minBox[subscript[i]]); } @@ -98,16 +101,16 @@ export function randomPointBetweenCube(out, minBox, maxBox) { } // Fisher–Yates shuffle -export function randomSortArray(arr) { +export function randomSortArray (arr) { for (let i = 0; i < arr.length; i++) { - let transpose = i + randomRangeInt(0, arr.length - i); - let val = arr[transpose]; + const transpose = i + randomRangeInt(0, arr.length - i); + const val = arr[transpose]; arr[transpose] = arr[i]; arr[i] = val; } } -export function randomSign() { +export function randomSign () { let sgn = randomRange(-1, 1); sgn === 0 ? sgn++ : sgn; return sign(sgn); diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.ts similarity index 57% rename from cocos/3d/framework/particle/particle-system-component.js rename to cocos/3d/framework/particle/particle-system-component.ts index 91e3799e19..b4092697d7 100644 --- a/cocos/3d/framework/particle/particle-system-component.js +++ b/cocos/3d/framework/particle/particle-system-component.ts @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import Component from '../../../components/CCComponent'; +import { Component } from '../../../components/component'; import { vec3, vec2, mat4, quat, randomRangeInt, pseudoRandom } from '../../../core/vmath'; import CurveRange from './animator/curve-range'; import GradientRange from './animator/gradient-range'; @@ -18,7 +18,7 @@ import { particleEmitZAxis, Space } from './particle-general-function'; import { INT_MAX } from '../../../core/vmath/bits'; import { ccclass, executionOrder, executeInEditMode, property, requireComponent, menu } from '../../../core/data/class-decorator'; -let _world_mat = mat4.create(); +const _world_mat = mat4.create(); @ccclass('cc.ParticleSystemComponent') @menu('Components/ParticleSystemComponent') @@ -28,157 +28,172 @@ let _world_mat = mat4.create(); export default class ParticleSystemComponent extends Component { @property - capacity = 2000; + public capacity = 2000; @property({ - type:GradientRange + type: GradientRange, }) - startColor = new GradientRange(); + public startColor = new GradientRange(); @property({ - type: CurveRange + type: CurveRange, }) - startSize = new CurveRange(); + public startSize = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startSpeed = new CurveRange(); + public startSpeed = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startRotation = new CurveRange(); + public startRotation = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startDelay = new CurveRange(); + public startDelay = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startLifetime = new CurveRange(); + public startLifetime = new CurveRange(); @property - duration = 5.0; + public duration = 5.0; @property - loop = true; + public loop = true; @property - _prewarm = false; + private _prewarm = false; @property - get prewarm() { + get prewarm () { return this._prewarm; } - set prewarm(val) { - if (val === true && this._loop === false) { + set prewarm (val) { + if (val === true && this.loop === false) { // console.warn('prewarm only works if loop is also enabled.'); } this._prewarm = val; } @property - _simulationSpace = Space.Local; + private _simulationSpace = Space.Local; @property({ - type: Space + type: Space, }) - get simulationSpace() { + get simulationSpace () { return this._simulationSpace; } - set simulationSpace(val) { - if (val === Space.World) { - this._renderer._material.define('USE_WORLD_SPACE', true); - } else { - this._renderer._material.define('USE_WORLD_SPACE', false); + set simulationSpace (val) { + if (val !== this._simulationSpace) { + this._simulationSpace = val; + this.renderer!._updateMaterialParams(); } - this._simulationSpace = val; } @property - simulationSpeed = 1.0; + public simulationSpeed = 1.0; @property - playOnAwake = false; + public playOnAwake = true; @property({ - type: CurveRange + type: CurveRange, }) - gravityModifier = new CurveRange(); + public gravityModifier = new CurveRange(); // emission module @property({ - type: CurveRange + type: CurveRange, }) - rateOverTime = new CurveRange(); + public rateOverTime = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - rateOverDistance = new CurveRange(); + public rateOverDistance = new CurveRange(); @property({ - type: [Burst] + type: [Burst], }) - bursts = new Array(); + public bursts = new Array(); // color over lifetime module @property({ - type: ColorOverLifetimeModule + type: ColorOverLifetimeModule, }) - colorOverLifetimeModule = new ColorOverLifetimeModule(); + public colorOverLifetimeModule = new ColorOverLifetimeModule(); // shpae module @property({ - type: ShapeModule + type: ShapeModule, }) - shapeModule = new ShapeModule(); - - // particle system renderer - @property({ - type: ParticleSystemRenderer - }) - renderer = null; + public shapeModule = new ShapeModule(); // size over lifetime module @property({ - type: SizeOvertimeModule + type: SizeOvertimeModule, }) - sizeOvertimeModule = new SizeOvertimeModule(); + public sizeOvertimeModule = new SizeOvertimeModule(); @property({ - type: VelocityOvertimeModule + type: VelocityOvertimeModule, }) - velocityOvertimeModule = new VelocityOvertimeModule(); + public velocityOvertimeModule = new VelocityOvertimeModule(); @property({ - type: ForceOvertimeModule + type: ForceOvertimeModule, }) - forceOvertimeModule = new ForceOvertimeModule(); + public forceOvertimeModule = new ForceOvertimeModule(); @property({ - type: LimitVelocityOvertimeModule + type: LimitVelocityOvertimeModule, }) - limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); + public limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); @property({ - type: RotationOvertimeModule + type: RotationOvertimeModule, }) - rotationOvertimeModule = new RotationOvertimeModule(); + public rotationOvertimeModule = new RotationOvertimeModule(); @property({ - type: TextureAnimationModule + type: TextureAnimationModule, }) - textureAnimationModule = new TextureAnimationModule(); + public textureAnimationModule = new TextureAnimationModule(); - constructor() { + // particle system renderer + private renderer: ParticleSystemRenderer | null; + private _isPlaying: boolean; + private _isPaused: boolean; + private _isStopped: boolean; + private _isEmitting: boolean; + + private _time: number; // playback position in seconds. + private _emitRateTimeCounter: number; + private _emitRateDistanceCounter: number; + private _oldWPos: vec3; + private _curWPos: vec3; + + private _customData1: vec2; + private _customData2: vec2; + + private _subEmitters: any[]; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'} + + constructor () { super(); + this.rateOverTime.constant = 10; + this.startLifetime.constant = 5; + this.startSize.constant = 1; + this.startSpeed.constant = 1; + // internal status this._isPlaying = false; this._isPaused = false; @@ -195,9 +210,10 @@ export default class ParticleSystemComponent extends Component { this._customData2 = vec2.create(0, 0); this._subEmitters = []; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'} + this.renderer = null; } - onLoad() { + private onLoad () { // HACK, TODO this.renderer = this.getComponent(ParticleSystemRenderer); this.renderer.onInit(); @@ -210,17 +226,17 @@ export default class ParticleSystemComponent extends Component { // this._system.add(this); } - onDestroy() { + private onDestroy () { // this._system.remove(this); } - onEnable() { - if (this._playOnAwake) { + private onEnable () { + if (this.playOnAwake) { this.play(); } } - onDisable() { + private onDisable () { } @@ -229,7 +245,7 @@ export default class ParticleSystemComponent extends Component { // } - play() { + public play () { if (this._isPaused) { this._isPaused = false; } @@ -249,7 +265,7 @@ export default class ParticleSystemComponent extends Component { } } - pause() { + public pause () { if (this._isStopped) { console.warn('pause(): particle system is already stopped.'); return; @@ -261,7 +277,7 @@ export default class ParticleSystemComponent extends Component { this._isPaused = true; } - stop() { + public stop () { if (this._isPlaying) { this._isPlaying = false; } @@ -278,21 +294,21 @@ export default class ParticleSystemComponent extends Component { } // remove all particles from current particle system. - clear() { - this._particles.reset(); - this._renderer._model.clear(); + public clear () { + this.renderer!.clear(); } - emit(count, emitParams = null) { + private emit (count, emitParams = null) { if (emitParams !== null) { // TODO: } for (let i = 0; i < count; ++i) { - let particle = this.renderer._getFreeParticle(); - if (particle === null) + const particle = this.renderer!._getFreeParticle(); + if (particle === null) { return; - let rand = pseudoRandom(randomRangeInt(0, INT_MAX)); + } + const rand = pseudoRandom(randomRangeInt(0, INT_MAX)); if (this.shapeModule.enable) { this.shapeModule.emit(particle); @@ -307,13 +323,12 @@ export default class ParticleSystemComponent extends Component { switch (this._simulationSpace) { case Space.Local: break; - case Space.World: { + case Space.World: this.node.getWorldMatrix(_world_mat); vec3.transformMat4(particle.position, particle.position, _world_mat); - let worldRot = quat.create(); + const worldRot = quat.create(); this.node.getWorldRotation(worldRot); vec3.transformQuat(particle.velocity, particle.velocity, worldRot); - } break; case Space.Custom: // TODO: @@ -337,88 +352,28 @@ export default class ParticleSystemComponent extends Component { particle.randomSeed = randomRangeInt(0, 233280); - this.renderer._setNewParticle(particle); + this.renderer!._setNewParticle(particle); } // end of particles forLoop. } - // simulation, update particles. - _updateParticles(dt) { - this._entity.getWorldMatrix(_world_mat); - if (this._velocityOvertimeModule.enable) { - this._velocityOvertimeModule.update(this._simulationSpace, _world_mat); - } - if (this._forceOvertimeModule.enable) { - this._forceOvertimeModule.update(this._simulationSpace, _world_mat); - } - for (let i = 0; i < this._particles.length; ++i) { - let p = this._particles.data[i]; - p.remainingLifetime -= dt; - vec3.set(p.animatedVelocity, 0, 0, 0); - - if (p.remainingLifetime < 0.0) { - // subEmitter - // if (this._subEmitters.length > 0) { - // for (let idx = 0; idx < this._subEmitters.length; ++idx) { - // let subEmitter = this._subEmitters[idx]; - // if (subEmitter.type === 'death') { - // vec3.copy(subEmitter.emitter.entity.lpos, p.position); - // subEmitter.emitter.play(); - // } - // } - // } - - this._particles.remove(i); - --i; - continue; - } - - p.velocity.y -= this._gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity. - if (this._sizeOvertimeModule.enable) { - this._sizeOvertimeModule.animate(p); - } - if (this._colorOverLifetimeModule.enable) { - this._colorOverLifetimeModule.animate(p); - } - if (this._forceOvertimeModule.enable) { - this._forceOvertimeModule.animate(p, dt); - } - if (this._velocityOvertimeModule.enable) { - this._velocityOvertimeModule.animate(p); - } - else { - vec3.copy(p.ultimateVelocity, p.velocity); - } - if (this._limitVelocityOvertimeModule.enable) { - this._limitVelocityOvertimeModule.animate(p); - } - if (this._rotationOvertimeModule.enable) { - this._rotationOvertimeModule.animate(p, dt); - } - if (this._textureAnimationModule.enable) { - this._textureAnimationModule.animate(p); - } - vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. - } - } - // initialize particle system as though it had already completed a full cycle. - _prewarmSystem() { - this._startDelay.mode = 'constant'; // clear startDelay. - this._startDelay.constant = 0; - let dt = 1.0; // should use varying value? - let cnt = this.duration / dt; + private _prewarmSystem () { + this.startDelay.mode = 'constant'; // clear startDelay. + this.startDelay.constant = 0; + const dt = 1.0; // should use varying value? + const cnt = this.duration / dt; for (let i = 0; i < cnt; ++i) { this._time += dt; this._emit(dt); - this._renderer._updateParticles(dt); + this.renderer!._updateParticles(dt); } } // internal function - _emit(dt) { + private _emit (dt) { // emit particles. - let startDelay = this.startDelay.evaluate(); + const startDelay = this.startDelay.evaluate(); if (this._time > startDelay) { if (!this._isStopped) { this._isEmitting = true; @@ -436,30 +391,30 @@ export default class ParticleSystemComponent extends Component { // emit by rateOverTime this._emitRateTimeCounter += this.rateOverTime.evaluate(this._time / this.duration, 1) * dt; if (this._emitRateTimeCounter > 1 && this._isEmitting) { - let emitNum = Math.floor(this._emitRateTimeCounter); + const emitNum = Math.floor(this._emitRateTimeCounter); this._emitRateTimeCounter -= emitNum; this.emit(emitNum); } // emit by rateOverDistance this.node.getWorldPosition(this._curWPos); - let distance = vec3.distance(this._curWPos, this._oldWPos); + const distance = vec3.distance(this._curWPos, this._oldWPos); vec3.copy(this._oldWPos, this._curWPos); this._emitRateDistanceCounter += distance * this.rateOverDistance.evaluate(this._time / this.duration, 1); if (this._emitRateDistanceCounter > 1 && this._isEmitting) { - let emitNum = Math.floor(this._emitRateDistanceCounter); + const emitNum = Math.floor(this._emitRateDistanceCounter); this._emitRateDistanceCounter -= emitNum; this.emit(emitNum); } // bursts - for (let i = 0; i < this.bursts.length; ++i) { - this.bursts[i].update(this, dt); + for (const burst of this.bursts) { + burst.update(this, dt); } } } - update(dt) { - let scaledDeltaTime = dt * this.simulationSpeed; + private update (dt) { + const scaledDeltaTime = dt * this.simulationSpeed; if (this._isPlaying) { this._time += scaledDeltaTime; @@ -467,58 +422,58 @@ export default class ParticleSystemComponent extends Component { this._emit(scaledDeltaTime); // simulation, update particles. - this.renderer._updateParticles(scaledDeltaTime); + this.renderer!._updateParticles(scaledDeltaTime); // update render data - this.renderer._updateRenderData(); + this.renderer!._updateRenderData(); } } - addSubEmitter(subEmitter) { + private addSubEmitter (subEmitter) { this._subEmitters.push(subEmitter); } - removeSubEmitter(idx) { - this._subEmitters.remove(idx); + private removeSubEmitter (idx) { + this._subEmitters.splice(this._subEmitters.indexOf(idx), 1); } - addBurst(burst) { - this._bursts.push(burst); + private addBurst (burst) { + this.bursts.push(burst); } - removeBurst(idx) { - this._bursts.remove(idx); + private removeBurst (idx) { + this.bursts.splice(this.bursts.indexOf(idx), 1); } - getParticleCount() { - return this._particles.length; + public getParticleCount () { + return this.renderer!.getParticleCount(); } - setCustomData1(x, y) { + public setCustomData1 (x, y) { vec2.set(this._customData1, x, y); } - setCustomData2(x, y) { + public setCustomData2 (x, y) { vec2.set(this._customData2, x, y); } - get isPlaying() { + get isPlaying () { return this._isPlaying; } - get isPaused() { + get isPaused () { return this._isPaused; } - get isStopped() { + get isStopped () { return this._isStopped; } - get isEmitting() { + get isEmitting () { return this._isEmitting; } - get time() { + get time () { return this._time; } } diff --git a/cocos/3d/framework/particle/particle.js b/cocos/3d/framework/particle/particle.ts similarity index 53% rename from cocos/3d/framework/particle/particle.js rename to cocos/3d/framework/particle/particle.ts index 82228dc683..291ee35ea9 100644 --- a/cocos/3d/framework/particle/particle.js +++ b/cocos/3d/framework/particle/particle.ts @@ -1,7 +1,29 @@ import { vec3, color4 } from '../../../core/vmath'; +import { Color } from '../../../core/value-types'; +import ParticleSystemComponent from './particle-system-component'; export default class Particle { - constructor(particleSystem) { + public particleSystem: ParticleSystemComponent; + public position: vec3; + public velocity: vec3; + public animatedVelocity: vec3; + public ultimateVelocity: vec3; + public angularVelocity: vec3; + public axisOfRotation: vec3; + public rotation: vec3; + public startSize: vec3; + public size: vec3; + public startColor: Color; + public startColor01: color4; + public color = cc.Color.WHITE; + public randomSeed: number; // uint + public remainingLifetime: number; + public startLifetime: number; + public emitAccumulator0: number; + public emitAccumulator1: number; + public frameIndex: number; + + constructor (particleSystem: any) { this.particleSystem = particleSystem; this.position = vec3.create(0, 0, 0); this.velocity = vec3.create(0, 0, 0); diff --git a/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js index ad4cbe5525..e67a3cebea 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js +++ b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js @@ -1,5 +1,5 @@ import ParticleSystemRenderer from "./particle-system-renderer"; -import Material from "../../../assets/material"; +import { Material } from "../../../assets/material"; import Particle from "../particle"; import gfx from "../../../../renderer/gfx"; import { CurveUniform } from "../animator/optimized-curve"; diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-renderer.js deleted file mode 100644 index d4ee9e6787..0000000000 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.js +++ /dev/null @@ -1,296 +0,0 @@ -import { renderer } from '../../../../renderer'; -import { vec3, vec4, vec2, mat4 } from '../../../../core/vmath'; -import gfx from '../../../../renderer/gfx'; -import Material from '../../../assets/material'; -import { RecyclePool } from '../../../memop'; -import Particle from '../particle'; -import RenderableComponent from '../../renderable-component'; -import { Enum } from '../../../../core/value-types'; -import { property, ccclass, executeInEditMode } from '../../../../core/data/class-decorator'; -import { Space } from '../particle-general-function'; - -let _tempAttribUV = vec3.create(); -let _tempAttribUV0 = vec2.create(); -let _tempAttribColor = vec4.create(); -let _tempWorldTrans = mat4.create(); - -let _uvs = [ - 0, 0, // bottom-left - 1, 0, // bottom-right - 0, 1, // top-left - 1, 1 // top-right -]; - -const RenderMode = Enum({ - Billboard: 0, - StrecthedBillboard: 1, - HorizontalBillboard: 2, - VerticalBillboard: 3, - Mesh: 4 -}); - -@ccclass('cc.ParticleSystemRenderer') -@executeInEditMode -export default class ParticleSystemRenderer extends RenderableComponent { - - @property({ - type: RenderMode - }) - _renderMode = RenderMode.Billboard; - - @property({ - type: RenderMode - }) - get renderMode() { - return this._renderMode; - } - - set renderMode(val) { - if (this._renderMode === val) { - return; - } - this._renderMode = val; - this._updateMaterialParams(); - this._updateModel(); - } - - @property - _velocityScale = 1; - - @property - get velocityScale() { - return this._velocityScale; - } - - set velocityScale(val) { - this._velocityScale = val; - this._updateMaterialParams(); - this._updateModel(); - } - - @property - _lengthScale = 1; - - @property - get lengthScale() { - return this._lengthScale; - } - - set lengthScale(val) { - this._lengthScale = val; - this._updateMaterialParams(); - this._updateModel(); - } - - constructor() { - super(); - this._model = null; - - this.frameTile = cc.v2(1, 1); - this.attrs = new Array(5); - - this.device = cc.game._renderContext; - } - - onInit() { - this._vertAttrs = [ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3, index: gfx.ATTR_INDEX_POSITION }, - { name: gfx.ATTR_UV, type: gfx.ATTR_TYPE_FLOAT32, num: 3, index: gfx.ATTR_INDEX_UV }, - { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2, index: gfx.ATTR_INDEX_UV0 }, - { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, index: gfx.ATTR_INDEX_COLOR, normalize: true } - ]; - this.particleSystem = this.node.getComponent('cc.ParticleSystemComponent'); - this._particles = new RecyclePool(() => { - return new Particle(this); - }, this.particleSystem.capacity); - if (this.sharedMaterial == null) { - this.material = new Material(); - this.sharedMaterial.effectAsset = cc.EffectAsset.get('builtin-effect-particle-add'); - } - this._updateMaterialParams(); - this._updateModel(); - this.onEnable(); - } - - onEnable() { - if (this._model != null) - this._scene.addModel(this._model); - } - - onDisable() { - this._scene.removeModel(this._model); - } - - onDestroy() { - this._model.destroy(); - } - - _updateMaterialParams() { - if (!this.particleSystem) { - return; - } - if (this.particleSystem._simulationSpace === Space.World) { - this.sharedMaterial.define('USE_WORLD_SPACE', true); - } else { - this.sharedMaterial.define('USE_WORLD_SPACE', false); - } - - if (this._renderMode === RenderMode.Billboard) { - this.sharedMaterial.define('USE_BILLBOARD', true); - this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false); - this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false); - this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false); - } else if (this._renderMode === RenderMode.StrecthedBillboard) { - this.sharedMaterial.define('USE_BILLBOARD', false); - this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', true); - this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false); - this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false); - this.sharedMaterial.setProperty('velocityScale', this._velocityScale); - this.sharedMaterial.setProperty('lengthScale', this._lengthScale); - } else if (this._renderMode === RenderMode.HorizontalBillboard) { - this.sharedMaterial.define('USE_BILLBOARD', false); - this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false); - this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', true); - this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false); - } else if (this._renderMode === RenderMode.VerticalBillboard) { - this.sharedMaterial.define('USE_BILLBOARD', false); - this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false); - this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false); - this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', true); - } else { - console.warn(`particle system renderMode ${this._renderMode} not support.`); - } - - if (this.particleSystem.textureAnimationModule.enable) { - this.sharedMaterial.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY)); - } - else { - this.sharedMaterial.setProperty('frameTile', this.frameTile); - } - } - - _updateModel() { - if (!this.particleSystem) { - return; - } - if (this._model === null) { - this._model = new renderer.ParticleBatchModel(this.device, this.particleSystem.capacity, this._vertAttrs); - this._model.setParticleRenderer(this); - this._model.setNode(this.node); - } - this._model.setEffect(this.sharedMaterial ? this.sharedMaterial.effect : null); - if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') - return; - if (this._renderMode === RenderMode.StrecthedBillboard) { - this._model.enableStretchedBillboard(); - } else { - this._model.disableStretchedBillboard(); - } - } - - _getFreeParticle() { - if (this._particles.length >= this.particleSystem._capacity) - return null; - return this._particles.add(); - } - - _setNewParticle(p) { - - } - - _updateParticles(dt) { - this.node.getWorldMatrix(_tempWorldTrans); - if (this.particleSystem.velocityOvertimeModule.enable) { - this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); - } - if (this.particleSystem.forceOvertimeModule.enable) { - this.particleSystem.forceOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); - } - for (let i = 0; i < this._particles.length; ++i) { - let p = this._particles.data[i]; - p.remainingLifetime -= dt; - vec3.set(p.animatedVelocity, 0, 0, 0); - - if (p.remainingLifetime < 0.0) { - this._particles.remove(i); - --i; - continue; - } - - p.velocity.y -= this.particleSystem.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity. - if (this.particleSystem.sizeOvertimeModule.enable) { - this.particleSystem.sizeOvertimeModule.animate(p); - } - if (this.particleSystem.colorOverLifetimeModule.enable) { - this.particleSystem.colorOverLifetimeModule.animate(p); - } - if (this.particleSystem.forceOvertimeModule.enable) { - this.particleSystem.forceOvertimeModule.animate(p, dt); - } - if (this.particleSystem.velocityOvertimeModule.enable) { - this.particleSystem.velocityOvertimeModule.animate(p); - } - else { - vec3.copy(p.ultimateVelocity, p.velocity); - } - if (this.particleSystem.limitVelocityOvertimeModule.enable) { - this.particleSystem.limitVelocityOvertimeModule.animate(p); - } - if (this.particleSystem.rotationOvertimeModule.enable) { - this.particleSystem.rotationOvertimeModule.animate(p, dt); - } - if (this.particleSystem.textureAnimationModule.enable) { - this.particleSystem.textureAnimationModule.animate(p); - } - vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. - } - } - - // internal function - _updateRenderData() { - // update vertex buffer - let idx = 0; - let uploadVel = this._renderMode == RenderMode.StrecthedBillboard; - for (let i = 0; i < this._particles.length; ++i) { - let p = this._particles.data[i]; - let fi = 0; - if (this.particleSystem.textureAnimationModule.enable) { - fi = p.frameIndex; - } - idx = i * 4; - let attrNum = 0; - for (let j = 0; j < 4; ++j) { // four verts per particle. - attrNum = 0; - this.attrs[attrNum++] = p.position; - _tempAttribUV.x = _uvs[2 * j]; - _tempAttribUV.y = _uvs[2 * j + 1]; - _tempAttribUV.z = fi; - this.attrs[attrNum++] = _tempAttribUV; - _tempAttribUV0.x = p.size.x; - _tempAttribUV0.y = p.rotation.x; - this.attrs[attrNum++] = _tempAttribUV0; - this.attrs[attrNum++] = p.color._val; - - if (uploadVel) { - this.attrs[attrNum++] = p.ultimateVelocity; - } - - this._model.addParticleVertexData(idx++, this.attrs); - } - } - - // because we use index buffer, per particle index count = 6. - this._model.updateIA(this._particles.length * 6); - } - - updateShaderUniform() { - - } - - _onMaterialModified(index, material) { - this._updateMaterialParams(); - this._updateModel(); - } -} - -Object.assign(ParticleSystemRenderer, { uv: _uvs }); diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts new file mode 100644 index 0000000000..af4d8caf62 --- /dev/null +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -0,0 +1,339 @@ +import { ccclass, executeInEditMode, property } from '../../../../core/data/class-decorator'; +import { Enum, Vec2 } from '../../../../core/value-types'; +import { mat4, vec2, vec3, vec4 } from '../../../../core/vmath'; +import { GFXAttributeName, GFXFormat } from '../../../../gfx/define'; +import { IGFXInputAttribute } from '../../../../gfx/input-assembler'; +import * as renderer from '../../../../renderer'; +import gfx from '../../../../renderer/gfx'; +import ParticleBatchModel from '../../../../renderer/models/particle-batch-model'; +import { Material } from '../../../assets/material'; +import RecyclePool from '../../../memop/recycle-pool'; +import Particle from '../particle'; +import { RenderableComponent } from '../../renderable-component'; +import { Space } from '../particle-general-function'; +// import ParticleSystemComponent from '../particle-system-component'; + +const _tempAttribUV: vec3 = vec3.create(); +const _tempAttribUV0: vec2 = vec2.create(); +const _tempAttribColor: vec4 = vec4.create(); +const _tempWorldTrans: mat4 = mat4.create(); + +const _uvs = [ + 0, 0, // bottom-left + 1, 0, // bottom-right + 0, 1, // top-left + 1, 1, // top-right +]; + +const RenderMode = Enum({ + Billboard: 0, + StrecthedBillboard: 1, + HorizontalBillboard: 2, + VerticalBillboard: 3, + Mesh: 4, +}); + +const USE_WORLD_SPACE = 'USE_WORLD_SPACE'; +const USE_BILLBOARD = 'USE_BILLBOARD'; +const USE_STRETCHED_BILLBOARD = 'USE_STRETCHED_BILLBOARD'; +const USE_HORIZONTAL_BILLBOARD = 'USE_HORIZONTAL_BILLBOARD'; +const USE_VERTICAL_BILLBOARD = 'USE_VERTICAL_BILLBOARD'; + +@ccclass('cc.ParticleSystemRenderer') +@executeInEditMode +export default class ParticleSystemRenderer extends RenderableComponent { + + @property({ + type: RenderMode, + }) + public get renderMode () { + return this._renderMode; + } + + public set renderMode (val) { + if (this._renderMode === val) { + return; + } + this._renderMode = val; + this._updateMaterialParams(); + this._updateModel(); + } + + @property + public get velocityScale () { + return this._velocityScale; + } + + public set velocityScale (val) { + this._velocityScale = val; + this._updateMaterialParams(); + this._updateModel(); + } + + @property + public get lengthScale () { + return this._lengthScale; + } + + public set lengthScale (val) { + this._lengthScale = val; + this._updateMaterialParams(); + this._updateModel(); + } + + @property({ + type: RenderMode, + }) + private _renderMode = RenderMode.Billboard; + + @property + private _velocityScale = 1; + + @property + private _lengthScale = 1; + + private _defines: { [index: string]: boolean }; + private _model: ParticleBatchModel | null; + private frameTile: Vec2; + private attrs: any[]; + private _vertAttrs: IGFXInputAttribute[]; + private particleSystem: any; + private _particles: RecyclePool; + + constructor () { + super(); + this._model = null; + + this.frameTile = cc.v2(1, 1); + this.attrs = new Array(5); + this._vertAttrs = [ + { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, + { name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RGB32F }, + { name: GFXAttributeName.ATTR_TEX_COORD1, format: GFXFormat.RG32F }, + { name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGBA8, isNormalized: true }, + ]; + this._defines = { + USE_WORLD_SPACE: true, + USE_BILLBOARD: true, + USE_STRETCHED_BILLBOARD: false, + USE_HORIZONTAL_BILLBOARD: false, + USE_VERTICAL_BILLBOARD: false, + }; + } + + public onInit () { + this.particleSystem = this.node.getComponent('cc.ParticleSystemComponent'); + this._particles = new RecyclePool(() => { + return new Particle(this); + }, 16); + if (this.sharedMaterial == null) { + this.setMaterial(new Material(), 0, false); + this.sharedMaterial!._owner = this; + this.sharedMaterial!.effectName = 'builtin-effect-particle-add'; + } + this.onEnable(); + this._updateMaterialParams(); + this._updateModel(); + } + + public onEnable () { + if (!this.particleSystem) { + return; + } + if (this._model == null) { + this._model = this._getRenderScene().createModel(ParticleBatchModel, this.node) as ParticleBatchModel; + this._model.setCapacity(this.particleSystem.capacity); + this._model.setVertexAttributes(this._vertAttrs); + this._model.node = this.node; + this._model.enabled = this.enabledInHierarchy; + } + } + + public onDisable () { + this._getRenderScene().destroyModel(this._model!); + } + + public onDestroy () { + this._model!.destroy(); + } + + private clear () { + this._particles.reset(); + this._model!.destroy(); + } + + public _getFreeParticle (): Particle | null { + if (this._particles.length >= this.particleSystem._capacity) { + return null; + } + return this._particles.add(); + } + + public _setNewParticle (p: Particle) { + + } + + public _updateParticles (dt: number) { + this.node.getWorldMatrix(_tempWorldTrans); + if (this.particleSystem.velocityOvertimeModule.enable) { + this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); + } + if (this.particleSystem.forceOvertimeModule.enable) { + this.particleSystem.forceOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); + } + for (let i = 0; i < this._particles.length; ++i) { + const p = this._particles.data[i]; + p.remainingLifetime -= dt; + vec3.set(p.animatedVelocity, 0, 0, 0); + + if (p.remainingLifetime < 0.0) { + this._particles.removeAt(i); + --i; + continue; + } + + p.velocity.y -= this.particleSystem.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity. + if (this.particleSystem.sizeOvertimeModule.enable) { + this.particleSystem.sizeOvertimeModule.animate(p); + } + if (this.particleSystem.colorOverLifetimeModule.enable) { + this.particleSystem.colorOverLifetimeModule.animate(p); + } + if (this.particleSystem.forceOvertimeModule.enable) { + this.particleSystem.forceOvertimeModule.animate(p, dt); + } + if (this.particleSystem.velocityOvertimeModule.enable) { + this.particleSystem.velocityOvertimeModule.animate(p); + } else { + vec3.copy(p.ultimateVelocity, p.velocity); + } + if (this.particleSystem.limitVelocityOvertimeModule.enable) { + this.particleSystem.limitVelocityOvertimeModule.animate(p); + } + if (this.particleSystem.rotationOvertimeModule.enable) { + this.particleSystem.rotationOvertimeModule.animate(p, dt); + } + if (this.particleSystem.textureAnimationModule.enable) { + this.particleSystem.textureAnimationModule.animate(p); + } + vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. + } + } + + // internal function + public _updateRenderData () { + // update vertex buffer + let idx = 0; + const uploadVel = this._renderMode === RenderMode.StrecthedBillboard; + for (let i = 0; i < this._particles.length; ++i) { + const p = this._particles.data[i]; + let fi = 0; + if (this.particleSystem.textureAnimationModule.enable) { + fi = p.frameIndex; + } + idx = i * 4; + let attrNum = 0; + for (let j = 0; j < 4; ++j) { // four verts per particle. + attrNum = 0; + this.attrs[attrNum++] = p.position; + _tempAttribUV.x = _uvs[2 * j]; + _tempAttribUV.y = _uvs[2 * j + 1]; + _tempAttribUV.z = fi; + this.attrs[attrNum++] = _tempAttribUV; + _tempAttribUV0.x = p.size.x; + _tempAttribUV0.y = p.rotation.x; + this.attrs[attrNum++] = _tempAttribUV0; + this.attrs[attrNum++] = p.color._val; + + if (uploadVel) { + this.attrs[attrNum++] = p.ultimateVelocity; + } + + this._model!.addParticleVertexData(idx++, this.attrs); + } + } + + // because we use index buffer, per particle index count = 6. + this._model!.updateIA(this._particles.length * 6); + } + + public updateShaderUniform () { + + } + + public getParticleCount (): number { + return this._particles.length; + } + + public _onMaterialModified (index: number, material: Material) { + this._updateMaterialParams(); + this._updateModel(); + } + + public _onRebuildPSO (index: number, material: Material) { + if (this._model) { + this._model.setSubModelMaterial(0, material); + } + } + + private _updateMaterialParams () { + if (!this.particleSystem) { + return; + } + if (this.particleSystem._simulationSpace === Space.World) { + this._defines[USE_WORLD_SPACE] = true; + } else { + this._defines[USE_WORLD_SPACE] = false; + } + + if (this._renderMode === RenderMode.Billboard) { + this._defines[USE_BILLBOARD] = true; + this._defines[USE_STRETCHED_BILLBOARD] = false; + this._defines[USE_HORIZONTAL_BILLBOARD] = false; + this._defines[USE_VERTICAL_BILLBOARD] = false; + } else if (this._renderMode === RenderMode.StrecthedBillboard) { + this._defines[USE_BILLBOARD] = false; + this._defines[USE_STRETCHED_BILLBOARD] = true; + this._defines[USE_HORIZONTAL_BILLBOARD] = false; + this._defines[USE_VERTICAL_BILLBOARD] = false; + this.sharedMaterial!.setProperty('velocityScale', this._velocityScale); + this.sharedMaterial!.setProperty('lengthScale', this._lengthScale); + } else if (this._renderMode === RenderMode.HorizontalBillboard) { + this._defines[USE_BILLBOARD] = false; + this._defines[USE_STRETCHED_BILLBOARD] = false; + this._defines[USE_HORIZONTAL_BILLBOARD] = true; + this._defines[USE_VERTICAL_BILLBOARD] = false; + } else if (this._renderMode === RenderMode.VerticalBillboard) { + this._defines[USE_BILLBOARD] = false; + this._defines[USE_STRETCHED_BILLBOARD] = false; + this._defines[USE_HORIZONTAL_BILLBOARD] = false; + this._defines[USE_VERTICAL_BILLBOARD] = true; + } else { + console.warn(`particle system renderMode ${this._renderMode} not support.`); + } + this.getMaterial(0, CC_EDITOR)!.setDefines(this._defines); + + if (this.particleSystem.textureAnimationModule.enable) { + this.getMaterial(0, CC_EDITOR)!.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY)); + } else { + this.getMaterial(0, CC_EDITOR)!.setProperty('frameTile', this.frameTile); + } + } + + private _updateModel () { + if (!this.particleSystem) { + return; + } + this._model!.setSubModelMaterial(0, this.sharedMaterial ? this.sharedMaterial : null); + if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') { + return; + } + if (this._renderMode === RenderMode.StrecthedBillboard) { + this._model!.enableStretchedBillboard(); + } else { + this._model!.disableStretchedBillboard(); + } + } +} + +Object.assign(ParticleSystemRenderer, { uv: _uvs }); diff --git a/cocos/3d/framework/physics/body.ts b/cocos/3d/framework/physics/body.ts index f183d680f9..1f9a8c63aa 100644 --- a/cocos/3d/framework/physics/body.ts +++ b/cocos/3d/framework/physics/body.ts @@ -1,7 +1,7 @@ import CANNON from 'cannon'; import Vec3 from '../../../core/value-types/vec3'; import { vec3 } from '../../../core/vmath'; -import Node from '../../../scene-graph/node'; +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'; diff --git a/cocos/3d/framework/physics/collider-component.ts b/cocos/3d/framework/physics/collider-component.ts index 132ecd0508..25762d8f0e 100644 --- a/cocos/3d/framework/physics/collider-component.ts +++ b/cocos/3d/framework/physics/collider-component.ts @@ -4,7 +4,7 @@ import { executeInEditMode, executionOrder, menu, - property + property, } from '../../../core/data/class-decorator'; import Vec3 from '../../../core/value-types/vec3'; import { PhysicsBoxShape, PhysicsShape, PhysicsSphereShape } from './body'; @@ -17,37 +17,39 @@ export class ColliderComponentBase extends PhysicsBasedComponent { @property private _center: Vec3 = new cc.Vec3(0, 0, 0); - constructor(shape: PhysicsShape) { + constructor (shape: PhysicsShape) { super(); this._center = new Vec3(0, 0, 0); this._shape = shape; } - public get body() { + public get body () { return this._body; } - public onLoad() { + public onLoad () { super.onLoad(); this.center = this._center; } - public onEnable() { + public onEnable () { super.onEnable(); this._body!.addShape(this._shape); } - public onDisable() { + public onDisable () { super.onDisable(); this._body!.removeShape(this._shape); } - @property(Vec3) - get center() { + @property({ + type: Vec3, + }) + get center () { return this._center; } - set center(value: Vec3) { + set center (value: Vec3) { this._center = new Vec3(value.x, value.y, value.z); this._shape.center = value; } @@ -61,24 +63,26 @@ export class BoxColliderComponent extends ColliderComponentBase { @property private _size: Vec3 = new Vec3(0, 0, 0); - constructor() { + constructor () { super(new PhysicsBoxShape(new Vec3(0, 0, 0))); } - public onLoad() { + public onLoad () { super.onLoad(); this.size = this._size; } - @property(Vec3) - get size() { + @property({ + type: Vec3, + }) + get size () { return this._size; } /** * Note, shall not specify size with component 0 */ - set size(value) { + set size (value) { this._size = value; (this._shape as PhysicsBoxShape).size = this._size; if (this._body) { @@ -95,21 +99,21 @@ export class SphereColliderComponent extends ColliderComponentBase { @property private _radius: number = 0; - constructor() { + constructor () { super(new PhysicsSphereShape(0)); } - public onLoad() { + public onLoad () { super.onLoad(); this.radius = this._radius; } @property - get radius() { + get radius () { return this._radius; } - set radius(value) { + set radius (value) { this._radius = value; (this._shape as PhysicsSphereShape).radius = value; if (this._body) { diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts index 5cfadbeb12..dcde768e92 100644 --- a/cocos/3d/framework/physics/detail/physics-based-component.ts +++ b/cocos/3d/framework/physics/detail/physics-based-component.ts @@ -1,5 +1,5 @@ -import Component from '../../../../components/CCComponent'; +import { Component } from '../../../../components/component'; import { ccclass } from '../../../../core/data/class-decorator'; import { PhysicsBody } from '../body'; diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 37309ba6aa..3d4b7cc157 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -4,11 +4,17 @@ import { executeInEditMode, executionOrder, menu, - property + property, } from '../../../core/data/class-decorator'; import { PhysicsMaterial } from '../../assets/physics/material'; import { PhysicsBasedComponent } from './detail/physics-based-component'; +const NonRigidBodyProperties = { + mass: 0, + linearDamping: 0, + angularDamping: 0, +}; + @ccclass('cc.RigidBodyComponent') @executionOrder(100) @menu('Components/RigidBodyComponent') @@ -26,38 +32,40 @@ export class RigidBodyComponent extends PhysicsBasedComponent { @property private _angularDamping: number = NonRigidBodyProperties.angularDamping; - constructor() { + constructor () { super(); } - public get body() { + public get body () { return this._body; } - public onLoad() { + public onLoad () { super.onLoad(); } - public onEnable() { + public onEnable () { super.onEnable(); this.mass = this._mass; this.linearDamping = this._linearDamping; this.angularDamping = this._angularDamping; } - public onDisable() { + public onDisable () { super.onDisable(); this.mass = NonRigidBodyProperties.mass; this.linearDamping = NonRigidBodyProperties.linearDamping; this.angularDamping = NonRigidBodyProperties.angularDamping; } - @property(PhysicsMaterial) - get material() { + @property({ + type: PhysicsMaterial, + }) + get material () { return this._material; } - set material(value) { + set material (value) { this._material = value; if (this._body) { this._body.material = this._material; @@ -65,11 +73,11 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } @property - get mass() { + get mass () { return this._mass; } - set mass(value) { + set mass (value) { this._mass = value; if (this._body) { this._body.mass = value; @@ -77,11 +85,11 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } @property - get linearDamping() { + get linearDamping () { return this._linearDamping; } - set linearDamping(value) { + set linearDamping (value) { this._linearDamping = value; if (this._body) { this._body.linearDamping = value; @@ -89,26 +97,20 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } @property - get angularDamping() { + get angularDamping () { return this._angularDamping; } - set angularDamping(value) { + set angularDamping (value) { this._angularDamping = value; if (this._body) { this._body.angularDamping = value; } } - public pullTransform() { + public pullTransform () { if (this._body) { this._body.pullTransform(); } } } - -const NonRigidBodyProperties = { - mass: 0, - linearDamping: 0, - angularDamping: 0, -}; diff --git a/cocos/3d/framework/physics/world.ts b/cocos/3d/framework/physics/world.ts index 866d0eb09e..20d1a7aec3 100644 --- a/cocos/3d/framework/physics/world.ts +++ b/cocos/3d/framework/physics/world.ts @@ -46,8 +46,10 @@ export class PhysicsWorld { constructor() { this._defaultMaterial = new PhysicsMaterial(); - this._defaultContactMaterial = new ContactMaterial( - this._defaultMaterial, this._defaultMaterial, { friction: 0.3, restitution: 0.0 }); + const mtl = new PhysicsMaterial(); + mtl.friction = 0.3; + mtl.restitution = 0; + this._defaultContactMaterial = new ContactMaterial(this._defaultMaterial, mtl); this._cannonWorld = new CANNON.World(); setWrap(this._cannonWorld, this); diff --git a/cocos/3d/framework/render-system.js b/cocos/3d/framework/render-system.js deleted file mode 100644 index d51bd637bb..0000000000 --- a/cocos/3d/framework/render-system.js +++ /dev/null @@ -1,21 +0,0 @@ -import { renderer } from '../../renderer'; -export default class RenderSystem { - constructor () { - this._scene = new renderer.Scene(); - } - - init () { - - } - - update (dt) { - this._scene.tick(); - cc.game._renderer.render(this._scene); - this._scene.reset(); - if (cc.director._scene) cc.director._scene.resetHasChanged(); - } - - get scene () { - return this._scene; - } -} diff --git a/cocos/3d/framework/renderSystemActor.js b/cocos/3d/framework/renderSystemActor.js deleted file mode 100644 index eaf5ed65d5..0000000000 --- a/cocos/3d/framework/renderSystemActor.js +++ /dev/null @@ -1,41 +0,0 @@ -import Component from '../../components/CCComponent'; - -class RenderSystemActorListener { - constructor() { - this._renderSystem = null; - } - - onRenderableComponentCreated(comp) { - if(this._renderSystem === null) { - this._renderSystem = cc.director._renderSystem; - } - comp._system = this._renderSystem; - if (this._renderSystem) { - comp._scene = this._renderSystem.scene; - } - } -} - -let listener = new RenderSystemActorListener(); - -/** - * @class RenderSystemActor - * @extends Component - * RenderSystemActor is used to access Rendersystem - */ -export default class RenderSystemActor extends Component { - constructor() { - super(); - this._system = null; - this._scene = null; - listener.onRenderableComponentCreated(this); - } - - get renderSystem() { - return this._system; - } - - get scene() { - return this._scene; - } -} diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.ts similarity index 59% rename from cocos/3d/framework/renderable-component.js rename to cocos/3d/framework/renderable-component.ts index 744cdf8a6a..bbf38ac38c 100644 --- a/cocos/3d/framework/renderable-component.js +++ b/cocos/3d/framework/renderable-component.ts @@ -1,30 +1,31 @@ -//@ts-check -import RenderSystemActor from "./renderSystemActor"; +// @ts-check +import { Component } from '../../components/component'; import { _decorator } from '../../core/data/index'; -import Material from "../assets/material"; +import { Material } from '../assets/material'; const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') -export default class RenderableComponent extends RenderSystemActor { - /** - * @type {Material[]} - */ - @property([Material]) - _materials = []; +export class RenderableComponent extends Component { + @property({ type: [Material] }) + private _materials: Array = []; - constructor() { + constructor () { super(); } + public onLoad () { + this.sharedMaterials = this._materials.concat(); + } + @property({ type: [Material], - displayName: 'Materials' + displayName: 'Materials', }) - get sharedMaterials() { + get sharedMaterials () { return this._materials; } - set sharedMaterials(val) { + set sharedMaterials (val) { // 因为现在编辑器的做法是,当这个val传进来时,内部的materials已经被修改了。 // 我们没办法做到上面的最优化,只能先清理ModelComponent里所有Submodel的材质,再重新关联。 this._clearMaterials(); @@ -37,14 +38,14 @@ export default class RenderableComponent extends RenderSystemActor { * !#ch 模型材质 * @type {Material[]} */ - get materials() { + get materials () { for (let i = 0; i < this._materials.length; i++) { - this._materials[i] = this.getMaterial(i); + this._materials[i] = this.getMaterial(i)!; } return this._materials; } - set materials(val) { + set materials (val) { const dLen = val.length - this._materials.length; if (dLen > 0) { this._materials = this._materials.concat(new Array(dLen).fill(null)); @@ -62,51 +63,53 @@ export default class RenderableComponent extends RenderSystemActor { * !#ch 返回相对应序号的材质 * @param {Number} idx - Look for the material list number */ - getMaterial(idx) { - if (idx < 0 || idx >= this._materials.length || this._materials[idx] == null) { - return null; - } - - let instantiated = Material.getInstantiatedMaterial(this._materials[idx], this); + public getMaterial (idx: number, inEditor: boolean = false): Material | null { + const mat = this._materials[idx]; + if (!mat) { return null; } + const instantiated = Material.getInstantiatedMaterial(mat, this, inEditor); if (instantiated !== this._materials[idx]) { - this.setMaterial(instantiated, idx); + this.setMaterial(instantiated, idx, !inEditor); } - return this._materials[idx]; } - getSharedMaterial(idx) { + public getSharedMaterial (idx: number): Material | null { if (idx < 0 || idx >= this._materials.length) { return null; } return this._materials[idx]; } - get material() { + get material () { return this.getMaterial(0); } - get sharedMaterial() { - return this.getSharedMaterial(0); - } - - set material(val) { + set material (val) { if (this._materials.length === 1 && this._materials[0] === val) { return; } this.setMaterial(val, 0); } - setMaterial(material, index) { + get sharedMaterial () { + return this.getSharedMaterial(0); + } + + public setMaterial (material: Material | null, index: number, notify: boolean = true) { this._materials[index] = material; - this._onMaterialModified(index, material); + if (notify) { + this._onMaterialModified(index, material); + } } - _onMaterialModified(index, material) { + protected _onMaterialModified (index: number, material: Material | null) { } - _clearMaterials() { + protected _onRebuildPSO (index: number, material: Material | null) { + } + + protected _clearMaterials () { } } diff --git a/cocos/3d/framework/skeleton-instance.js b/cocos/3d/framework/skeleton-instance.js deleted file mode 100644 index 92ac204819..0000000000 --- a/cocos/3d/framework/skeleton-instance.js +++ /dev/null @@ -1,176 +0,0 @@ -// @ts-check -import { vec3, quat, mat4 } from '../../core/vmath'; -import { Node } from '../../scene-graph'; - -let _v3_tmp = vec3.create(); -let _qt_tmp = quat.create(); - -/** - * - * @param {cc.Node} node - * @param {(node: cc.Node)=>void} fx - */ -function _walk(node, fx) { - fx(node); - for (let i = 0; i < node.childrenCount; ++i) { - _walk(node.children[i], fx); - } -} - -export default class SkeletonInstance { - /** - * - * @param {import("../assets/skeleton").default} skeleton - */ - constructor(skeleton) { - this._skeleton = skeleton; - - /** - * @type {cc.Node[]} - */ - this._nodes = this._copyNodesForest(skeleton._nodes); - - /** - * @type {mat4[]} - */ - this._matrices = new Array(this._nodes.length); - for (let i = 0; i < this._nodes.length; ++i) { - this._matrices[i] = mat4.create(); - } - - this.updateMatrices(); - } - - /** - * - * @param {cc.Node[]} nodes - */ - _copyNodesForest(nodes) { - /** @type {cc.Node[]} */ - const newNodes = new Array(nodes.length); - nodes.forEach((node, index) => { - newNodes[index] = this._copyNode(node); - }); - nodes.forEach((node, index) => { - const newNode = newNodes[index]; - node.children.forEach(childNode => { - const childIndex = nodes.indexOf(childNode); - newNode.addChild(newNodes[childIndex]); - }); - }); - return newNodes; - } - - /** - * - * @param {cc.Node} node - */ - _copyNode(node) { - const newNode = new Node(node.name); - newNode.setPosition(node.getPosition()); - newNode.setScale(node.getScale()); - newNode.setRotation(node.getRotation()); - return newNode; - } - - blend(fromSkel, toSkel, alpha) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - let jointFrom = fromSkel._nodes[i]; - let jointTo = toSkel._nodes[i]; - - vec3.lerp(_v3_tmp, jointFrom._lpos, jointTo._lpos, alpha); - joint.setPosition(_v3_tmp); - - vec3.lerp(_v3_tmp, jointFrom._lscale, jointTo._lscale, alpha); - joint.setScale(_v3_tmp); - - quat.lerp(_qt_tmp, jointFrom._lrot, jointTo._lrot, alpha); - joint.setRotation(_qt_tmp); - } - } - - updateMatrices() { - for (let i = 0; i < this._nodes.length; ++i) { - this._nodes[i].getWorldMatrix(this._matrices[i]); - } - } - - /** - * - * @param {number} i Index of the node. - */ - getWorldMatrix(i) { - return this._matrices[i]; - } - - getJointIndex(jointName) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - if (joint.name == jointName) { - return i; - } - } - return -1; - } - - getJointIndexFromOrignalNodeIndex(index) { - return index; - } - - clone() { - return new SkeletonInstance(this._skeleton); - } - - createMask() { - return new SkeletonMask(this); - } -} - -export class SkeletonMask { - /** - * - * @param {SkeletonInstance} skeleton - */ - constructor(skeleton) { - /** - * @type {SkeletonInstance} - * */ - this._skeleton = skeleton; - - this._isMaskedArray = new Array(skeleton._nodes.length); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - this._isMaskedArray[i] = false; - } - } - - setMasked(jointIndex, masked = true) { - this._isMaskedArray[jointIndex] = masked; - } - - setMaskedRecursive(jointIndex, masked = true) { - if (jointIndex < 0 || jointIndex >= this._skeleton._nodes.length) { - return; - } - - this._isMaskedArray[jointIndex] = masked; - _walk(this._skeleton._nodes[0], joint => { - let idx = this._skeleton._nodes.indexOf(joint); - if (idx >= 0) { - this._isMaskedArray[idx] = masked; - } - }); - } - - isMasked(jointIndex) { - return this._isMaskedArray[jointIndex]; - } - - complement() { - let ret = new SkeletonMask(this._skeleton); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - ret._isMaskedArray[i] = !this._isMaskedArray[i]; - } - return ret; - } -} \ No newline at end of file diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js deleted file mode 100644 index c3c9349a69..0000000000 --- a/cocos/3d/framework/skinning-model-component.js +++ /dev/null @@ -1,253 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -// @ts-check -import { mat4 } from '../../core/vmath'; -import ModelComponent from './model-component'; -import { renderer } from '../../renderer/index'; -import { ccclass, property, executionOrder, menu,executeInEditMode } from '../../core/data/class-decorator'; -import utils from '../misc/utils'; -import Skeleton from '../assets/skeleton'; -import Node from '../../scene-graph/node'; - -/** - * @typedef {import("../framework/skeleton-instance").default} SkeletonInstance - */ -let _m4_tmp = mat4.create(); - -/** - * !#en The Skinning Model Component - * - * !#ch 皮肤模型组件 - * @class SkinningModelComponent - * @extends ModelComponent - */ -@ccclass('cc.SkinningModelComponent') -@executionOrder(100) -@executeInEditMode -@menu('Components/SkinningModelComponent') -export default class SkinningModelComponent extends ModelComponent { - /** - * @type {Skeleton} - */ - @property(Skeleton) - _skeleton = null; - - /** - * @type {Node} - */ - @property(Node) - _skinningRoot = null; - - constructor() { - super(); - - /** - * @type {Map} - */ - this._skinningTarget = null; - - /** - * @type {import("../../renderer/gfx/texture-2d").default} - */ - this._jointsTexture = null; - - /** - * @type {Float32Array} - */ - this._jointMatricesData = null; - } - - /** - * !#en The bone nodes - * - * !#ch 骨骼节点 - * @type {Skeleton} - */ - @property({type: Skeleton}) - get skeleton() { - return this._skeleton; - } - - set skeleton(val) { - this._skeleton = val; - } - - @property({type: Node}) - get skinningRoot() { - return this._skinningRoot; - } - - set skinningRoot(value) { - this._skinningRoot = value; - this._resetTarget(); - } - - onLoad() { - this._resetTarget(); - this._reInitJointsData(); - this._updateModels(); - this._updateCastShadow(); - this._updateReceiveShadow(); - } - - update(dt) { - this._updateMatrices(); - } - - - onDestroy() { - } - - _updateMatrices() { - if (!this._mesh || !this._skeleton || !this._skinningTarget) { - return; - } - - // /** @type {import("../assets/utils/gltf-utils").GltfMeshResource} */ - // const res = this._mesh.resource; - // const gltf = res.gltfAsset.description; - - // /** @type {Node[]} */ - // const nodes = []; - // gltf.nodes.forEach((gltfNode, index) => nodes[index] = createNode(gltfNode)); - // gltf.nodes.forEach((gltfNode, index) => { - // if (gltfNode.children) { - // const node = nodes[index]; - // gltfNode.children.forEach((childIndex) => { - // nodes[childIndex].setParent(node); - // }); - // } - // }); - - const cancelThisNoTransform = this.node.getWorldMatrix(); - mat4.invert(cancelThisNoTransform, cancelThisNoTransform); - - this._skeleton.joints.forEach((joint, index) => { - // const debugNode = nodes[this._skeleton._debugjoints[index]]; - // let wm = debugNode.getWorldMatrix(); - - const targetNode = this._skinningTarget.get(joint); - if (!targetNode) { - return; - } - const bindpose = this._skeleton.bindposes[index]; - - // 1. transform mesh to joint's local space - // 2. transform from joint' local space to world space - // 3. because it has been in world space, just cancel this mesh's original local-world transform - const jointMatrix = _m4_tmp; - mat4.multiply(jointMatrix, cancelThisNoTransform, targetNode.getWorldMatrix()); - mat4.multiply(jointMatrix, jointMatrix, bindpose); - this._setJointMatrix(index, jointMatrix); - }); - - this._commitJointsData(); - } - - _createModel() { - return new renderer.SkinningModel(); - } - - _updateModelParams() { - super._updateModelParams(); - for (let i = 0; i < this._models.length; ++i) - this._updateModelJointParam(this._models[i]); - } - - _reInitJointsData() { - if (this._jointsTexture) { - this._jointsTexture.destroy(); - } - - if (!this._skeleton) { - this._jointMatricesData = null; - return; - } - - if (cc.game._renderContext.allowFloatTexture()) { - this._jointsTexture = utils.createJointsTexture(this._skeleton); - this._jointMatricesData = new Float32Array(this._jointsTexture._width * this._jointsTexture._height * 4); - } else { - this._jointMatricesData = new Float32Array(this._skeleton.joints.length * 16); - } - } - - _commitJointsData() { - if (this._jointsTexture != null) { - this._jointsTexture.updateImage({ - image: this._jointMatricesData, - width: this._jointsTexture._width, - height: this._jointsTexture._height, - level: 0, - flipY: false, - premultiplyAlpha: false - }); - } - } - - _updateModelJointParam(model) { - if (this._jointsTexture != null) { - model.setJointsTexture(this._jointsTexture); - } else { - model.setJointsMatrixArray(this._jointMatricesData); - } - } - - _setJointMatrix(iMatrix, matrix) { - this._jointMatricesData[16 * iMatrix + 0] = matrix.m00; - this._jointMatricesData[16 * iMatrix + 1] = matrix.m01; - this._jointMatricesData[16 * iMatrix + 2] = matrix.m02; - this._jointMatricesData[16 * iMatrix + 3] = matrix.m03; - this._jointMatricesData[16 * iMatrix + 4] = matrix.m04; - this._jointMatricesData[16 * iMatrix + 5] = matrix.m05; - this._jointMatricesData[16 * iMatrix + 6] = matrix.m06; - this._jointMatricesData[16 * iMatrix + 7] = matrix.m07; - this._jointMatricesData[16 * iMatrix + 8] = matrix.m08; - this._jointMatricesData[16 * iMatrix + 9] = matrix.m09; - this._jointMatricesData[16 * iMatrix + 10] = matrix.m10; - this._jointMatricesData[16 * iMatrix + 11] = matrix.m11; - this._jointMatricesData[16 * iMatrix + 12] = matrix.m12; - this._jointMatricesData[16 * iMatrix + 13] = matrix.m13; - this._jointMatricesData[16 * iMatrix + 14] = matrix.m14; - this._jointMatricesData[16 * iMatrix + 15] = matrix.m15; - } - - _resetTarget() { - this._skinningTarget = new Map(); - if (!this._skeleton || !this._skinningRoot) { - return; - } - const rootNode = this._skinningRoot; - this._skeleton.joints.forEach(joint => { - const targetNode = rootNode.getChildByPath(joint); - if (!targetNode) { - console.warn(`Skinning target ${joint} not found in scene graph.`); - return; - } - this._skinningTarget.set(joint, targetNode); - }); - } -} diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts new file mode 100644 index 0000000000..a4f6e0bbea --- /dev/null +++ b/cocos/3d/framework/skinning-model-component.ts @@ -0,0 +1,178 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +// @ts-check +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { mat4 } from '../../core/vmath'; +import { GFXDevice, GFXFeature } from '../../gfx/device'; +import { SkinningModel, __FORCE_USE_UNIFORM_STORAGE__ } from '../../renderer/models/skinning-model'; +import { Node } from '../../scene-graph/node'; +import { Material } from '../assets/material'; +import Skeleton from '../assets/skeleton'; +import { ModelComponent } from './model-component'; + +const _m4_tmp = mat4.create(); + +type SkinningTarget = Map; + +/** + * !#en The Skinning Model Component + * !#ch 皮肤模型组件 + */ +@ccclass('cc.SkinningModelComponent') +@executionOrder(100) +@executeInEditMode +@menu('Components/SkinningModelComponent') +export default class SkinningModelComponent extends ModelComponent { + + /** + * !#en The bone nodes + * + * !#ch 骨骼节点 + */ + @property({type: Skeleton}) + get skeleton () { + return this._skeleton; + } + + set skeleton (val) { + this._skeleton = val; + this._resetSkinningTarget(); + this._bindSkeleton(); + } + + @property({type: Node}) + get skinningRoot () { + return this._skinningRoot; + } + + set skinningRoot (value) { + this._skinningRoot = value; + this._resetSkinningTarget(); + } + @property(Skeleton) + private _skeleton: Skeleton | null = null; + + @property(Node) + private _skinningRoot: Node | null = null; + + private _skinningTarget: SkinningTarget | null = null; + + constructor () { + super(); + } + + public onLoad () { + super.onLoad(); + this._resetSkinningTarget(); + } + + public update (dt) { + this._tryUpdateMatrices(); + } + + public onDestroy () { + } + + public _tryUpdateMatrices () { + if (!this._skeleton || !this._skinningTarget || !this._model) { + return; + } + + const skinningModel = this._model as SkinningModel; + const skeleton = this._skeleton; + const skinningTarget = this._skinningTarget; + + const cancelThisNodeTransform = this.node.getWorldMatrix(); + mat4.invert(cancelThisNodeTransform, cancelThisNodeTransform); + this._skeleton.joints.forEach((joint, index) => { + // If target joint doesn't exists in scene graph, skip it. + const targetNode = skinningTarget.get(joint); + if (!targetNode) { + return; + } + // 1. transform mesh to joint's local space + // 2. transform from joint' local space to world space + // 3. because it has been in world space, just cancel this mesh's original local-world transform + const bindpose = skeleton.bindposes[index]; + const jointMatrix = _m4_tmp; + mat4.multiply(jointMatrix, cancelThisNodeTransform, targetNode.getWorldMatrix()); + mat4.multiply(jointMatrix, jointMatrix, bindpose); + skinningModel.updateJointMatrix(index, jointMatrix); + }); + + skinningModel.commitJointMatrices(); + } + + public _createModel () { + return this._getRenderScene().createModel(SkinningModel, this.node); + } + + public _updateModelParams () { + // Should bind skeleton before super create pso + this._bindSkeleton(); + super._updateModelParams(); + } + + protected _onMaterialModified (index: number, material: Material) { + super._onMaterialModified(index, material); + + const device = _getGlobalDevice(); + const useJointTexture = !__FORCE_USE_UNIFORM_STORAGE__ && device !== null && device.hasFeature(GFXFeature.TEXTURE_FLOAT); + this.getMaterial(0, CC_EDITOR)!.setDefines({ + CC_USE_SKINNING: true, + CC_USE_JOINTS_TEXTURE: useJointTexture, + }); + } + + private _bindSkeleton () { + if (this._model && this._skeleton) { + (this._model as SkinningModel).bindSkeleton(this._skeleton); + } + } + + private _resetSkinningTarget () { + if (!this._skeleton || !this._skinningRoot) { + return; + } + + // Collect target to skin. + this._skinningTarget = new Map(); + const rootNode = this._skinningRoot; + this._skeleton.joints.forEach((joint) => { + const targetNode = rootNode.getChildByPath(joint); + if (!targetNode) { + console.warn(`Skinning target ${joint} not found in scene graph.`); + return; + } + this._skinningTarget!.set(joint, targetNode); + }); + } +} + +function _getGlobalDevice (): GFXDevice | null { + // @ts-ignore + return cc.director.root.device; +} diff --git a/cocos/3d/framework/skinning-model-system.js b/cocos/3d/framework/skinning-model-system.js deleted file mode 100644 index 25d4542bf1..0000000000 --- a/cocos/3d/framework/skinning-model-system.js +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import { System } from '../ecs'; -import { FixedArray } from '../memop'; -import { _decorator } from '../../core/data/index'; -const { ccclass, property } = _decorator; - -/** - * !#en Skinning Model Component Management System - * - * !#ch 皮肤模型管理系统 - * @class SkinningModelSystem - * @extends System - */ -@ccclass('cc.SkinningModelSystem') -export default class SkinningModelSystem extends System { - constructor() { - super(); - - this._comps = new FixedArray(200); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - add(comp) { - this._comps.push(comp); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - remove(comp) { - this._comps.fastRemove(this._comps.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._comps.length; ++i) { -// let comp = this._comps.data[i]; -// if (comp.enabled === false) { -// continue; -// } - -// comp._updateMatrices(); -// } -// } -} diff --git a/cocos/3d/framework/skybox-component.js b/cocos/3d/framework/skybox-component.js deleted file mode 100644 index ce398e6ca8..0000000000 --- a/cocos/3d/framework/skybox-component.js +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import { renderer } from '../../renderer/index'; -import { box } from '../primitive/index'; -import Material from '../assets/material'; -import { ccclass, property, menu, executeInEditMode } from '../../core/data/class-decorator'; -import TextureCube from '../assets/texture-cube'; -import Component from '../../components/CCComponent'; - -/** - * !#en The Skybox Component - * - * !#ch 天空盒组件 - * @class SkyboxComponent - * @extends Component - */ -@ccclass('cc.SkyboxComponent') -@menu('Components/SkyboxComponent') -@executeInEditMode -export default class SkyboxComponent extends Component { - - @property - _cubemap = null; - @property - _rgbeTexture = false; - - @property({ - type: TextureCube, - displayName: 'Cubemap' - }) - get cubemap() { - return this._cubemap; - } - - set cubemap(val) { - this._cubemap = val; - this._updateMaterialParams(); - } - - @property({ - type: Boolean, - displayName: 'RGBE Texture' - }) - set rgbeTexture(v) { - this._rgbeTexture = v; - this._updateMaterialParams(); - } - get rgbeTexture() { - return this._rgbeTexture; - } - - constructor() { - super(); - - this._model = new renderer.Model(); - this._attachedCamera = null; - } - - onLoad() { - this._model.setNode(this.node); - - let ia = renderer.createIA(cc.game._renderContext, box(2, 2, 2)); - this._model.setInputAssembler(ia); - - if (!this._material) { - this._material = new Material(); - let skyboxEffect = cc.EffectAsset.get('builtin-effect-skybox'); - if (skyboxEffect) this._material.effectAsset = skyboxEffect; - } - - this._updateMaterialParams(); - this._model.setEffect(this._material.effect); - } - - onEnable() { - if (this.node) { - let cameraComponent = this.getComponent(cc.CameraComponent); - if (cameraComponent && (cameraComponent._clearFlags & renderer.CLEAR_SKYBOX)) { - this._attachedCamera = cameraComponent._camera; - this._attachedCamera._clearModel = this._model; - } - } - } - - onDisable() { - if (this._attachedCamera) { - this._attachedCamera._clearModel = null; - this._attachedCamera = null; - } - } - - _updateMaterialParams() { - if (!this._material) return; - if (this._cubemap) this._material.setProperty('cubeMap', this._cubemap); - this._material.define('USE_RGBE_CUBEMAP', this._rgbeTexture); - } -} diff --git a/cocos/3d/framework/skybox-component.ts b/cocos/3d/framework/skybox-component.ts new file mode 100644 index 0000000000..45b316293a --- /dev/null +++ b/cocos/3d/framework/skybox-component.ts @@ -0,0 +1,106 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { Camera, Model } from '../../renderer'; +import { Material } from '../assets/material'; +import { Mesh } from '../assets/mesh'; +import { TextureCube } from '../assets/texture-cube'; +import { createMesh } from '../misc/utils'; +import { box } from '../primitive'; + +/** + * !#en The Skybox Component + * + * !#ch 天空盒组件 + * @class SkyboxComponent + * @extends Component + */ +@ccclass('cc.SkyboxComponent') +@menu('Components/SkyboxComponent') +@executeInEditMode +export default class SkyboxComponent extends Component { + + @property + protected _cubemap = null; + @property + protected _rgbeTexture = false; + + @property({ + type: TextureCube, + displayName: 'Cubemap', + }) + get cubemap () { + return this._cubemap; + } + + set cubemap (val) { + this._cubemap = val; + if (this._material) { this._material.setProperty('cubeMap', this._cubemap); } + } + + @property({ + type: Boolean, + displayName: 'RGBE Texture', + }) + set rgbeTexture (v) { + this._rgbeTexture = v; + if (this._material) { this._material.setDefines({ USE_RGBE_CUBEMAP: v }); } + } + get rgbeTexture () { + return this._rgbeTexture; + } + + protected _attachedCamera: Camera | null = null; + protected _model: Model | null = null; + protected _mesh: Mesh | null = null; + protected _material: Material | null = null; + + public onLoad () { + this._model = this._getRenderScene().createModel(Model, this.node); + this._mesh = createMesh(box({ width: 2, height: 2, length: 2 })); + this._material = new Material({ + effectName: 'builtin-effect-skybox', + defines: { USE_RGBE_CUBEMAP: this._rgbeTexture }, + }); + if (this._cubemap) { this._material.setProperty('cubeMap', this._cubemap); } + + const subMeshData = this._mesh.renderingMesh!.getSubmesh(0); + this._model.initSubModel(0, subMeshData!, this._material); + } + + public onEnable () { + if (this._model) { this._model.enabled = true; } + } + + public onDisable () { + if (this._model) { this._model.enabled = false; } + } + + public onDestroy () { + if (this._model) { this._model.destroy(); this._model = null; } + } +} diff --git a/cocos/3d/geom-utils/aabb.js b/cocos/3d/geom-utils/aabb.ts similarity index 64% rename from cocos/3d/geom-utils/aabb.js rename to cocos/3d/geom-utils/aabb.ts index 523d831776..d702c33402 100644 --- a/cocos/3d/geom-utils/aabb.js +++ b/cocos/3d/geom-utils/aabb.ts @@ -1,12 +1,12 @@ +import { mat3, mat4, vec3 } from '../../core/vmath'; import enums from './enums'; -import { vec3, mat3 } from '../../core/vmath'; -let _v3_tmp = vec3.create(); -let _v3_tmp2 = vec3.create(); -let _m3_tmp = mat3.create(); +const _v3_tmp = vec3.create(); +const _v3_tmp2 = vec3.create(); +const _m3_tmp = mat3.create(); // https://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/ -let transform_extent_m4 = function(out, extent, m4) { +const transform_extent_m4 = (out: vec3, extent: vec3, m4: mat4) => { _m3_tmp.m00 = Math.abs(m4.m00); _m3_tmp.m01 = Math.abs(m4.m01); _m3_tmp.m02 = Math.abs(m4.m02); _m3_tmp.m03 = Math.abs(m4.m04); _m3_tmp.m04 = Math.abs(m4.m05); _m3_tmp.m05 = Math.abs(m4.m06); _m3_tmp.m06 = Math.abs(m4.m08); _m3_tmp.m07 = Math.abs(m4.m09); _m3_tmp.m08 = Math.abs(m4.m10); @@ -14,34 +14,29 @@ let transform_extent_m4 = function(out, extent, m4) { }; export default class aabb { - constructor(px = 0, py = 0, pz = 0, w = 1, h = 1, l = 1) { - this._type = enums.SHAPE_AABB; - this.center = vec3.create(px, py, pz); - this.halfExtents = vec3.create(w, h, l); - } /** * create a new aabb * - * @param {number} px X coordinates for aabb's original point - * @param {number} py Y coordinates for aabb's original point - * @param {number} pz Z coordinates for aabb's original point - * @param {number} w the half of aabb width - * @param {number} h the half of aabb height - * @param {number} l the half of aabb length - * @return {aabb} + * @param px - X coordinates for aabb's original point + * @param py - Y coordinates for aabb's original point + * @param pz - Z coordinates for aabb's original point + * @param w - the half of aabb width + * @param h - the half of aabb height + * @param l - the half of aabb length + * @returns the resulting aabb */ - static create(px, py, pz, w, h, l) { + public static create (px?: number, py?: number, pz?: number, w?: number, h?: number, l?: number) { return new aabb(px, py, pz, w, h, l); } /** * clone a new aabb * - * @param {aabb} a the source aabb - * @return {aabb} + * @param a - the source aabb + * @returns the cloned aabb */ - static clone(a) { + public static clone (a: aabb) { return new aabb(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z); } @@ -53,7 +48,7 @@ export default class aabb { * @param {aabb} a the source aabb * @return {aabb} */ - static copy(out, a) { + public static copy (out, a) { vec3.copy(out.center, a.center); vec3.copy(out.halfExtents, a.halfExtents); @@ -63,17 +58,17 @@ export default class aabb { /** * create a new aabb from two corner points * - * @param {aabb} out the receiving aabb - * @param {vec3} minPos lower corner position of the aabb - * @param {vec3} maxPos upper corner position of the aabb - * @return {aabb} + * @param out - the receiving aabb + * @param minPos - lower corner position of the aabb + * @param maxPos - upper corner position of the aabb + * @returns the resulting aabb */ - static fromPoints(out, minPos, maxPos) { + public static fromPoints (out: aabb, minPos: vec3, maxPos: vec3) { vec3.scale(out.center, vec3.add(_v3_tmp, minPos, maxPos), 0.5); vec3.scale(out.halfExtents, vec3.sub(_v3_tmp2, maxPos, minPos), 0.5); return out; } - + /** * Set the components of a aabb to the given values * @@ -87,18 +82,27 @@ export default class aabb { * @return {aabb} out * @function */ - static set(out, px, py, pz, w, h, l) { + public static set (out, px, py, pz, w, h, l) { vec3.set(out.center, px, py, pz); vec3.set(out.halfExtents, w, h, l); return out; } + public center: vec3; + public halfExtents: vec3; + protected _type: number = enums.SHAPE_AABB; + + constructor (px = 0, py = 0, pz = 0, w = 1, h = 1, l = 1) { + this.center = vec3.create(px, py, pz); + this.halfExtents = vec3.create(w, h, l); + } + /** * Get the bounding points of this shape * @param {vec3} minPos * @param {vec3} maxPos */ - getBoundary(minPos, maxPos) { + public getBoundary (minPos, maxPos) { vec3.sub(minPos, this.center, this.halfExtents); vec3.add(maxPos, this.center, this.halfExtents); } @@ -111,9 +115,13 @@ export default class aabb { * @param {vec3} scale the scale part of the transform * @param {aabb} [out] the target shape */ - transform(m, pos, rot, scale, out) { - if (!out) out = this; + public transform (m, pos, rot, scale, out) { + if (!out) { out = this; } vec3.transformMat4(out.center, this.center, m); transform_extent_m4(out.halfExtents, this.halfExtents, m); } + + get type (){ + return this._type; + } } diff --git a/cocos/3d/geom-utils/curve.js b/cocos/3d/geom-utils/curve.ts similarity index 53% rename from cocos/3d/geom-utils/curve.js rename to cocos/3d/geom-utils/curve.ts index cbf3d1e342..0824fcf8d2 100644 --- a/cocos/3d/geom-utils/curve.js +++ b/cocos/3d/geom-utils/curve.ts @@ -9,70 +9,77 @@ const WrapMode = Enum({ Once: 1, Loop: 2, PingPong: 3, - ClampForever: 4 + ClampForever: 4, }); export class Keyframe { - time = 0; + public time = 0; - value = 0; + public value = 0; - inTangent = 0; + public inTangent = 0; - outTangent = 0; + public outTangent = 0; } CCClass.fastDefine('cc.Keyframe', Keyframe, { time: 0, value: 0, inTangent: 0, - outTangent: 0 + outTangent: 0, }); export class OptimizedKey { - constructor() { + public index: number; + public time: number; + public endTime: number; + public coefficient: Float32Array; + constructor () { this.index = -1; this.time = 0; this.endTime = 0; this.coefficient = new Float32Array(4); } - evaluate(T) { - let t = T - this.time; + public evaluate (T: number) { + const t = T - this.time; return evalOptCurve(t, this.coefficient); } } -export function evalOptCurve(t, coefs) { +export function evalOptCurve (t: number, coefs: Float32Array) { return (t * (t * (t * coefs[0] + coefs[1]) + coefs[2])) + coefs[3]; } export class AnimationCurve { - keyFrames = null; + public keyFrames: Keyframe[] | null; - preWrapMode = WrapMode.Default; + public preWrapMode: number = WrapMode.Default; - postWrapMode = WrapMode.Default; + public postWrapMode: number = WrapMode.Default; - constructor(keyFrames) { + private cachedKey: OptimizedKey; + + constructor (keyFrames: Keyframe[] | null = null) { this.keyFrames = keyFrames; this.cachedKey = new OptimizedKey(); } - addKey(keyFrame) { - if (this.keyFrames == null) + public addKey (keyFrame: Keyframe) { + if (this.keyFrames == null) { this.keyFrames = []; + } this.keyFrames.push(keyFrame); } - //cubic Hermite spline - evaluate_slow(time) { + // cubic Hermite spline + public evaluate_slow (time: number) { let wrappedTime = time; - let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; - let startTime = this.keyFrames[0].time; - let endTime = this.keyFrames[this.keyFrames.length - 1].time; + const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; + const startTime = this.keyFrames![0].time; + const endTime = this.keyFrames![this.keyFrames!.length - 1].time; switch (wrapMode) { case WrapMode.Loop: wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; @@ -85,43 +92,44 @@ export class AnimationCurve { break; } let preKFIndex = 0; - if (wrappedTime > this.keyFrames[0].time) { - if (wrappedTime >= this.keyFrames[this.keyFrames.length - 1].time) - preKFIndex = this.keyFrames.length - 2; + if (wrappedTime > this.keyFrames![0].time) { + if (wrappedTime >= this.keyFrames![this.keyFrames!.length - 1].time) { + preKFIndex = this.keyFrames!.length - 2; + } else { - for (let i = 0; i < this.keyFrames.length - 1; i++) { - if (wrappedTime >= this.keyFrames[0].time && wrappedTime <= this.keyFrames[i + 1].time) { + for (let i = 0; i < this.keyFrames!.length - 1; i++) { + if (wrappedTime >= this.keyFrames![0].time && wrappedTime <= this.keyFrames![i + 1].time) { preKFIndex = i; break; } } } } - let keyframe0 = this.keyFrames[preKFIndex]; - let keyframe1 = this.keyFrames[preKFIndex + 1]; + const keyframe0 = this.keyFrames![preKFIndex]; + const keyframe1 = this.keyFrames![preKFIndex + 1]; - let t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime); - let dt = keyframe1.time - keyframe0.time; + const t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime); + const dt = keyframe1.time - keyframe0.time; - let m0 = keyframe0.outTangent * dt; - let m1 = keyframe1.inTangent * dt; + const m0 = keyframe0.outTangent * dt; + const m1 = keyframe1.inTangent * dt; - let t2 = t * t; - let t3 = t2 * t; + const t2 = t * t; + const t3 = t2 * t; - let a = 2 * t3 - 3 * t2 + 1; - let b = t3 - 2 * t2 + t; - let c = t3 - t2; - let d = -2 * t3 + 3 * t2; + const a = 2 * t3 - 3 * t2 + 1; + const b = t3 - 2 * t2 + t; + const c = t3 - t2; + const d = -2 * t3 + 3 * t2; return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value; } - evaluate(time) { + public evaluate (time) { let wrappedTime = time; - let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; - let startTime = this.keyFrames[0].time; - let endTime = this.keyFrames[this.keyFrames.length - 1].time; + const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; + const startTime = this.keyFrames![0].time; + const endTime = this.keyFrames![this.keyFrames!.length - 1].time; switch (wrapMode) { case WrapMode.Loop: wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; @@ -136,9 +144,9 @@ export class AnimationCurve { if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) { return this.cachedKey.evaluate(wrappedTime); } else { - let leftIndex = this.findIndex(this.cachedKey, wrappedTime); + const leftIndex = this.findIndex(this.cachedKey, wrappedTime); let rightIndex = leftIndex + 1; - if (rightIndex == this.keyFrames.length) { + if (rightIndex === this.keyFrames!.length) { rightIndex -= 1; } this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex); @@ -146,18 +154,18 @@ export class AnimationCurve { } } - calcOptimizedKey(optKey, leftIndex, rightIndex) { - let lhs = this.keyFrames[leftIndex]; - let rhs = this.keyFrames[rightIndex]; + private calcOptimizedKey (optKey: OptimizedKey, leftIndex: number, rightIndex: number) { + const lhs = this.keyFrames![leftIndex]; + const rhs = this.keyFrames![rightIndex]; optKey.index = leftIndex; optKey.time = lhs.time; optKey.endTime = rhs.time; - let dx = rhs.time - lhs.time; - let dy = rhs.value - lhs.value; - let length = 1 / (dx * dx); - let d1 = lhs.outTangent * dx; - let d2 = rhs.inTangent * dx; + const dx = rhs.time - lhs.time; + const dy = rhs.value - lhs.value; + const length = 1 / (dx * dx); + const d1 = lhs.outTangent * dx; + const d2 = rhs.inTangent * dx; optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx; optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length; @@ -165,31 +173,31 @@ export class AnimationCurve { optKey.coefficient[3] = lhs.value; } - findIndex(optKey, t) { - let cachedIndex = optKey.index; + private findIndex (optKey: OptimizedKey, t: number) { + const cachedIndex = optKey.index; if (cachedIndex !== -1) { - let cachedTime = this.keyFrames[cachedIndex].time; + const cachedTime = this.keyFrames![cachedIndex].time; if (t > cachedTime) { for (let i = 0; i < LOOK_FORWARD; i++) { - let currIndex = cachedIndex + i; - if (currIndex + 1 < this.keyFrames.length && this.keyFrames[currIndex + 1].time > t) { + const currIndex = cachedIndex + i; + if (currIndex + 1 < this.keyFrames!.length && this.keyFrames![currIndex + 1].time > t) { return currIndex; } } } else { for (let i = 0; i < LOOK_FORWARD; i++) { - let currIndex = cachedIndex - i; - if (currIndex >= 0 && this.keyFrames[currIndex - 1].time <= t) { + const currIndex = cachedIndex - i; + if (currIndex >= 0 && this.keyFrames![currIndex - 1].time <= t) { return currIndex - 1; } } } } let left = 0; - let right = this.keyFrames.length; + let right = this.keyFrames!.length; let mid = parseInt((left + right) / 2); while (right - left > 1) { - if (this.keyFrames[mid].time >= t) { + if (this.keyFrames![mid].time >= t) { right = mid; } else { left = mid + 1; @@ -203,5 +211,5 @@ export class AnimationCurve { CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, { preWrapMode: WrapMode.Default, postWrapMode: WrapMode.Default, - keyFrames: [] + keyFrames: [], }); diff --git a/cocos/3d/geom-utils/frustum.js b/cocos/3d/geom-utils/frustum.js deleted file mode 100644 index d75fa293fa..0000000000 --- a/cocos/3d/geom-utils/frustum.js +++ /dev/null @@ -1,119 +0,0 @@ -import enums from './enums'; -import plane from './plane'; -import { vec3 } from '../../core/vmath'; - -let _v = new Array(8); -_v[0] = vec3.create( 1, 1, 1); -_v[1] = vec3.create(-1, 1, 1); -_v[2] = vec3.create(-1, -1, 1); -_v[3] = vec3.create( 1, -1, 1); -_v[4] = vec3.create( 1, 1, -1); -_v[5] = vec3.create(-1, 1, -1); -_v[6] = vec3.create(-1, -1, -1); -_v[7] = vec3.create( 1, -1, -1); - -export default class frustum { - constructor() { - this._type = enums.SHAPE_FRUSTUM; - this.planes = new Array(6); - for (let i = 0; i < 6; ++i) { - this.planes[i] = plane.create(); - } - this.vertices = new Array(8); - for (let i = 0; i < 8; ++i) { - this.vertices[i] = vec3.create(); - } - } - - /** - * create a new frustum - * - * @return {frustum} - */ - static create() { - return new frustum(); - } - - /** - * Clone a frustum - * - * @param {frustum} f frustum to clone - * @return {frustum} the new frustum - */ - static clone(f) { - return frustum.copy(new frustum(), f); - } - - /** - * Copy the values from one frustum to another - * - * @param {frustum} out the receiving frustum - * @param {frustum} f the source frustum - * @return {frustum} - */ - static copy(out, f) { - out._type = f._type; - for (let i = 0; i < 6; ++i) { - plane.copy(out.planes[i], f.planes[i]); - } - for (let i = 0; i < 8; ++i) { - vec3.copy(out.vertices[i], f.vertices[i]); - } - return out; - } - - /** - * Set whether to use accurate intersection testing function on this frustum - * - * @param {boolean} b - */ - set accurate(b) { - this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; - } - - /** - * Update the frustum information according to the given transform matrix. - * Note that the resulting planes are not normalized under normal mode. - * - * @param {mat4} m the view-projection matrix - * @param {mat4} inv the inverse view-projection matrix - */ - update(m, inv) { - // RTR4, ch. 22.14.1, p. 983 - // extract frustum planes from view-proj matrix. - - // left plane - vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08); - this.planes[0].d = -(m.m15 + m.m12); - // right plane - vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08); - this.planes[1].d = -(m.m15 - m.m12); - // bottom plane - vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09); - this.planes[2].d = -(m.m15 + m.m13); - // top plane - vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09); - this.planes[3].d = -(m.m15 - m.m13); - // near plane - vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10); - this.planes[4].d = -(m.m15 + m.m14); - // far plane - vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10); - this.planes[5].d = -(m.m15 - m.m14); - - if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) return; - - // normalize planes - for (let i = 0; i < 6; i++) { - let plane = this.planes[i]; - let invDist = 1 / vec3.magnitude(plane.n); - vec3.scale(plane.n, plane.n, invDist); - plane.d *= invDist; - } - - // update frustum vertices - for (let i = 0; i < 8; i++) { - vec3.transformMat4(this.vertices[i], _v[i], inv); - } - } -} diff --git a/cocos/3d/geom-utils/frustum.ts b/cocos/3d/geom-utils/frustum.ts new file mode 100644 index 0000000000..26330d9e37 --- /dev/null +++ b/cocos/3d/geom-utils/frustum.ts @@ -0,0 +1,116 @@ +import { mat4, vec3 } from '../../core/vmath'; +import enums from './enums'; +import plane from './plane'; + +const _v = new Array(8); +_v[0] = vec3.create(1, 1, 1); +_v[1] = vec3.create(-1, 1, 1); +_v[2] = vec3.create(-1, -1, 1); +_v[3] = vec3.create(1, -1, 1); +_v[4] = vec3.create(1, 1, -1); +_v[5] = vec3.create(-1, 1, -1); +_v[6] = vec3.create(-1, -1, -1); +_v[7] = vec3.create(1, -1, -1); + +// tslint:disable-next-line: class-name +export class frustum { + + /** + * Set whether to use accurate intersection testing function on this frustum + */ + set accurate (b: boolean) { + this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; + } + + /** + * create a new frustum + * + * @return {frustum} + */ + public static create () { + return new frustum(); + } + + /** + * Clone a frustum + */ + public static clone (f: frustum): frustum { + return frustum.copy(new frustum(), f); + } + + /** + * Copy the values from one frustum to another + */ + public static copy (out: frustum, f: frustum): frustum { + out._type = f._type; + for (let i = 0; i < 6; ++i) { + plane.copy(out.planes[i], f.planes[i]); + } + for (let i = 0; i < 8; ++i) { + vec3.copy(out.vertices[i], f.vertices[i]); + } + return out; + } + + public planes: plane[]; + public vertices: vec3[]; + private _type: number; + + constructor () { + this._type = enums.SHAPE_FRUSTUM; + this.planes = new Array(6); + for (let i = 0; i < 6; ++i) { + this.planes[i] = plane.create(); + } + this.vertices = new Array(8); + for (let i = 0; i < 8; ++i) { + this.vertices[i] = vec3.create(); + } + } + + /** + * Update the frustum information according to the given transform matrix. + * Note that the resulting planes are not normalized under normal mode. + * + * @param {mat4} m the view-projection matrix + * @param {mat4} inv the inverse view-projection matrix + */ + public update (m: mat4, inv: mat4) { + // RTR4, ch. 22.14.1, p. 983 + // extract frustum planes from view-proj matrix. + + // left plane + vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08); + this.planes[0].d = -(m.m15 + m.m12); + // right plane + vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08); + this.planes[1].d = -(m.m15 - m.m12); + // bottom plane + vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09); + this.planes[2].d = -(m.m15 + m.m13); + // top plane + vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09); + this.planes[3].d = -(m.m15 - m.m13); + // near plane + vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10); + this.planes[4].d = -(m.m15 + m.m14); + // far plane + vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10); + this.planes[5].d = -(m.m15 - m.m14); + + if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) { return; } + + // normalize planes + for (let i = 0; i < 6; i++) { + const pl = this.planes[i]; + const invDist = 1 / vec3.magnitude(pl.n); + vec3.scale(pl.n, pl.n, invDist); + pl.d *= invDist; + } + + // update frustum vertices + for (let i = 0; i < 8; i++) { + vec3.transformMat4(this.vertices[i], _v[i], inv); + } + } +} diff --git a/cocos/3d/geom-utils/index.js b/cocos/3d/geom-utils/index.ts similarity index 91% rename from cocos/3d/geom-utils/index.js rename to cocos/3d/geom-utils/index.ts index 30b4011744..99bd86140e 100644 --- a/cocos/3d/geom-utils/index.js +++ b/cocos/3d/geom-utils/index.ts @@ -8,6 +8,6 @@ export { default as triangle } from './triangle'; export { default as sphere } from './sphere'; export { default as aabb } from './aabb'; export { default as obb } from './obb'; -export { default as frustum } from './frustum'; +export { frustum } from './frustum'; export { default as Octree } from './octree'; export { Keyframe, AnimationCurve } from './curve'; diff --git a/cocos/3d/index.js b/cocos/3d/index.js index 8f70aeeed1..c3998ccf3c 100644 --- a/cocos/3d/index.js +++ b/cocos/3d/index.js @@ -27,9 +27,10 @@ export * from './assets'; export * from './builtin'; export * from './framework'; export * from './memop'; -import utils from './misc/utils'; +import * as utils from './misc/utils'; import * as primitives from './primitive'; import * as geometry from './geom-utils'; +import './ui'; export { utils, @@ -39,4 +40,4 @@ export { cc.geometry = geometry; cc.primitives = primitives; -cc.utils = utils; \ No newline at end of file +cc.utils = utils; diff --git a/cocos/3d/memop/recycle-pool.js b/cocos/3d/memop/recycle-pool.js deleted file mode 100644 index 98f8097312..0000000000 --- a/cocos/3d/memop/recycle-pool.js +++ /dev/null @@ -1,57 +0,0 @@ -import sort from './timsort'; - -export default class RecyclePool { - constructor(fn, size) { - this._fn = fn; - this._count = 0; - this._data = new Array(size); - - for (let i = 0; i < size; ++i) { - this._data[i] = fn(); - } - } - - get length() { - return this._count; - } - - get data() { - return this._data; - } - - reset() { - this._count = 0; - } - - resize(size) { - if (size > this._data.length) { - for (let i = this._data.length; i < size; ++i) { - this._data[i] = this._fn(); - } - } - } - - add() { - if (this._count >= this._data.length) { - this.resize(this._data.length * 2); - } - - return this._data[this._count++]; - } - - remove(idx) { - if (idx >= this._count) { - return; - } - - let last = this._count - 1; - let tmp = this._data[idx]; - this._data[idx] = this._data[last]; - this._data[last] = tmp; - this._count -= 1; - } - - sort(cmp) { - return sort(this._data, 0, this._count, cmp); - } -} \ No newline at end of file diff --git a/cocos/3d/memop/recycle-pool.ts b/cocos/3d/memop/recycle-pool.ts new file mode 100644 index 0000000000..67f8b5a89f --- /dev/null +++ b/cocos/3d/memop/recycle-pool.ts @@ -0,0 +1,72 @@ +import sort from './timsort'; + +export default class RecyclePool { + private _fn: () => T; + private _count = 0; + private _data: T[]; + private _objIdx: Map; + + constructor (fn: () => T, size: number) { + this._fn = fn; + this._data = new Array(size); + this._objIdx = new Map(); + + for (let i = 0; i < size; ++i) { + this._data[i] = fn(); + this._objIdx.set(this._data[i], i); + } + } + + get length () { + return this._count; + } + + get data () { + return this._data; + } + + public reset () { + this._count = 0; + } + + public resize (size: number) { + if (size > this._data.length) { + for (let i = this._data.length; i < size; ++i) { + this._data[i] = this._fn(); + this._objIdx.set(this._data[i], i); + } + } + } + + public add () { + if (this._count >= this._data.length) { + this.resize(this._data.length * 2); + } + + return this._data[this._count++]; + } + + public removeAt (idx: number) { + if (idx >= this._count) { + return; + } + + const last = this._count - 1; + const tmp = this._data[idx]; + this._data[idx] = this._data[last]; + this._data[last] = tmp; + this._objIdx.set(this._data[idx], idx); + this._objIdx.set(this._data[last], last); + this._count -= 1; + } + + public remove (obj: T) { + if (this._objIdx.has(obj)) { + this.removeAt(this._objIdx.get(obj)!); + } + } + + public sort (compare: (a: T, b: T) => number) { + return sort(this._data, 0, this._count, compare); + } +} diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js deleted file mode 100644 index f4f7bde08a..0000000000 --- a/cocos/3d/misc/utils.js +++ /dev/null @@ -1,67 +0,0 @@ -import { renderer } from '../../renderer'; -import find from '../../scene-graph/find'; -import Mesh from '../assets/mesh'; -import gfx from '../../renderer/gfx/index'; - -/** - * - * @param {import("../assets/skeleton").default} skinning - */ -function createJointsTexture(skinning) { - const jointCount = skinning.joints.length; - - // Set jointsTexture. - // A squared texture with side length N(N > 1) multiples of 2 can store - // 2 ^ (2 * N - 2) matrices. - // We support most 1024 joints. - let size; - if (jointCount > 1024) { - throw "To many joints(more than 1024)."; - } else if (jointCount > 256) { - size = 64; - } else if (jointCount > 64) { - size = 32; - } else if (jointCount > 16) { - size = 16; - } else if (jointCount > 4) { - size = 8; - } else { - size = 4; - } - - return new gfx.Texture2D(cc.game._renderContext, { - width: size, - height: size, - format: gfx.TEXTURE_FMT_RGBA32F, - minFilter: gfx.FILTER_NEAREST, - magFilter: gfx.FILTER_NEAREST, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - mipmap: false - }); -} - -function createMesh(context, data) { - let ia = renderer.createIA(context, data); - let meshAsset = new Mesh(); - meshAsset._subMeshes = [ia]; - meshAsset._minPosition = data.minPos; - meshAsset._maxPosition = data.maxPos; - - return meshAsset; -} - -/** - * @param {Uint8Array} buffer - */ -function toPPM(buffer, w, h) { - return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; -} - -export default { - createJointsTexture, - createMesh, - - find, - toPPM -}; diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts new file mode 100644 index 0000000000..7b2e70722c --- /dev/null +++ b/cocos/3d/misc/utils.ts @@ -0,0 +1,245 @@ +import { GFXAttributeName, GFXPrimitiveMode } from '../../gfx/define'; +export { default as find } from '../../scene-graph/find'; +import { Vec3 } from '../../core/value-types'; +import { AttributeBaseType, AttributeType, + IMeshStruct, IndexUnit, IPrimitive, IVertexAttribute, IVertexBundle, Mesh } from '../assets/mesh'; +import { IGeometry } from '../primitive/define'; + +const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute); +export function createMesh (geometry: IGeometry) { + // Collect attributes and calculate length of result vertex buffer. + const attributes: IVertexAttribute[] = []; + let stride = 0; + const channels: Array<{ offset: number; data: number[]; attribute: IVertexAttribute; }> = []; + let verticesCount = 0; + const addAttribute = (attribute: IVertexAttribute, data: number[]) => { + const componentCount = _getComponentCount(attribute); + const componentBytesLength = _getComponentByteLength(attribute); + const bytesLength = componentBytesLength * componentCount; + attributes.push(attribute); + channels.push({ offset: stride, data, attribute }); + stride += bytesLength; + verticesCount = Math.max(verticesCount, Math.floor(data.length / componentCount)); + }; + addAttribute(copyAttribute(predefinedAttributes.positions), geometry.positions); + if (geometry.normals) { + addAttribute(copyAttribute(predefinedAttributes.normals), geometry.normals); + } + if (geometry.uvs) { + addAttribute(copyAttribute(predefinedAttributes.uvs), geometry.uvs); + } + if (geometry.colors) { + addAttribute(copyAttribute(predefinedAttributes.colors), geometry.colors); + } + + // Use this to generate final merged buffer. + const bufferBlob = new BufferBlob(); + + // Fill vertex buffer. + const vertexBuffer = new ArrayBuffer(verticesCount * stride); + const vertexBufferView = new DataView(vertexBuffer); + for (const channel of channels) { + _writeVertices(vertexBufferView, channel.offset, stride, channel.attribute, channel.data); + } + const vertexBundle: IVertexBundle = { + verticesCount, + attributes, + data: { + offset: bufferBlob.getLength(), + length: vertexBuffer.byteLength, + }, + }; + bufferBlob.addBuffer(vertexBuffer); + + // Fill index buffer. + let indexBuffer: ArrayBuffer | null = null; + const targetIndexUnit = IndexUnit.UINT16; + if (geometry.indices) { + const { indices } = geometry; + const indexUnitBytesLength = 2; + indexBuffer = new ArrayBuffer(indexUnitBytesLength * indices.length); + const indexBufferView = new DataView(indexBuffer); + const writer = _getIndicesWriter(indexBufferView, targetIndexUnit); + for (let i = 0; i < indices.length; ++i) { + writer(indexUnitBytesLength * i, indices[i]); + } + } + + // Create primitive. + const primitive: IPrimitive = { + primitiveMode: geometry.primitiveMode || GFXPrimitiveMode.TRIANGLE_LIST, + vertexBundelIndices: [0], + }; + // geometric info for raycasting + if (primitive.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) { + const geomInfo = Float32Array.from(geometry.positions); + primitive.geometricInfo = { + doubleSided: geometry.doubleSided, + range: { offset: bufferBlob.getLength(), length: geomInfo.byteLength }, + }; + bufferBlob.addBuffer(geomInfo.buffer); + } + + if (indexBuffer) { + primitive.indices = { + indexUnit: targetIndexUnit, + range: { + offset: bufferBlob.getLength(), + length: indexBuffer.byteLength, + }, + }; + bufferBlob.addBuffer(indexBuffer); + } + + // Create mesh struct. + const meshStruct: IMeshStruct = { + vertexBundles: [vertexBundle], + primitives: [primitive], + minPosition: geometry.minPos && new Vec3(geometry.minPos.x, geometry.minPos.y, geometry.minPos.z), + maxPosition: geometry.maxPos && new Vec3(geometry.maxPos.x, geometry.maxPos.y, geometry.maxPos.z), + }; + + // Create mesh. + const mesh = new Mesh(); + mesh.assign(meshStruct, new Uint8Array(bufferBlob.getCombined())); + + return mesh; +} + +/** + * + */ +export function toPPM (buffer: Uint8Array, w: number, h: number) { + return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; +} + +const predefinedAttributes = { + positions: { + name: GFXAttributeName.ATTR_POSITION, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC3, + normalize: false, + }, + normals: { + name: GFXAttributeName.ATTR_NORMAL, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC3, + normalize: false, + }, + uvs: { + name: GFXAttributeName.ATTR_TEX_COORD, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC2, + normalize: false, + }, + colors: { + name: GFXAttributeName.ATTR_COLOR, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC4, + normalize: false, + }, +}; + +class BufferBlob { + private _arrayBuffers: ArrayBuffer[] = []; + private _length = 0; + + public addBuffer (arrayBuffer: ArrayBuffer) { + const result = this._length; + this._arrayBuffers.push(arrayBuffer); + this._length += arrayBuffer.byteLength; + return result; + } + + public getLength () { + return this._length; + } + + public getCombined () { + let length = 0; + this._arrayBuffers.forEach((arrayBuffer) => length += arrayBuffer.byteLength); + const result = new Uint8Array(length); + let counter = 0; + this._arrayBuffers.forEach((arrayBuffer) => { + result.set(new Uint8Array(arrayBuffer), counter); + counter += arrayBuffer.byteLength; + }); + return result.buffer; + } +} + +function _writeVertices ( + target: DataView, offset: number, stride: number, attribute: IVertexAttribute, data: number[]) { + const writer = _getVerticesWriter(target, attribute.baseType); + const componentCount = _getComponentCount(attribute); + const componentBytesLength = _getComponentByteLength(attribute); + const nVertices = Math.floor(data.length / componentCount); + + for (let iVertex = 0; iVertex < nVertices; ++iVertex) { + const x = offset + stride * iVertex; + for (let iComponent = 0; iComponent < componentCount; ++iComponent) { + const y = x + componentBytesLength * iComponent; + writer(y, data[componentCount * iVertex + iComponent]); + } + } +} + +function _getComponentByteLength (vertexAttribute: IVertexAttribute) { + switch (vertexAttribute.baseType) { + case AttributeBaseType.INT8: + case AttributeBaseType.UINT8: + return 1; + case AttributeBaseType.INT16: + case AttributeBaseType.UINT16: + return 2; + case AttributeBaseType.INT32: + case AttributeBaseType.UINT32: + case AttributeBaseType.FLOAT32: + return 4; + } + return 1; +} + +function _getComponentCount (vertexAttribute: IVertexAttribute) { + switch (vertexAttribute.type) { + case AttributeType.SCALAR: return 1; + case AttributeType.VEC2: return 2; + case AttributeType.VEC3: return 3; + case AttributeType.VEC4: return 4; + } + return 1; +} + +const isLittleEndian = cc.sys.isLittleEndian; + +function _getVerticesWriter (dataView: DataView, baseType: AttributeBaseType) { + switch (baseType) { + case AttributeBaseType.INT8: + return (offset: number, value: number) => dataView.setInt8(offset, value); + case AttributeBaseType.UINT8: + return (offset: number, value: number) => dataView.setUint8(offset, value); + case AttributeBaseType.INT16: + return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian); + case AttributeBaseType.UINT16: + return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case AttributeBaseType.INT32: + return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian); + case AttributeBaseType.UINT32: + return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); + case AttributeBaseType.FLOAT32: + return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian); + } + return (offset: number, value: number) => dataView.setUint8(offset, value); +} + +function _getIndicesWriter (dataView: DataView, indexUnit: IndexUnit) { + switch (indexUnit) { + case IndexUnit.UINT8: + return (offset: number, value: number) => dataView.setUint8(offset, value); + case IndexUnit.UINT16: + return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case IndexUnit.UINT32: + return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); + } + return (offset: number, value: number) => dataView.setUint8(offset, value); +} diff --git a/cocos/3d/primitive/box.js b/cocos/3d/primitive/box.js deleted file mode 100644 index e9aa1b0873..0000000000 --- a/cocos/3d/primitive/box.js +++ /dev/null @@ -1,130 +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 c0 = vec3.create(0, 0, 0); -let c1 = vec3.create(0, 0, 0); -let c2 = vec3.create(0, 0, 0); -let c3 = vec3.create(0, 0, 0); -let c4 = vec3.create(0, 0, 0); -let c5 = vec3.create(0, 0, 0); -let c6 = vec3.create(0, 0, 0); -let c7 = vec3.create(0, 0, 0); - -/** - * @param {Number} width - * @param {Number} height - * @param {Number} length - * @param {Object} opts - * @param {Number} opts.widthSegments - * @param {Number} opts.heightSegments - * @param {Number} opts.lengthSegments - */ -export default function (width = 1, height = 1, length = 1, opts = {}) { - let ws = opts.widthSegments !== undefined ? opts.widthSegments : 1; - let hs = opts.heightSegments !== undefined ? opts.heightSegments : 1; - let ls = opts.lengthSegments !== undefined ? opts.lengthSegments : 1; - let inv = opts.invWinding !== undefined ? opts.invWinding : false; - - let hw = width * 0.5; - let hh = height * 0.5; - let hl = length * 0.5; - - let corners = [ - vec3.set(c0, -hw, -hh, hl), - vec3.set(c1, hw, -hh, hl), - vec3.set(c2, hw, hh, hl), - vec3.set(c3, -hw, hh, hl), - vec3.set(c4, hw, -hh, -hl), - vec3.set(c5, -hw, -hh, -hl), - vec3.set(c6, -hw, hh, -hl), - vec3.set(c7, hw, hh, -hl), - ]; - - let faceAxes = [ - [ 2, 3, 1 ], // FRONT - [ 4, 5, 7 ], // BACK - [ 7, 6, 2 ], // TOP - [ 1, 0, 4 ], // BOTTOM - [ 1, 4, 2 ], // RIGHT - [ 5, 0, 6 ] // LEFT - ]; - - let faceNormals = [ - [ 0, 0, 1 ], // FRONT - [ 0, 0, -1 ], // BACK - [ 0, 1, 0 ], // TOP - [ 0, -1, 0 ], // BOTTOM - [ 1, 0, 0 ], // RIGHT - [ -1, 0, 0 ] // LEFT - ]; - - let positions = []; - let normals = []; - let uvs = []; - let indices = []; - let minPos = vec3.create(-hw, -hh, -hl); - let maxPos = vec3.create(hw, hh, hl); - let boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl); - - function _buildPlane (side, uSegments, vSegments) { - let u, v; - let ix, iy; - let offset = positions.length / 3; - let faceAxe = faceAxes[side]; - let faceNormal = faceNormals[side]; - - for (iy = 0; iy <= vSegments; iy++) { - for (ix = 0; ix <= uSegments; ix++) { - u = ix / uSegments; - v = iy / vSegments; - - vec3.lerp(temp1, corners[faceAxe[0]], corners[faceAxe[1]], u); - vec3.lerp(temp2, corners[faceAxe[0]], corners[faceAxe[2]], v); - vec3.sub(temp3, temp2, corners[faceAxe[0]]); - vec3.add(r, temp1, temp3); - - positions.push(r.x, r.y, r.z); - normals.push(faceNormal[0], faceNormal[1], faceNormal[2]); - uvs.push(u, v); - - if ((ix < uSegments) && (iy < vSegments)) { - let useg1 = uSegments + 1; - let a = ix + iy * useg1; - let b = ix + (iy + 1) * useg1; - let c = (ix + 1) + (iy + 1) * useg1; - let d = (ix + 1) + iy * useg1; - - if (inv) { - indices.push(offset + a, offset + b, offset + d); - indices.push(offset + d, offset + b, offset + c); - } else { - indices.push(offset + a, offset + d, offset + b); - indices.push(offset + b, offset + d, offset + c); - } - } - } - } - } - - _buildPlane(0, ws, hs); // FRONT - _buildPlane(4, ls, hs); // RIGHT - _buildPlane(1, ws, hs); // BACK - _buildPlane(5, ls, hs); // LEFT - _buildPlane(3, ws, ls); // BOTTOM - _buildPlane(2, ws, ls); // TOP - - return { - positions, - normals, - uvs, - indices, - minPos, - maxPos, - boundingRadius - }; -} diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts new file mode 100644 index 0000000000..e67755f41c --- /dev/null +++ b/cocos/3d/primitive/box.ts @@ -0,0 +1,155 @@ +import { Vec3 } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { IGeometry, IGeometryOptions } from './define'; + +interface IBoxOptions extends RecursivePartial { + /** + * Box extent on X-axis. + */ + width?: number; + + /** + * Box extent on Y-axis. + */ + height?: number; + + /** + * Box extent on Z-axis. + */ + length?: number; + + /** + * Segment count on X-axis. + */ + widthSegments?: number; + + /** + * Segment count on Y-axis. + */ + heightSegments?: number; + + /** + * Segment count on Z-axis. + */ + lengthSegments?: number; +} + +/** + * This function generates a box with specified extents and centered at origin, + * but may be repositioned through `center` option). + * @param options Options. + */ +export default function box (options?: IBoxOptions): IGeometry { + options = options || {}; + const ws = options.widthSegments || 1; + const hs = options.heightSegments || 1; + const ls = options.lengthSegments || 1; + + const hw = (options.width || 1) / 2; + const hh = (options.height || 1) / 2; + const hl = (options.length || 1) / 2; + + const corners = [ + vec3.set(c0, -hw, -hh, hl), + vec3.set(c1, hw, -hh, hl), + vec3.set(c2, hw, hh, hl), + vec3.set(c3, -hw, hh, hl), + vec3.set(c4, hw, -hh, -hl), + vec3.set(c5, -hw, -hh, -hl), + vec3.set(c6, -hw, hh, -hl), + vec3.set(c7, hw, hh, -hl), + ]; + + const faceAxes = [ + [2, 3, 1], // FRONT + [4, 5, 7], // BACK + [7, 6, 2], // TOP + [1, 0, 4], // BOTTOM + [1, 4, 2], // RIGHT + [5, 0, 6], // LEFT + ]; + + const faceNormals = [ + [0, 0, 1], // FRONT + [0, 0, -1], // BACK + [0, 1, 0], // TOP + [0, -1, 0], // BOTTOM + [1, 0, 0], // RIGHT + [-1, 0, 0], // LEFT + ]; + + const positions: number[] = []; + const normals: number[] = []; + const uvs: number[] = []; + const indices: number[] = []; + const minPos = new Vec3(-hw, -hh, -hl); + const maxPos = new Vec3(hw, hh, hl); + const boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl); + + function _buildPlane (side: number, uSegments: number, vSegments: number) { + let u: number; + let v: number; + let ix: number; + let iy: number; + const offset = positions.length / 3; + const faceAxe = faceAxes[side]; + const faceNormal = faceNormals[side]; + + for (iy = 0; iy <= vSegments; iy++) { + for (ix = 0; ix <= uSegments; ix++) { + u = ix / uSegments; + v = iy / vSegments; + + vec3.lerp(temp1, corners[faceAxe[0]], corners[faceAxe[1]], u); + vec3.lerp(temp2, corners[faceAxe[0]], corners[faceAxe[2]], v); + vec3.sub(temp3, temp2, corners[faceAxe[0]]); + vec3.add(r, temp1, temp3); + + positions.push(r.x, r.y, r.z); + normals.push(faceNormal[0], faceNormal[1], faceNormal[2]); + uvs.push(u, v); + + if ((ix < uSegments) && (iy < vSegments)) { + const useg1 = uSegments + 1; + const a = ix + iy * useg1; + const b = ix + (iy + 1) * useg1; + const c = (ix + 1) + (iy + 1) * useg1; + const d = (ix + 1) + iy * useg1; + + indices.push(offset + a, offset + d, offset + b); + indices.push(offset + b, offset + d, offset + c); + } + } + } + } + + _buildPlane(0, ws, hs); // FRONT + _buildPlane(4, ls, hs); // RIGHT + _buildPlane(1, ws, hs); // BACK + _buildPlane(5, ls, hs); // LEFT + _buildPlane(3, ws, ls); // BOTTOM + _buildPlane(2, ws, ls); // TOP + + return { + positions, + normals, + uvs, + indices, + minPos, + maxPos, + boundingRadius, + }; +} + +const temp1 = new Vec3(); +const temp2 = new Vec3(); +const temp3 = new Vec3(); +const r = new Vec3(); +const c0 = new Vec3(); +const c1 = new Vec3(); +const c2 = new Vec3(); +const c3 = new Vec3(); +const c4 = new Vec3(); +const c5 = new Vec3(); +const c6 = new Vec3(); +const c7 = new Vec3(); diff --git a/cocos/3d/primitive/circle.ts b/cocos/3d/primitive/circle.ts new file mode 100644 index 0000000000..eb20f37dc5 --- /dev/null +++ b/cocos/3d/primitive/circle.ts @@ -0,0 +1,56 @@ +import { GFXPrimitiveMode } from '../../gfx/define'; +import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; + +interface ICircleOptions extends IGeometryOptions { + // The segments. Default to 64. + segments: number; +} + +function applyDefaultCircleOptions (options?: RecursivePartial): ICircleOptions { + options = applyDefaultGeometryOptions(options); + options.segments = 64; + return options as ICircleOptions; +} + +/** + * Generate a circle with radius 1, centered at origin. + * @param options Options. + */ +export default function circle (options?: RecursivePartial | ICircleOptions): IGeometry { + const normalizedOptions = applyDefaultCircleOptions(options); + const segments = normalizedOptions.segments; + + const positions = new Array(3 * (segments + 1)); + positions[0] = 0; + positions[1] = 0; + positions[2] = 0; + const indices = new Array(1 + segments * 2); + indices[0] = 0; + const step = Math.PI * 2 / segments; + for (let iSegment = 0; iSegment < segments; ++iSegment) { + const angle = step * iSegment; + const x = Math.cos(angle); + const y = Math.sin(angle); + const p = (iSegment + 1) * 3; + positions[p + 0] = x; + positions[p + 1] = y; + positions[p + 2] = 0; + const i = iSegment * 2; + indices[1 + (i)] = iSegment + 1; + indices[1 + (i + 1)] = iSegment + 2; + } + if (segments > 0) { + indices[indices.length - 1] = 1; + } + + const result: IGeometry = { + positions, + indices, + minPos: { x: 1, y: 1, z: 0 }, + maxPos: { x: -1, y: -1, z: 0 }, + boundingRadius: 1, + primitiveMode: GFXPrimitiveMode.TRIANGLE_FAN, + }; + + return result; +} diff --git a/cocos/3d/primitive/define.ts b/cocos/3d/primitive/define.ts new file mode 100644 index 0000000000..b4f555e759 --- /dev/null +++ b/cocos/3d/primitive/define.ts @@ -0,0 +1,85 @@ +import { GFXPrimitiveMode } from '../../gfx/define'; + +export interface IGeometryOptions { + /** + * Whether to include normal. Default to true. + */ + includeNormal: boolean; + + /** + * Whether to include uv. Default to true. + */ + includeUV: boolean; +} + +export function applyDefaultGeometryOptions ( + options?: RecursivePartial): GeometryOptions { + options = options || {}; + if (options.includeNormal === undefined) { + options.includeNormal = true; + } + if (options.includeUV === undefined) { + options.includeUV = true; + } + return options as GeometryOptions; +} + +export interface IGeometry { + /** + * Vertex positions. + */ + positions: number[]; + + /** + * Min position. + */ + minPos: { + x: number; + y: number; + z: number; + }; + + /** + * Max position. + */ + maxPos: { + x: number; + y: number; + z: number; + }; + + /** + * Bounding sphere radius. + */ + boundingRadius: number; + + /** + * Gemetry indices, if one needs indexed-draw. + */ + indices?: number[]; + + /** + * Vertex normals. + */ + normals?: number[]; + + /** + * Texture coordinates. + */ + uvs?: number[]; + + /** + * Vertex colors. + */ + colors?: number[]; + + /** + * Topology of the geometry vertices. Default is TRIANGLE_LIST. + */ + primitiveMode?: GFXPrimitiveMode; + + /** + * whether rays casting from the back face of this geometry could collide with it + */ + doubleSided?: boolean; +} diff --git a/cocos/3d/primitive/index.js b/cocos/3d/primitive/index.ts similarity index 70% rename from cocos/3d/primitive/index.js rename to cocos/3d/primitive/index.ts index f69ede2753..9d77900f62 100644 --- a/cocos/3d/primitive/index.js +++ b/cocos/3d/primitive/index.ts @@ -6,4 +6,6 @@ export { default as plane } from './plane'; export { default as quad } from './quad'; export { default as sphere } from './sphere'; export { default as torus } from './torus'; -export { default as capsule } from './capsule'; \ No newline at end of file +export { default as capsule } from './capsule'; +export { default as circle } from './circle'; +export { translate, scale } from './transform'; \ No newline at end of file diff --git a/cocos/3d/primitive/quad.js b/cocos/3d/primitive/quad.js deleted file mode 100644 index 503702c5a0..0000000000 --- a/cocos/3d/primitive/quad.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -import { vec3 } from '../../core/vmath'; - -let positions = [ - -0.5, -0.5, 0, // bottom-left - -0.5, 0.5, 0, // top-left - 0.5, 0.5, 0, // top-right - 0.5, -0.5, 0, // bottom-right -]; - -let normals = [ - 0, 0, 1, - 0, 0, 1, - 0, 0, 1, - 0, 0, 1, -]; - -let uvs = [ - 0, 0, - 0, 1, - 1, 1, - 1, 0, -]; - -let indices = [ - 0, 3, 1, - 3, 2, 1 -]; - -// TODO: ? -let minPos = vec3.create(-0.5, -0.5, 0); -let maxPos = vec3.create(0.5, 0.5, 0); -let boundingRadius = Math.sqrt(0.5 * 0.5 + 0.5 * 0.5); - -export default function () { - return { - positions, - indices, - normals, - uvs, - minPos, - maxPos, - boundingRadius - }; -} diff --git a/cocos/3d/primitive/quad.ts b/cocos/3d/primitive/quad.ts new file mode 100644 index 0000000000..a142a6cd8d --- /dev/null +++ b/cocos/3d/primitive/quad.ts @@ -0,0 +1,47 @@ +'use strict'; + +import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; + +/** + * Generate a quad with width and height both to 1, centered at origin. + * @param options Options. + */ +export default function quad (options?: IGeometryOptions): IGeometry { + const normalizedOptions = applyDefaultGeometryOptions(options); + const result: IGeometry = { + positions: [ + -0.5, -0.5, 0, // bottom-left + -0.5, 0.5, 0, // top-left + 0.5, 0.5, 0, // top-right + 0.5, -0.5, 0, // bottom-right + ], + indices: [ + 0, 3, 1, + 3, 2, 1, + ], + minPos: { + x: -0.5, y: -0.5, z: 0, + }, + maxPos: { + x: 0.5, y: 0.5, z: 0, + }, + boundingRadius: Math.sqrt(0.5 * 0.5 + 0.5 * 0.5), + }; + if (normalizedOptions.includeNormal !== false) { + result.normals = [ + 0, 0, 1, + 0, 0, 1, + 0, 0, 1, + 0, 0, 1, + ]; + } + if (normalizedOptions.includeUV !== false) { + result.uvs = [ + 0, 0, + 0, 1, + 1, 1, + 1, 0, + ]; + } + return result; +} diff --git a/cocos/3d/primitive/sphere.js b/cocos/3d/primitive/sphere.js index f7e1037801..9e22d56bce 100644 --- a/cocos/3d/primitive/sphere.js +++ b/cocos/3d/primitive/sphere.js @@ -1,6 +1,7 @@ 'use strict'; import { vec3 } from '../../core/vmath'; +import { GFXPrimitiveMode } from '../../gfx/define'; /** * @param {Number} radius diff --git a/cocos/3d/primitive/transform.ts b/cocos/3d/primitive/transform.ts new file mode 100644 index 0000000000..57eb6bd39f --- /dev/null +++ b/cocos/3d/primitive/transform.ts @@ -0,0 +1,46 @@ +import { IGeometry } from './define'; + +export function translate (geometry: IGeometry, offset: { x?: number; y?: number; z?: number; }) { + const x = offset.x || 0; + const y = offset.y || 0; + const z = offset.z || 0; + const nVertex = Math.floor(geometry.positions.length / 3); + for (let iVertex = 0; iVertex < nVertex; ++iVertex) { + const iX = iVertex * 3; + const iY = iVertex * 3 + 1; + const iZ = iVertex * 3 + 2; + geometry.positions[iX] = geometry.positions[iX] + x; + geometry.positions[iY] = geometry.positions[iY] + y; + geometry.positions[iZ] = geometry.positions[iZ] + z; + } + geometry.minPos.x += x; + geometry.minPos.y += y; + geometry.minPos.z += z; + geometry.maxPos.x += x; + geometry.maxPos.y += y; + geometry.maxPos.z += z; + return geometry; +} + +export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: number }) { + const x = value.x || 0; + const y = value.y || 0; + const z = value.z || 0; + const nVertex = Math.floor(geometry.positions.length / 3); + for (let iVertex = 0; iVertex < nVertex; ++iVertex) { + const iX = iVertex * 3; + const iY = iVertex * 3 + 1; + const iZ = iVertex * 3 + 2; + geometry.positions[iX] *= x; + geometry.positions[iY] *= y; + geometry.positions[iZ] *= z; + } + geometry.minPos.x *= x; + geometry.minPos.y *= y; + geometry.minPos.z *= z; + geometry.maxPos.x *= x; + geometry.maxPos.y *= y; + geometry.maxPos.z *= z; + geometry.boundingRadius = Math.max(Math.max(x, y), z); + return geometry; +} diff --git a/cocos/3d/ui/assembler/assembler.ts b/cocos/3d/ui/assembler/assembler.ts new file mode 100644 index 0000000000..ed8d1ed208 --- /dev/null +++ b/cocos/3d/ui/assembler/assembler.ts @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { UIRenderComponent } from '../components/ui-render-component'; +import { RenderData } from '../../../renderer/ui/renderData'; +import { UI } from '../../../renderer/ui/ui'; + +export interface IAssembler { + + 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); +} diff --git a/cocos/2d/renderer/webgl/assemblers/assembler.js b/cocos/3d/ui/assembler/index.ts similarity index 89% rename from cocos/2d/renderer/webgl/assemblers/assembler.js rename to cocos/3d/ui/assembler/index.ts index b9096953f6..3f8c710bb4 100644 --- a/cocos/2d/renderer/webgl/assemblers/assembler.js +++ b/cocos/3d/ui/assembler/index.ts @@ -23,7 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -module.exports = { - useModel: false, - datas: [] -}; \ No newline at end of file +// require('./sprite'); +// require('./mask-assembler'); +// require('./graphics'); +import './label/index'; +import './sprite/index'; +// require('./motion-streak'); diff --git a/cocos/2d/renderer/webgl/assemblers/label/bmfont.js b/cocos/3d/ui/assembler/label/bmfont.js similarity index 55% rename from cocos/2d/renderer/webgl/assemblers/label/bmfont.js rename to cocos/3d/ui/assembler/label/bmfont.js index c4b985ee3c..c19f3ad835 100644 --- a/cocos/2d/renderer/webgl/assemblers/label/bmfont.js +++ b/cocos/3d/ui/assembler/label/bmfont.js @@ -23,45 +23,23 @@ THE SOFTWARE. ****************************************************************************/ -const js = require('../../../../platform/js'); -const bmfontUtls = require('../../../utils/label/bmfont'); +import * as js from '../../../../core/utils/js'; +import bmfontUtls from '../../../../2d/renderer/utils/label/bmfont'; +import { fillMeshVertices3D } from '../utils'; -module.exports = js.addon({ - createData (comp) { +let bmfont = { + createData(comp) { return comp.requestRenderData(); }, - fillBuffers (comp, renderer) { - let node = comp.node, - renderData = comp._renderData, - data = renderData._data, - color = node.color._val; - - let matrix = node._worldMatrix, - a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - - let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2; - - let vertexCount = renderData.vertexCount; - buffer.request(vertexCount, renderData.indiceCount); - - // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData; - - for (let i = 0; i < vertexCount; i++) { - let vert = data[i]; - vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; - vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; - vbuf[vertexOffset++] = vert.u; - vbuf[vertexOffset++] = vert.v; - } + fillBuffers(comp, renderer) { + let node = comp.node; + fillMeshVertices3D(node, renderer._meshBuffer3D, comp._renderData, node._color._val); }, - appendQuad (renderData, texture, rect, rotated, x, y, scale) { + appendQuad(renderData, texture, rect, rotated, x, y, scale) { let dataOffset = renderData.dataLength; - + renderData.dataLength += 4; renderData.vertexCount = renderData.dataLength; renderData.indiceCount = renderData.dataLength / 2 * 3; @@ -82,12 +60,12 @@ module.exports = js.addon({ data[dataOffset].u = l; data[dataOffset].v = b; - data[dataOffset+1].u = r; - data[dataOffset+1].v = b; - data[dataOffset+2].u = l; - data[dataOffset+2].v = t; - data[dataOffset+3].u = r; - data[dataOffset+3].v = t; + data[dataOffset + 1].u = r; + data[dataOffset + 1].v = b; + data[dataOffset + 2].u = l; + data[dataOffset + 2].v = t; + data[dataOffset + 3].u = r; + data[dataOffset + 3].v = t; } else { l = (rect.x) / texw; r = (rect.x + rectHeight) / texw; @@ -96,21 +74,25 @@ module.exports = js.addon({ data[dataOffset].u = l; data[dataOffset].v = t; - data[dataOffset+1].u = l; - data[dataOffset+1].v = b; - data[dataOffset+2].u = r; - data[dataOffset+2].v = t; - data[dataOffset+3].u = r; - data[dataOffset+3].v = b; + data[dataOffset + 1].u = l; + data[dataOffset + 1].v = b; + data[dataOffset + 2].u = r; + data[dataOffset + 2].v = t; + data[dataOffset + 3].u = r; + data[dataOffset + 3].v = b; } data[dataOffset].x = x; data[dataOffset].y = y - rectHeight * scale; - data[dataOffset+1].x = x + rectWidth * scale; - data[dataOffset+1].y = y - rectHeight * scale; - data[dataOffset+2].x = x; - data[dataOffset+2].y = y; - data[dataOffset+3].x = x + rectWidth * scale; - data[dataOffset+3].y = y; + data[dataOffset + 1].x = x + rectWidth * scale; + data[dataOffset + 1].y = y - rectHeight * scale; + data[dataOffset + 2].x = x; + data[dataOffset + 2].y = y; + data[dataOffset + 3].x = x + rectWidth * scale; + data[dataOffset + 3].y = y; }, -}, bmfontUtls); +}; + +js.addon(bmfont, bmfontUtls); + +export default bmfont; diff --git a/cocos/2d/renderer/webgl/assemblers/label/index.js b/cocos/3d/ui/assembler/label/index.ts similarity index 74% rename from cocos/2d/renderer/webgl/assemblers/label/index.js rename to cocos/3d/ui/assembler/label/index.ts index fe44c9af4d..9e79489c73 100644 --- a/cocos/2d/renderer/webgl/assemblers/label/index.js +++ b/cocos/3d/ui/assembler/label/index.ts @@ -23,27 +23,32 @@ THE SOFTWARE. ****************************************************************************/ -const Label = require('../../../../components/CCLabel'); -const ttfAssembler = require('./ttf'); -const bmfontAssembler = require('./bmfont'); +// const Label = require('../../../../components/CCLabel'); +// const ttfAssembler = require('./ttf'); +// const bmfontAssembler = require('./bmfont'); +import { LabelComponent} from '../../components/label-component'; +import { ttf } from './ttf'; +// import bmfontAssembler from './bmfont'; -var labelAssembler = { +const labelAssembler = { getAssembler (comp) { - let assembler = ttfAssembler; - + const assembler = ttf; + if (comp.font instanceof cc.BitmapFont) { - assembler = bmfontAssembler; + // assembler = bmfontAssembler; } return assembler; }, // Skip invalid labels (without own _assembler) - updateRenderData (label) { - return label.__allocedDatas; - } + // updateRenderData(label) { + // return label.__allocedDatas; + // } }; -Label._assembler = labelAssembler; +export { + labelAssembler, +}; -module.exports = labelAssembler; \ No newline at end of file +LabelComponent.Assembler = labelAssembler; diff --git a/cocos/3d/ui/assembler/label/ttf.ts b/cocos/3d/ui/assembler/label/ttf.ts new file mode 100644 index 0000000000..edd7a7a8a4 --- /dev/null +++ b/cocos/3d/ui/assembler/label/ttf.ts @@ -0,0 +1,85 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 ttfUtls from '../../../../2d/renderer/utils/label/ttf'; +import * as js from '../../../../core/utils/js'; +import { RenderData } from '../../../../renderer/ui/renderData'; +import { UI } from '../../../../renderer/ui/ui'; +import { LabelComponent } from '../../components/label-component'; +import { IAssembler} from '../assembler'; +import { fillMeshVertices3D } from '../utils'; + +const WHITE = cc.color(255, 255, 255, 255); + +export const ttf: IAssembler = { + useModel: false, + + createData (comp: LabelComponent) { + const renderData: RenderData|null = comp.requestRenderData(); + + renderData!.dataLength = 4; + renderData!.vertexCount = 4; + renderData!.indiceCount = 6; + + const datas = renderData!.datas; + datas[0].u = 0; + datas[0].v = 1; + datas[1].u = 1; + datas[1].v = 1; + datas[2].u = 0; + datas[2].v = 0; + datas[3].u = 1; + datas[3].v = 0; + return renderData as RenderData; + }, + + fillBuffers (comp: LabelComponent, /*renderer*/buffer: UI) { + fillMeshVertices3D(comp.node, /*renderer._quadBuffer3D*/buffer, comp.renderData, WHITE); + }, + + updateVerts (comp: LabelComponent) { + 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 datas = renderData!.datas; + datas[0].x = -appx; + datas[0].y = -appy; + datas[1].x = width - appx; + datas[1].y = -appy; + datas[2].x = -appx; + datas[2].y = height - appy; + datas[3].x = width - appx; + datas[3].y = height - appy; + }, + + updateRenderData (comp: LabelComponent) {}, +}; + +js.addon(ttf, ttfUtls); diff --git a/cocos/3d/ui/assembler/mask-assembler.ts b/cocos/3d/ui/assembler/mask-assembler.ts new file mode 100644 index 0000000000..2b2f09747f --- /dev/null +++ b/cocos/3d/ui/assembler/mask-assembler.ts @@ -0,0 +1,213 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { vec3 } from '../../../core/vmath'; +import { GFXComparisonFunc, GFXStencilOp } from '../../../gfx/define'; +import { IUIRenderData, UI } from '../../../renderer/ui/ui'; +import { Material } from '../../assets/material'; +import { IGeometry } from '../../primitive/define'; +import { MaskComponent } from '../components/mask-component'; +import { IAssembler } from './assembler'; + +interface IStencilState { + stencilTest?: boolean; + func?: GFXComparisonFunc; + readMask?: number; + writeMask?: number; + failOp?: GFXStencilOp; + zFailOp?: GFXStencilOp; + passOp?: GFXStencilOp; + ref?: number; +} + +interface IStencilStateUpdate { + func: GFXComparisonFunc; + writeMask: number; + ref: number; +} + +function overrideStencilState (material: Material, state: IStencilState) { + material.overridePipelineStates({ + depthStencilState: { + stencilTestFront: state.stencilTest, + stencilFuncFront: state.func, + stencilReadMaskFront: state.readMask, + stencilWriteMaskFront: state.writeMask, + stencilFailOpFront: state.failOp, + stencilZFailOpFront: state.zFailOp, + stencilPassOpFront: state.passOp, + stencilRefFront: state.ref, + stencilTestBack: state.stencilTest, + stencilFuncBack: state.func, + stencilReadMaskBack: state.readMask, + stencilWriteMaskBack: state.writeMask, + stencilFailOpBack: state.failOp, + stencilZFailOpBack: state.zFailOp, + stencilPassOpBack: state.passOp, + stencilRefBack: state.ref, + }, + }); +} + +function updateDynamicStencilStates (material: Material, state: IStencilStateUpdate) { + +} + +class StencilManager { + private _maskStack: MaskComponent[] = []; + + public enter (mask: MaskComponent) { + this._maskStack.push(mask); + } + + public exit () { + this._maskStack.pop(); + } + + public updateMaskMaterial (material: Material) { + updateDynamicStencilStates(material, { + func: GFXComparisonFunc.ALWAYS, + writeMask: this._protectAncestorMasks(), + ref: this._getWriteMaskForTopMask(), + }); + } + + public updateClearMaskMaterial (material: Material) { + updateDynamicStencilStates(material, { + func: GFXComparisonFunc.ALWAYS, + writeMask: this._protectAncestorMasks(), + ref: 0, + }); + } + + private _readAncestorMasks (): number { + let result = 0; + this._maskStack.forEach((mask, iBit) => { + result |= (1 << iBit); + }); + return result; + } + + private _protectAncestorMasks (): number { + return ~this._readAncestorMasks(); + } + + private _getWriteMaskForTopMask (): number { + return 1 << this._maskStack.length; + } +} + +const stencilManager = new StencilManager(); + +export const maskAssembler: IAssembler = { + fillBuffers (mask: MaskComponent, ui: UI) { + stencilManager.enter(mask); + + const maskGeometry = mask._getMaskGeometry(); + const maskMaterial = mask._getMaskMaterial(); + if (maskGeometry && maskMaterial) { + const meshBuffer = createMeshBuffer(ui, maskGeometry); + const nVert = Math.floor(maskGeometry.positions.length / 3); + const v = new vec3(); + const worldMatrix = mask.node.getWorldMatrix(); + for (let i = 0; i < nVert; ++i) { + vec3.set(v, + maskGeometry.positions[3 * i + 0], + maskGeometry.positions[3 * i + 1], + maskGeometry.positions[3 * i + 2]); + vec3.transformMat4(v, v, worldMatrix); + meshBuffer.vData![3 * i + 0] = v.x; + meshBuffer.vData![3 * i + 1] = v.y; + meshBuffer.vData![3 * i + 2] = v.z; + } + const maskRenderData = ui.createUIRenderData() as IUIRenderData; + maskRenderData.meshBuffer = meshBuffer; + maskRenderData.material = maskMaterial; + ui.addToQueue(maskRenderData); + } + }, +}; + +export const maskEndAssembler: IAssembler = { + fillBuffers (mask: MaskComponent, ui: UI) { + stencilManager.exit(); + + const clearGeometry = mask._getClearGeometry(); + const clearMaterial = mask._getClearMaterial(); + if (clearGeometry && clearMaterial) { + const meshBuffer = createMeshBuffer(ui, clearGeometry); + meshBuffer.vData!.set(clearGeometry.positions); + const clearMaskRenderData = ui.createUIRenderData() as IUIRenderData; + clearMaskRenderData.meshBuffer = meshBuffer; + clearMaskRenderData.material = clearMaterial; + } + }, +}; + +export function setupMaskMaterial (material: Material) { + overrideStencilState(material, { + stencilTest: true, + func: GFXComparisonFunc.ALWAYS, + readMask: 0xffffffff, + failOp: GFXStencilOp.KEEP, + zFailOp: GFXStencilOp.KEEP, + passOp: GFXStencilOp.REPLACE, + }); +} + +export function setupClearMaskMaterial (material: Material) { + overrideStencilState(material, { + stencilTest: true, + func: GFXComparisonFunc.ALWAYS, + readMask: 0xffffffff, + failOp: GFXStencilOp.KEEP, + zFailOp: GFXStencilOp.KEEP, + passOp: GFXStencilOp.REPLACE, + ref: 0, + }); +} + +export function setupMaskTargetMaterial (material: Material) { + overrideStencilState(material, { + stencilTest: true, + func: GFXComparisonFunc.NOT_EQUAL, + readMask: 0xffffffff, + writeMask: 0xffffffff, + failOp: GFXStencilOp.KEEP, + zFailOp: GFXStencilOp.KEEP, + passOp: GFXStencilOp.KEEP, + ref: 0, + }); +} + +function createMeshBuffer (ui: UI, geometry: IGeometry) { + const nVert = Math.floor(geometry.positions.length / 3); + const meshBuffer = ui.createBuffer(nVert, geometry.indices ? geometry.indices.length : 0); + if (geometry.indices) { + meshBuffer.iData!.set(geometry.indices); + } + // geometry.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : geometry.primitiveMode; + return meshBuffer; +} diff --git a/cocos/3d/ui/assembler/sprite/bar-filled.ts b/cocos/3d/ui/assembler/sprite/bar-filled.ts new file mode 100644 index 0000000000..c039b5d77a --- /dev/null +++ b/cocos/3d/ui/assembler/sprite/bar-filled.ts @@ -0,0 +1,298 @@ +/**************************************************************************** + 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. + ****************************************************************************/ +// @ts-check +import { SpriteComponent } from '../../components/sprite-component'; +const FillType = SpriteComponent.FillType; + +// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); +import { Mat4 } from '../../../../core/value-types'; +import { vec3 } from '../../../../core/vmath/index'; +import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; +import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; +import { Node } from '../../../../scene-graph/node'; +import { MeshBuffer } from '../../mesh-buffer'; +import { IAssembler } from '../assembler'; +import { fillVerticesWithoutCalc3D } from '../utils'; + +const matrix = new Mat4(); + +export const barFilled: IAssembler = { + useModel: false, + updateRenderData (sprite: SpriteComponent) { + const frame = sprite.spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + // if (frame) { + // if (!frame._original && dynamicAtlasManager) { + // dynamicAtlasManager.insertSpriteFrame(frame); + // } + // if (sprite._material._texture !== frame._texture) { + // sprite._activateMaterial(); + // } + // } + + const renderData = sprite.renderData; + if (renderData && frame) { + const uvDirty = renderData.uvDirty; + const vertDirty = renderData.vertDirty; + + if (!uvDirty && !vertDirty) { + // return sprite.__allocedDatas; + return; + } + + let fillStart = sprite._fillStart; + let fillRange = sprite._fillRange; + + if (fillRange < 0) { + fillStart += fillRange; + fillRange = -fillRange; + } + + fillRange = fillStart + fillRange; + + fillStart = fillStart > 1.0 ? 1.0 : fillStart; + fillStart = fillStart < 0.0 ? 0.0 : fillStart; + + fillRange = fillRange > 1.0 ? 1.0 : fillRange; + fillRange = fillRange < 0.0 ? 0.0 : fillRange; + fillRange = fillRange - fillStart; + fillRange = fillRange < 0 ? 0 : fillRange; + + let fillEnd = fillStart + fillRange; + fillEnd = fillEnd > 1 ? 1 : fillEnd; + + if (uvDirty) { + this.updateUVs!(sprite, fillStart, fillEnd); + } + if (vertDirty) { + this.updateVerts(sprite, fillStart, fillEnd); + this.updateWorldVerts!(sprite); + } + } + }, + + updateUVs (sprite: SpriteComponent, fillStart: number, fillEnd: number) { + const spriteFrame = sprite.spriteFrame; + const renderData = sprite.renderData; + const datas = renderData!.datas; + + // build uvs + const atlasWidth = spriteFrame!.width; + const atlasHeight = spriteFrame!.height; + const textureRect = spriteFrame!.getRect(); + // uv computation should take spritesheet into account. + let ul = 0; + let vb = 0; + let ur = 0; + let vt = 0; + let quadUV0 = 0; + let quadUV1 = 0; + let quadUV2 = 0; + let quadUV3 = 0; + let quadUV4 = 0; + let quadUV5 = 0; + let quadUV6 = 0; + let quadUV7 = 0; + if (spriteFrame!.isRotated) { + ul = (textureRect.x) / atlasWidth; + vb = (textureRect.y + textureRect.width) / atlasHeight; + ur = (textureRect.x + textureRect.height) / atlasWidth; + vt = (textureRect.y) / atlasHeight; + + quadUV0 = quadUV2 = ul; + quadUV4 = quadUV6 = ur; + quadUV3 = quadUV7 = vb; + quadUV1 = quadUV5 = vt; + } else { + ul = (textureRect.x) / atlasWidth; + vb = (textureRect.y + textureRect.height) / atlasHeight; + ur = (textureRect.x + textureRect.width) / atlasWidth; + vt = (textureRect.y) / atlasHeight; + + quadUV0 = quadUV4 = ul; + quadUV2 = quadUV6 = ur; + quadUV1 = quadUV3 = vb; + quadUV5 = quadUV7 = vt; + } + + switch (sprite.fillType) { + case FillType.HORIZONTAL: + // datas[0].u = ul + (ur - ul) * fillStart; + // datas[0].v = vb; + // datas[1].u = ul + (ur - ul) * fillEnd; + // datas[1].v = vb; + // datas[2].u = ul + (ur - ul) * fillStart; + // datas[2].v = vt; + // datas[3].u = ul + (ur - ul) * fillEnd; + // datas[3].v = vt; + + datas[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart; + datas[0].v = quadUV1 + (quadUV3 - quadUV1) * fillStart; + datas[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd; + datas[1].v = quadUV1 + (quadUV3 - quadUV1) * fillEnd; + datas[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart; + datas[2].v = quadUV5 + (quadUV7 - quadUV5) * fillStart; + datas[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd; + datas[3].v = quadUV5 + (quadUV7 - quadUV5) * fillEnd; + break; + case FillType.VERTICAL: + // datas[0].u = ul; + // datas[0].v = vb + (vt - vb) * fillStart; + // datas[1].u = ur; + // datas[1].v = vb + (vt - vb) * fillStart; + // datas[2].u = ul; + // datas[2].v = vb + (vt - vb) * fillEnd; + // datas[3].u = ur; + // datas[3].v = vb + (vt - vb) * fillEnd; + + datas[0].u = quadUV0 + (quadUV4 - quadUV0) * fillStart; + datas[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart; + datas[1].u = quadUV2 + (quadUV6 - quadUV2) * fillStart; + datas[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart; + datas[2].u = quadUV0 + (quadUV4 - quadUV0) * fillEnd; + datas[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd; + datas[3].u = quadUV2 + (quadUV6 - quadUV2) * fillEnd; + datas[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd; + break; + default: + cc.errorID(2626); + break; + } + + renderData!.uvDirty = false; + }, + + updateVerts (sprite: SpriteComponent, fillStart: number, fillEnd: number) { + 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; + + let l = -appx; + let b = -appy; + let r = width - appx; + let t = height - appy; + + let progressStart = 0; + let progressEnd = 0; + switch (sprite._fillType) { + case FillType.HORIZONTAL: + progressStart = l + (r - l) * fillStart; + progressEnd = l + (r - l) * fillEnd; + + l = progressStart; + r = progressEnd; + break; + case FillType.VERTICAL: + progressStart = b + (t - b) * fillStart; + progressEnd = b + (t - b) * fillEnd; + + b = progressStart; + t = progressEnd; + break; + default: + cc.errorID(2626); + break; + } + + datas[0].x = l; + datas[0].y = b; + datas[1].x = r; + datas[1].y = b; + datas[2].x = l; + datas[2].y = t; + datas[3].x = r; + datas[3].y = t; + + renderData!.vertDirty = false; + }, + + createData (sprite: SpriteComponent) { + const renderData: RenderData|null = sprite.requestRenderData(); + // 0-4 for world verts + // 5-8 for local verts + renderData!.dataLength = 8; + renderData!.vertexCount = 4; + renderData!.indiceCount = 6; + + const datas = renderData!.datas; + for (const data of datas) { + data.z = 0; + } + + return renderData as RenderData; + }, + + updateWorldVerts (sprite: SpriteComponent) { + const node = sprite.node; + const datas = sprite.renderData!.datas; + + // node._updateWorldMatrix(); + // const matrix = node._worldMatrix; + for (let i = 0; i < 4; i++) { + const local = datas[i + 4]; + const world = datas[i]; + vec3.transformMat4(world, local, matrix); + } + }, + + fillBuffers (sprite: SpriteComponent, renderer: UI) { + const buffer: MeshBuffer = renderer.createBuffer( + sprite.renderData!.vertexCount, + sprite.renderData!.indiceCount, + ); + const commitBuffer: IUIRenderData = renderer.createUIRenderData(); + // if (renderer.worldMatDirty) { + // this.updateWorldVerts(sprite); + // } + + // buffer + let indiceOffset: number = buffer.indiceOffset; + const vertexId: number = buffer.vertexOffset; + + const node = sprite.node; + fillVerticesWithoutCalc3D(node, buffer, sprite.renderData, sprite.color); + + // buffer data may be realloc, need get reference after request. + const ibuf = buffer.iData; + ibuf![indiceOffset++] = vertexId; + ibuf![indiceOffset++] = vertexId + 1; + ibuf![indiceOffset++] = vertexId + 2; + ibuf![indiceOffset++] = vertexId + 1; + ibuf![indiceOffset++] = vertexId + 3; + ibuf![indiceOffset++] = vertexId + 2; + + commitBuffer.meshBuffer = buffer; + commitBuffer.material = sprite.material!; + commitBuffer.texture = sprite.spriteFrame!; + commitBuffer.priority = sprite.priority; + renderer.addToQueue(commitBuffer); + }, +}; diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/index.js b/cocos/3d/ui/assembler/sprite/index.ts similarity index 68% rename from cocos/2d/renderer/webgl/assemblers/sprite/index.js rename to cocos/3d/ui/assembler/sprite/index.ts index c59947b09c..bd8a7e2e81 100644 --- a/cocos/2d/renderer/webgl/assemblers/sprite/index.js +++ b/cocos/3d/ui/assembler/sprite/index.ts @@ -23,42 +23,43 @@ THE SOFTWARE. ****************************************************************************/ -const Sprite = require('../../../../components/CCSprite'); +// const Sprite = require('../../../../components/CCSprite'); +import { SpriteComponent } from '../../components/sprite-component'; -const SpriteType = Sprite.Type; -const FillType = Sprite.FillType; +const SpriteType = SpriteComponent.Type; +const FillType = SpriteComponent.FillType; -const simpleRenderUtil = require('./simple'); -const slicedRenderUtil = require('./sliced'); -const tiledRenderUtil = require('./tiled'); -const radialFilledRenderUtil = require('./radial-filled'); -const barFilledRenderUtil = require('./bar-filled'); -const meshRenderUtil = require('./mesh'); +import { simple } from './simple'; +import { sliced } from './sliced'; +import { tilled } from './tiled'; +import { radialFilled } from './radial-filled'; +import { barFilled } from './bar-filled'; +import { Utils } from 'cannon'; +// import meshRenderUtil from './mesh'; // Inline all type switch to avoid jit deoptimization during inlined function change -let spriteAssembler = { +const spriteAssembler = { getAssembler (sprite) { - let util = simpleRenderUtil; - + let util = simple; + switch (sprite.type) { case SpriteType.SLICED: - util = slicedRenderUtil; + util = sliced; break; case SpriteType.TILED: - util = tiledRenderUtil; + util = tilled; break; case SpriteType.FILLED: if (sprite._fillType === FillType.RADIAL) { - util = radialFilledRenderUtil; - } - else { - util = barFilledRenderUtil; + util = radialFilled; + } else { + util = barFilled; } break; - case SpriteType.MESH: - util = meshRenderUtil; - break; + // case SpriteType.MESH: + // util = meshRenderUtil; + // break; } return util; @@ -67,9 +68,11 @@ let spriteAssembler = { // Skip invalid sprites (without own _assembler) updateRenderData (sprite) { return sprite.__allocedDatas; - } + }, }; -Sprite._assembler = spriteAssembler; +export { + spriteAssembler, +}; -module.exports = spriteAssembler; +SpriteComponent.Assembler = spriteAssembler; diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/mesh.js b/cocos/3d/ui/assembler/sprite/mesh.js similarity index 72% rename from cocos/2d/renderer/webgl/assemblers/sprite/mesh.js rename to cocos/3d/ui/assembler/sprite/mesh.js index e8f024b84b..8ad6bae97f 100644 --- a/cocos/2d/renderer/webgl/assemblers/sprite/mesh.js +++ b/cocos/3d/ui/assembler/sprite/mesh.js @@ -23,28 +23,28 @@ THE SOFTWARE. ****************************************************************************/ -const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); +// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); - module.exports = { +let mesh = { useModel: false, - createData (sprite) { + createData(sprite) { return sprite.requestRenderData(); }, - updateRenderData (sprite) { + updateRenderData(sprite) { let frame = sprite.spriteFrame; - + // TODO: Material API design and export from editor could affect the material activation process // need to update the logic here - if (frame) { - if (!frame._original && dynamicAtlasManager) { - dynamicAtlasManager.insertSpriteFrame(frame); - } - if (sprite._material._texture !== frame._texture) { - sprite._activateMaterial(); - } - } + // if (frame) { + // if (!frame._original && dynamicAtlasManager) { + // dynamicAtlasManager.insertSpriteFrame(frame); + // } + // if (sprite._material._texture !== frame._texture) { + // sprite._activateMaterial(); + // } + // } let renderData = sprite._renderData; if (renderData && frame) { @@ -53,7 +53,7 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); if (renderData.vertexCount !== vertices.x.length) { renderData.vertexCount = vertices.x.length; renderData.indiceCount = vertices.triangles.length; - + // 1 for world vertices, 2 for local vertices renderData.dataLength = renderData.vertexCount * 2; @@ -72,12 +72,7 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); } }, - updateUVs (sprite) { - let material = sprite.getMaterial(); - let texture = material.effect.getProperty('texture'); - let texw = texture._width, - texh = texture._height; - + updateUVs(sprite) { let vertices = sprite.spriteFrame.vertices, u = vertices.nu, v = vertices.nv; @@ -93,7 +88,7 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); renderData.uvDirty = false; }, - updateVerts (sprite) { + updateVerts(sprite) { let node = sprite.node, contentWidth = Math.abs(node.width), contentHeight = Math.abs(node.height), @@ -112,87 +107,72 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); offsetY = frame._offset.y, trimX = offsetX + (originalWidth - rectWidth) / 2, trimY = offsetY + (originalHeight - rectHeight) / 2; - - let scaleX = contentWidth / (sprite.trim ? rectWidth : originalWidth), + + let scaleX = contentWidth / (sprite.trim ? rectWidth : originalWidth), scaleY = contentHeight / (sprite.trim ? rectHeight : originalHeight); let renderData = sprite._renderData; let data = renderData._data; - + if (!sprite.trim) { for (let i = 0, l = x.length; i < l; i++) { - let vertice = data[i+l]; + let vertice = data[i + l]; vertice.x = (x[i]) * scaleX - appx; vertice.y = (originalHeight - y[i]) * scaleY - appy; } } else { for (let i = 0, l = x.length; i < l; i++) { - let vertice = data[i+l]; + let vertice = data[i + l]; vertice.x = (x[i] - trimX) * scaleX - appx; vertice.y = (originalHeight - y[i] - trimY) * scaleY - appy; } } - + renderData.vertDirty = false; }, - updateWorldVerts (sprite) { + updateWorldVerts(sprite) { let node = sprite.node, renderData = sprite._renderData, data = renderData._data; + + node._updateWorldMatrix(); let matrix = node._worldMatrix; - let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; - for (let i = 0, l = renderData.vertexCount; i < l; i++) { - let local = data[i+l]; + let local = data[i + l]; let world = data[i]; - world.x = local.x * a + local.y * c + tx; - world.y = local.x * b + local.y * d + ty; + vec3.set(vec3_temp, local.x, local.y, 0); + vec3.transformMat4(world, vec3_temp, matrix); } }, - fillBuffers (sprite, renderer) { - let node = sprite.node, - renderData = sprite._renderData, - data = renderData._data; - + fillBuffers(sprite, /*renderer*/buffer) { let vertices = sprite.spriteFrame.vertices; if (!vertices) { return; } - + // update world verts - if (renderer.worldMatDirty) { - this.updateWorldVerts(sprite); - } + // if (renderer.worldMatDirty) { + this.updateWorldVerts(sprite); + // } // buffer - let buffer = renderer._meshBuffer, - vertexOffset = buffer.byteOffset >> 2; - - let indiceOffset = buffer.indiceOffset, + let /*buffer = renderer._meshBuffer3D,*/ + indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; - buffer.request(renderData.vertexCount, renderData.indiceCount); + let node = sprite.node; + fillVerticesWithoutCalc3D(node, buffer, sprite._renderData, sprite._color._val); // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - ibuf = buffer._iData; - - for (let i = 0, l = renderData.vertexCount; i < l; i++) { - let vertice = data[i]; - vbuf[vertexOffset++] = vertice.x; - vbuf[vertexOffset++] = vertice.y; - vbuf[vertexOffset++] = vertice.u; - vbuf[vertexOffset++] = vertice.v; - } - + let ibuf = buffer._iData; let triangles = vertices.triangles; - for (let i = 0, l = triangles.length; i < l; i++) { ibuf[indiceOffset++] = vertexId + triangles[i]; } }, -}; \ No newline at end of file +}; + +export default mesh; diff --git a/cocos/3d/ui/assembler/sprite/radial-filled.ts b/cocos/3d/ui/assembler/sprite/radial-filled.ts new file mode 100644 index 0000000000..2175eeac93 --- /dev/null +++ b/cocos/3d/ui/assembler/sprite/radial-filled.ts @@ -0,0 +1,387 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); +import { Color, Vec2 } from '../../../../core/value-types'; +import { RenderData } from '../../../../renderer/ui/renderData'; +import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; +import { SpriteComponent } from '../../components/sprite-component'; +import { MeshBuffer } from '../../mesh-buffer'; +import { IAssembler } from '../assembler'; +import { fillVertices3D } from '../utils'; + +const PI_2 = Math.PI * 2; + +const _vertPos: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; +const _vertices: number[] = [0, 0, 0, 0]; +const _uvs: number[] = [0, 0, 0, 0, 0, 0, 0, 0]; +const _intersectPoint_1: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; +const _intersectPoint_2: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; +const _center = new Vec2(); +const _triangles: [[number, number], [number, number], [number, number], [number, number]] = [ + [0, 0], [0, 0], [0, 0], [0, 0], +]; + +function _calcInsectedPoints (left, right, bottom, top, center, angle, intersectPoints) { + // left bottom, right, top + const sinAngle = Math.sin(angle); + const cosAngle = Math.cos(angle); + let tanAngle = 0; + let cotAngle = 0; + if (cosAngle !== 0) { + tanAngle = sinAngle / cosAngle; + // calculate right and left + if ((left - center.x) * cosAngle > 0) { + const yleft = center.y + tanAngle * (left - center.x); + intersectPoints[0].x = left; + intersectPoints[0].y = yleft; + } + if ((right - center.x) * cosAngle > 0) { + const yright = center.y + tanAngle * (right - center.x); + + intersectPoints[2].x = right; + intersectPoints[2].y = yright; + } + + } + + if (sinAngle !== 0) { + cotAngle = cosAngle / sinAngle; + // calculate top and bottom + if ((top - center.y) * sinAngle > 0) { + const xtop = center.x + cotAngle * (top - center.y); + intersectPoints[3].x = xtop; + intersectPoints[3].y = top; + } + if ((bottom - center.y) * sinAngle > 0) { + const xbottom = center.x + cotAngle * (bottom - center.y); + intersectPoints[1].x = xbottom; + intersectPoints[1].y = bottom; + } + + } +} + +function _calculateVertices (sprite) { + const node = sprite.node; + const width = node.width; + const height = node.height; + const appx = node.anchorX * width; + const appy = node.anchorY * height; + + const l = -appx; + const b = -appy; + const r = width - appx; + const t = height - appy; + + const vertices = _vertices; + vertices[0] = l; + vertices[1] = b; + vertices[2] = r; + vertices[3] = t; + + const fillCenter = sprite._fillCenter; + const cx = _center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l; + const cy = _center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t - b) + b; + + _vertPos[0].x = _vertPos[3].x = l; + _vertPos[1].x = _vertPos[2].x = r; + _vertPos[0].y = _vertPos[1].y = b; + _vertPos[2].y = _vertPos[3].y = t; + + for (let num of _triangles) { + num = [0, 0]; + } + + if (cx !== vertices[0]) { + _triangles[0] = [3, 0]; + } + if (cx !== vertices[2]) { + _triangles[2] = [1, 2]; + } + if (cy !== vertices[1]) { + _triangles[1] = [0, 1]; + } + if (cy !== vertices[3]) { + _triangles[3] = [2, 3]; + } +} + +function _calculateUVs (spriteFrame) { + const atlasWidth = spriteFrame.width; + const atlasHeight = spriteFrame.height; + const textureRect = spriteFrame._rect; + + let u0 = 0; + let u1 = 0; + let v0 = 0; + let v1 = 0; + const uvs = _uvs; + + if (spriteFrame._rotated) { + u0 = (textureRect.x) / atlasWidth; + u1 = (textureRect.x + textureRect.height) / atlasWidth; + + v0 = (textureRect.y) / atlasHeight; + v1 = (textureRect.y + textureRect.width) / atlasHeight; + + uvs[0] = uvs[2] = u0; + uvs[4] = uvs[6] = u1; + uvs[3] = uvs[7] = v1; + uvs[1] = uvs[5] = v0; + } else { + u0 = (textureRect.x) / atlasWidth; + u1 = (textureRect.x + textureRect.width) / atlasWidth; + + v0 = (textureRect.y) / atlasHeight; + v1 = (textureRect.y + textureRect.height) / atlasHeight; + + uvs[0] = uvs[4] = u0; + uvs[2] = uvs[6] = u1; + uvs[1] = uvs[3] = v1; + uvs[5] = uvs[7] = v0; + } +} + +function _getVertAngle (start, end) { + const placementX = end.x - start.x; + const placementY = end.y - start.y; + + if (placementX === 0 && placementY === 0) { + return 0; + } else if (placementX === 0) { + if (placementY > 0) { + return Math.PI * 0.5; + } else { + return Math.PI * 1.5; + } + } else { + let angle = Math.atan(placementY / placementX); + if (placementX < 0) { + angle += Math.PI; + } + + return angle; + } +} + +function _generateTriangle (data, offset, vert0, vert1, vert2) { + const vertices = _vertices; + const v0x = vertices[0]; + const v0y = vertices[1]; + const v1x = vertices[2]; + const v1y = vertices[3]; + + data[offset].x = vert0.x; + data[offset].y = vert0.y; + data[offset + 1].x = vert1.x; + data[offset + 1].y = vert1.y; + data[offset + 2].x = vert2.x; + data[offset + 2].y = vert2.y; + + let progressX; + let progressY; + progressX = (vert0.x - v0x) / (v1x - v0x); + progressY = (vert0.y - v0y) / (v1y - v0y); + _generateUV(progressX, progressY, data, offset); + + progressX = (vert1.x - v0x) / (v1x - v0x); + progressY = (vert1.y - v0y) / (v1y - v0y); + _generateUV(progressX, progressY, data, offset + 1); + + progressX = (vert2.x - v0x) / (v1x - v0x); + progressY = (vert2.y - v0y) / (v1y - v0y); + _generateUV(progressX, progressY, data, offset + 2); +} + +function _generateUV (progressX, progressY, data, offset) { + const uvs = _uvs; + const px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX; + const px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX; + const py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX; + const py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX; + const uv = data[offset]; + uv.u = px1 + (px2 - px1) * progressY; + uv.v = py1 + (py2 - py1) * progressY; +} + +export const radialFilled: IAssembler = { + useModel: false, + + createData (sprite: SpriteComponent) { + return sprite.requestRenderData(); + }, + + updateRenderData (sprite: SpriteComponent) { + const frame = sprite.spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + // if (frame) { + // if (!frame._original && dynamicAtlasManager) { + // dynamicAtlasManager.insertSpriteFrame(frame); + // } + // if (sprite._material._texture !== frame._texture) { + // sprite._activateMaterial(); + // } + // } + + const renderData = sprite.renderData; + if (renderData && frame) { + if (renderData.vertDirty || renderData.uvDirty) { + const datas = renderData.datas; + + let fillStart = sprite._fillStart; + let fillRange = sprite._fillRange; + if (fillRange < 0) { + fillStart += fillRange; + fillRange = -fillRange; + } + + // do round fill start [0,1), include 0, exclude 1 + while (fillStart >= 1.0) { fillStart -= 1.0; } + while (fillStart < 0.0) { fillStart += 1.0; } + + fillStart *= PI_2; + fillRange *= PI_2; + const fillEnd = fillStart + fillRange; + + // build vertices + _calculateVertices(sprite); + // build uvs + _calculateUVs(frame); + + _calcInsectedPoints( + _vertices[0], _vertices[2], + _vertices[1], _vertices[3], + _center, fillStart, _intersectPoint_1, + ); + _calcInsectedPoints( + _vertices[0], _vertices[2], + _vertices[1], _vertices[3], + _center, fillStart + fillRange, _intersectPoint_2, + ); + + let offset = 0; + for (let triangleIndex = 0; triangleIndex < 4; ++triangleIndex) { + const triangle = _triangles[triangleIndex]; + if (!triangle) { + continue; + } + // all in + if (fillRange >= PI_2) { + renderData.dataLength = offset + 3; + _generateTriangle(datas, offset, _center, _vertPos[triangle[0]], _vertPos[triangle[1]]); + offset += 3; + continue; + } + // test against + let startAngle = _getVertAngle(_center, _vertPos[triangle[0]]); + let endAngle = _getVertAngle(_center, _vertPos[triangle[1]]); + if (endAngle < startAngle) { endAngle += PI_2; } + startAngle -= PI_2; + endAngle -= PI_2; + // testing + for (let testIndex = 0; testIndex < 3; ++testIndex) { + if (startAngle >= fillEnd) { + // all out + } else if (startAngle >= fillStart) { + renderData.dataLength = offset + 3; + if (endAngle >= fillEnd) { + // startAngle to fillEnd + _generateTriangle( + datas, offset, _center, + _vertPos[triangle[0]], + _intersectPoint_2[triangleIndex], + ); + } else { + // startAngle to endAngle + _generateTriangle(datas, offset, _center, + _vertPos[triangle[0]], _vertPos[triangle[1]], + ); + } + offset += 3; + } else { + // startAngle < fillStart + if (endAngle <= fillStart) { + // all out + } else if (endAngle <= fillEnd) { + renderData.dataLength = offset + 3; + // fillStart to endAngle + _generateTriangle(datas, offset, _center, + _intersectPoint_1[triangleIndex], + _vertPos[triangle[1]], + ); + offset += 3; + } else { + renderData.dataLength = offset + 3; + // fillStart to fillEnd + _generateTriangle(datas, offset, _center, + _intersectPoint_1[triangleIndex], + _intersectPoint_2[triangleIndex], + ); + offset += 3; + } + } + // add 2 * PI + startAngle += PI_2; + endAngle += PI_2; + } + } + + renderData.indiceCount = renderData.vertexCount = offset; + renderData.vertDirty = renderData.uvDirty = false; + } + } + }, + + fillBuffers (comp: SpriteComponent, renderer: UI) { + const buffer: MeshBuffer = renderer.createBuffer( + comp.renderData!.vertexCount, + comp.renderData!.indiceCount, + ); + const commitBuffer: IUIRenderData = renderer.createUIRenderData(); + + const node = comp.node; + const color: Color = comp.color; + /*buffer = renderer._meshBuffer3D,*/ + const renderData: RenderData|null = comp.renderData; + const indiceOffset = buffer!.indiceOffset; + const vertexId = buffer.vertexOffset; + fillVertices3D(node, buffer, renderData, color); + + // buffer data may be realloc, need get reference after request. + const ibuf = buffer.iData; + for (let i = 0; i < renderData!.dataLength; i++) { + ibuf![indiceOffset + i] = vertexId + i; + } + + commitBuffer.meshBuffer = buffer; + commitBuffer.material = comp.material!; + commitBuffer.texture = comp.spriteFrame!; + commitBuffer.priority = comp.priority; + renderer.addToQueue(commitBuffer); + }, +}; diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts new file mode 100644 index 0000000000..45c66cc429 --- /dev/null +++ b/cocos/3d/ui/assembler/sprite/simple.ts @@ -0,0 +1,197 @@ +/**************************************************************************** + 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 { Color, Vec3 } from '../../../../core/value-types'; +import { vec3 } from '../../../../core/vmath/index'; +import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; +import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; +import { Node } from '../../../../scene-graph/node'; +import { SpriteComponent } from '../../components/sprite-component'; +import { MeshBuffer } from '../../mesh-buffer'; +import { IAssembler } from '../assembler'; +// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); +const matrix = cc.mat4(); +const vec3_temps: Vec3[] = []; +for (let i = 0; i < 4; i++) { + vec3_temps.push(new Vec3()); +} + +export const simple: IAssembler = { + + useModel: false, + + createData (sprite: SpriteComponent) { + const renderData = sprite.requestRenderData(); + renderData!.dataLength = 4; + renderData!.vertexCount = 4; + renderData!.indiceCount = 6; + return renderData as RenderData; + }, + + updateRenderData (sprite: SpriteComponent) { + const frame = sprite.spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + // if (frame) { + // if (!frame._original && dynamicAtlasManager) { + // dynamicAtlasManager.insertSpriteFrame(frame); + // } + // if (sprite._material._texture !== frame._texture) { + // sprite._activateMaterial(); + // } + // } + + const renderData = sprite.renderData; + if (renderData && frame) { + if (renderData.vertDirty) { + this.updateVerts(sprite); + } + } + }, + + fillBuffers (sprite: SpriteComponent, renderer: UI) { + if (sprite === null) { + return; + } + + const buffer: MeshBuffer = renderer.createBuffer( + sprite.renderData!.vertexCount, + sprite.renderData!.indiceCount, + ); + const commitBuffer: IUIRenderData = renderer.createUIRenderData(); + const datas: IRenderData[] = sprite!.renderData!.datas; + const node: Node = sprite.node; + const color: Color = sprite.color; + + node.getWorldMatrix(matrix); + + let vertexOffset: number = buffer.byteOffset >> 2; + let indiceOffset: number = buffer.indiceOffset; + const vertexId: number = buffer.vertexOffset; + + buffer.request(4, 6); + + // buffer data may be realloc, need get reference after request. + const vbuf: Float32Array|null = buffer.vData; + // const uintbuf = buffer.uintVData; + const ibuf: Uint16Array|null = buffer.iData; + + const data0 = datas[0]; + const data3 = datas[3]; + vec3.set(vec3_temps[0], data0.x, data0.y, 0); + vec3.set(vec3_temps[1], data3.x, data0.y, 0); + vec3.set(vec3_temps[2], data0.x, data3.y, 0); + vec3.set(vec3_temps[3], data3.x, data3.y, 0); + + // get uv from sprite frame directly + const uv = sprite!.spriteFrame!.uv; + for (let i = 0; i < 4; i++) { + // vertex + const vertex = vec3_temps[i]; + vec3.transformMat4(vertex, vertex, matrix); + + vbuf![vertexOffset++] = vertex.x; + vbuf![vertexOffset++] = vertex.y; + vbuf![vertexOffset++] = vertex.z; + + // uv + const uvOffset = i * 2; + vbuf![vertexOffset++] = uv[0 + uvOffset]; + vbuf![vertexOffset++] = uv[1 + uvOffset]; + + // color + vbuf![vertexOffset++] = color.r; + vbuf![vertexOffset++] = color.g; + vbuf![vertexOffset++] = color.b; + vbuf![vertexOffset++] = color.a; + // uintbuf[vertexOffset++] = color; + } + + // fill indice data + ibuf![indiceOffset++] = vertexId; + ibuf![indiceOffset++] = vertexId + 1; + ibuf![indiceOffset++] = vertexId + 2; + ibuf![indiceOffset++] = vertexId + 1; + ibuf![indiceOffset++] = vertexId + 3; + ibuf![indiceOffset++] = vertexId + 2; + + commitBuffer.meshBuffer = buffer; + commitBuffer.material = sprite.material!; + commitBuffer.texture = sprite.spriteFrame!; + commitBuffer.priority = sprite.priority; + renderer.addToQueue(commitBuffer); + }, + + updateVerts (sprite: SpriteComponent) { + const renderData: RenderData|null = sprite.renderData; + if (!renderData) { + return; + } + + const node: Node = sprite.node; + const datas: IRenderData[] = renderData.datas; + const cw: number = node.width; + const ch: number = node.height; + const appx: number = node.anchorX * cw; + const appy: number = node.anchorY * ch; + let l: number = 0; + let b: number = 0; + let r: number = 0; + let t: number = 0; + // if (sprite.trim) { + l = -appx; + b = -appy; + r = cw - appx; + t = ch - appy; + // } + // else { + // let frame = sprite.spriteFrame, + // ow = frame._originalSize.width, oh = frame._originalSize.height, + // rw = frame._rect.width, rh = frame._rect.height, + // offset = frame._offset, + // scaleX = cw / ow, scaleY = ch / oh; + // let trimLeft = offset.x + (ow - rw) / 2; + // let trimRight = offset.x - (ow - rw) / 2; + // let trimBottom = offset.y + (oh - rh) / 2; + // let trimTop = offset.y - (oh - rh) / 2; + // l = trimLeft * scaleX - appx; + // b = trimBottom * scaleY - appy; + // r = cw + trimRight * scaleX - appx; + // t = ch + trimTop * scaleY - appy; + // } + + datas[0].x = l; + datas[0].y = b; + // datas[1].x = r; + // datas[1].y = b; + // datas[2].x = l; + // datas[2].y = t; + datas[3].x = r; + datas[3].y = t; + + renderData.vertDirty = false; + }, +}; diff --git a/cocos/3d/ui/assembler/sprite/sliced.ts b/cocos/3d/ui/assembler/sprite/sliced.ts new file mode 100644 index 0000000000..979d3e30a0 --- /dev/null +++ b/cocos/3d/ui/assembler/sprite/sliced.ts @@ -0,0 +1,195 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ + +// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); +import { IUV, SpriteFrame } from '../../../../assets/CCSpriteFrame'; +import { Color, Mat4 } from '../../../../core/value-types'; +import { vec3 } from '../../../../core/vmath/index'; +import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; +import { IUIRenderData } from '../../../../renderer/ui/ui'; +import { Node } from '../../../../scene-graph/node'; +import { SpriteComponent } from '../../components/sprite-component'; +import { MeshBuffer } from '../../mesh-buffer'; +import { IAssembler } from '../assembler'; + +const vec3_temp = vec3.create(); +const matrix = new Mat4(); + +export const sliced: IAssembler = { + useModel: false, + + createData (sprite: SpriteComponent) { + const renderData: RenderData | null = sprite.requestRenderData(); + // 0-4 for local verts + // 5-20 for world verts + renderData!.dataLength = 20; + + renderData!.vertexCount = 16; + renderData!.indiceCount = 54; + return renderData as RenderData; + }, + + updateRenderData (sprite: SpriteComponent) { + const frame = sprite.spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + // if (frame) { + // if (!frame._original && dynamicAtlasManager) { + // dynamicAtlasManager.insertSpriteFrame(frame); + // } + // if (sprite._material._texture !== frame._texture) { + // sprite._activateMaterial(); + // } + // } + + const renderData = sprite.renderData; + if (renderData && frame) { + const vertDirty = renderData.vertDirty; + if (vertDirty) { + this.updateVerts(sprite); + this.updateWorldVerts!(sprite); + } + } + }, + + updateVerts (sprite: SpriteComponent) { + 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 frame: SpriteFrame|null = sprite.spriteFrame; + const leftWidth = frame!.insetLeft; + const rightWidth = frame!.insetRight; + const topHeight = frame!.insetTop; + const bottomHeight = frame!.insetBottom; + + let sizableWidth = width - leftWidth - rightWidth; + let sizableHeight = height - topHeight - bottomHeight; + let xScale = width / (leftWidth + rightWidth); + let yScale = height / (topHeight + bottomHeight); + xScale = (isNaN(xScale) || xScale > 1) ? 1 : xScale; + yScale = (isNaN(yScale) || yScale > 1) ? 1 : yScale; + sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; + sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; + + datas[0].x = -appx; + datas[0].y = -appy; + datas[1].x = leftWidth * xScale - appx; + datas[1].y = bottomHeight * yScale - appy; + datas[2].x = datas[1].x + sizableWidth; + datas[2].y = datas[1].y + sizableHeight; + datas[3].x = width - appx; + datas[3].y = height - appy; + + renderData!.vertDirty = false; + }, + + fillBuffers (sprite: SpriteComponent, renderer) { + // if (renderer.worldMatDirty) { + // this.updateWorldVerts(sprite); + // } + + const buffer: MeshBuffer = renderer.createBuffer( + sprite.renderData!.vertexCount, + sprite.renderData!.indiceCount, + ); + const commitBuffer: IUIRenderData = renderer.createUIRenderData(); + const renderData: RenderData|null = sprite.renderData; + const node: Node = sprite.node; + const color: Color = sprite.color; + const datas: IRenderData[] = renderData!.datas; + + let vertexOffset = buffer.byteOffset >> 2; + const vertexCount = renderData!.vertexCount; + let indiceOffset: number = buffer.indiceOffset; + const vertexId: number = buffer.vertexOffset; + + const uvSliced: IUV[] = sprite!.spriteFrame!.uvSliced; + + buffer.request(vertexCount, renderData!.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf: Float32Array|null = buffer.vData; + // const uintbuf = buffer._uintVData, + const ibuf: Uint16Array|null = buffer.iData; + + // for (let i = 4; i < 20; ++i) { + for (let i = 4; i < 16; ++i) { + const vert = datas[i]; + const uvs = uvSliced[i - 4]; + + vbuf![vertexOffset++] = vert.x; + vbuf![vertexOffset++] = vert.y; + vbuf![vertexOffset++] = vert.z; + vbuf![vertexOffset++] = uvs.u; + vbuf![vertexOffset++] = uvs.v; + vbuf![vertexOffset++] = color.r; + vbuf![vertexOffset++] = color.g; + vbuf![vertexOffset++] = color.b; + vbuf![vertexOffset++] = color.a; + // uintbuf[vertexOffset++] = color; + } + + for (let r = 0; r < 3; ++r) { + for (let c = 0; c < 3; ++c) { + const start = vertexId + r * 4 + c; + ibuf![indiceOffset++] = start; + ibuf![indiceOffset++] = start + 1; + ibuf![indiceOffset++] = start + 4; + ibuf![indiceOffset++] = start + 1; + ibuf![indiceOffset++] = start + 5; + ibuf![indiceOffset++] = start + 4; + } + } + + commitBuffer.meshBuffer = buffer; + commitBuffer.material = sprite.material!; + commitBuffer.texture = sprite.spriteFrame!; + commitBuffer.priority = sprite.priority; + renderer.addToQueue(commitBuffer); + }, + + updateWorldVerts (sprite: SpriteComponent) { + const node: Node = sprite.node; + const datas: IRenderData[] = sprite!.renderData!.datas; + + node.getWorldMatrix(matrix); + for (let row = 0; row < 4; ++row) { + const rowD = datas[row]; + for (let col = 0; col < 4; ++col) { + const colD = datas[col]; + const world = datas[4 + row * 4 + col]; + + vec3.set(vec3_temp, colD.x, rowD.y, 0); + vec3.transformMat4(world, vec3_temp, matrix); + } + } + }, +}; diff --git a/cocos/3d/ui/assembler/sprite/tiled.ts b/cocos/3d/ui/assembler/sprite/tiled.ts new file mode 100644 index 0000000000..234d66da96 --- /dev/null +++ b/cocos/3d/ui/assembler/sprite/tiled.ts @@ -0,0 +1,283 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ + +// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); +import { Mat4, Vec3 } from '../../../../core/value-types'; +import { vec3 } from '../../../../core/vmath/index'; +import { RenderData } from '../../../../renderer/ui/renderData'; +import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; +import { SpriteComponent } from '../../components/sprite-component'; +import { UIRenderComponent } from '../../components/ui-render-component'; +import { MeshBuffer } from '../../mesh-buffer'; +import { IAssembler } from '../assembler'; + +const matrix = new Mat4(); + +const vec3_temps: Vec3[] = []; +for (let i = 0; i < 4; i++) { + vec3_temps.push(new Vec3()); +} + +const _tempVertexOffset = 6; +const _tempUvOffset = 3; +const _tempColorOffset = 5; + +export const tilled: IAssembler = { + useModel: false, + + createData (sprite: UIRenderComponent) { + return sprite.requestRenderData() as RenderData; + }, + + updateRenderData (sprite: SpriteComponent) { + const frame = sprite.spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + // if (frame) { + // if (!frame._original && dynamicAtlasManager) { + // dynamicAtlasManager.insertSpriteFrame(frame); + // } + // if (sprite._material._texture !== frame._texture) { + // sprite._activateMaterial(); + // } + // } + + const renderData = sprite.renderData; + if (!frame || !renderData || + !(renderData.uvDirty || renderData.vertDirty)) { + return; + } + + const node = sprite.node; + // contentWidth = Math.abs(node.width), + // contentHeight = Math.abs(node.height), + const contentWidth = Math.abs(node.width); + const contentHeight = Math.abs(node.height); + const appx = node.anchorX * contentWidth; + const appy = node.anchorY * contentHeight; + // node._updateWorldMatrix(); + + const rect = frame.getRect(); + const rectWidth = rect.width; + const rectHeight = rect.height; + const hRepeat = contentWidth / rectWidth; + const vRepeat = contentHeight / rectHeight; + const row = Math.ceil(vRepeat); + const col = Math.ceil(hRepeat); + + const data = renderData.datas; + renderData.dataLength = Math.max(8, row + 1, col + 1); + + for (let i = 0; i <= col; ++i) { + data[i].x = Math.min(rectWidth * i, contentWidth) - appx; + } + for (let i = 0; i <= row; ++i) { + data[i].y = Math.min(rectHeight * i, contentHeight) - appy; + } + + // update data property + renderData.vertexCount = row * col * 4; + renderData.indiceCount = row * col * 6; + renderData.uvDirty = false; + renderData.vertDirty = false; + }, + + fillBuffers (sprite: SpriteComponent, renderer: UI) { + const buffer: MeshBuffer = renderer.createBuffer( + sprite.renderData!.vertexCount, + sprite.renderData!.indiceCount, + ); + const commitBuffer: IUIRenderData = renderer.createUIRenderData(); + + const node = sprite.node; + const color = sprite.color; + const renderData = sprite.renderData; + const datas = renderData!.datas; + + // buffer + let vertexOffset = buffer.byteOffset >> 2; + let indiceOffset = buffer.indiceOffset; + let vertexId = buffer.vertexOffset; + + buffer.request(renderData!.vertexCount, renderData!.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData, + const ibuf = buffer.iData; + + const rotated = sprite.spriteFrame!.isRotated; + const uv = sprite.spriteFrame!.uv; + const rect = sprite.spriteFrame!.getRect(); + const contentWidth = Math.abs(node.width); + const contentHeight = Math.abs(node.height); + const hRepeat = contentWidth / rect.width; + const vRepeat = contentHeight / rect.height; + const row = Math.ceil(vRepeat); + const col = Math.ceil(hRepeat); + + // const matrix = node._worldMatrix; + + // this.updateVerts(vbuf, vertexOffset, matrix, row, col, datas); + // updataVerts + let x = 0; + let x1 = 0; + let y = 0; + let y1 = 0; + for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { + y = datas[yindex].y; + y1 = datas[yindex + 1].y; + for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { + x = datas[xindex].x; + x1 = datas[xindex + 1].x; + + vec3.set(vec3_temps[0], x, y, 0); + vec3.set(vec3_temps[1], x1, y, 0); + vec3.set(vec3_temps[2], x, y1, 0); + vec3.set(vec3_temps[3], x1, y1, 0); + + for (let i = 0; i < 4; i++) { + const vec3_temp = vec3_temps[i]; + vec3.transformMat4(vec3_temp, vec3_temp, matrix); + const move = i * 6; + vbuf![vertexOffset + move] = vec3_temp.x; + vbuf![vertexOffset + move + 1] = vec3_temp.y; + vbuf![vertexOffset + move + 2] = vec3_temp.z; + } + + vertexOffset += 24; + } + } + + const offset = _tempVertexOffset; + const uvOffset = _tempUvOffset; + const colorOffset = _tempColorOffset; + const offset1 = offset; + const offset2 = offset * 2; + const offset3 = offset * 3; + const offset4 = offset * 4; + let coefu = 0; + let coefv = 0; + for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { + coefv = Math.min(1, vRepeat - yindex); + for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { + coefu = Math.min(1, hRepeat - xindex); + + const vertexOffsetU = vertexOffset + uvOffset; + const vertexOffsetV = vertexOffsetU + 1; + // UV + if (rotated) { + // lb + vbuf![vertexOffsetU] = uv[0]; + vbuf![vertexOffsetV] = uv[1]; + // rb + vbuf![vertexOffsetU + offset1] = uv[0]; + vbuf![vertexOffsetV + offset1] = uv[1] + (uv[7] - uv[1]) * coefu; + // lt + vbuf![vertexOffsetU + offset2] = uv[0] + (uv[6] - uv[0]) * coefv; + vbuf![vertexOffsetV + offset2] = uv[1]; + // rt + vbuf![vertexOffsetU + offset3] = vbuf![vertexOffsetU + offset2]; + vbuf![vertexOffsetV + offset3] = vbuf![vertexOffsetV + offset1]; + } else { + // lb + vbuf![vertexOffsetU] = uv[0]; + vbuf![vertexOffsetV] = uv[1]; + // rb + vbuf![vertexOffsetU + offset1] = uv[0] + (uv[6] - uv[0]) * coefu; + vbuf![vertexOffsetV + offset1] = uv[1]; + // lt + vbuf![vertexOffsetU + offset2] = uv[0]; + vbuf![vertexOffsetV + offset2] = uv[1] + (uv[7] - uv[1]) * coefv; + // rt + vbuf![vertexOffsetU + offset3] = vbuf![vertexOffsetU + offset1]; + vbuf![vertexOffsetV + offset3] = vbuf![vertexOffsetV + offset2]; + } + // TODO: addColor + // color + // uintbuf[vertexOffset + colorOffset] = color; + // uintbuf[vertexOffset + colorOffset + offset1] = color; + // uintbuf[vertexOffset + colorOffset + offset2] = color; + // uintbuf[vertexOffset + colorOffset + offset3] = color; + vertexOffset += offset4; + } + } + + // update indices + const length = renderData!.indiceCount; + for (let i = 0; i < length; i += 6) { + ibuf![indiceOffset++] = vertexId; + ibuf![indiceOffset++] = vertexId + 1; + ibuf![indiceOffset++] = vertexId + 2; + ibuf![indiceOffset++] = vertexId + 1; + ibuf![indiceOffset++] = vertexId + 3; + ibuf![indiceOffset++] = vertexId + 2; + vertexId += 4; + } + + commitBuffer.meshBuffer = buffer; + commitBuffer.material = sprite.material!; + commitBuffer.texture = sprite.spriteFrame!; + commitBuffer.priority = sprite.priority; + renderer.addToQueue(commitBuffer); + }, + + updateVerts (sprite: SpriteComponent) { + // const renderData = sprite.renderData; + // const datas = renderData!.datas; + // const vbuf; + // const vertexOffset; + // sprite.node.getWorldMatrix(matrix); + // const row; + // const col; + // const data; + // let x, x1, y, y1; + // for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { + // y = data[yindex].y; + // y1 = data[yindex + 1].y; + // for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { + // x = data[xindex].x; + // x1 = data[xindex + 1].x; + + // vec3.set(vec3_temps[0], x, y, 0); + // vec3.set(vec3_temps[1], x1, y, 0); + // vec3.set(vec3_temps[2], x, y1, 0); + // vec3.set(vec3_temps[3], x1, y1, 0); + + // for (let i = 0; i < 4; i++) { + // let vec3_temp = vec3_temps[i]; + // vec3.transformMat4(vec3_temp, vec3_temp, matrix); + // let offset = i * 6; + // vbuf[vertexOffset + offset] = vec3_temp.x; + // vbuf[vertexOffset + offset + 1] = vec3_temp.y; + // vbuf[vertexOffset + offset + 2] = vec3_temp.z; + // } + + // vertexOffset += 24; + // } + // } + }, +}; diff --git a/cocos/3d/ui/assembler/utils.ts b/cocos/3d/ui/assembler/utils.ts new file mode 100644 index 0000000000..ba3d32d004 --- /dev/null +++ b/cocos/3d/ui/assembler/utils.ts @@ -0,0 +1,216 @@ + +import { mat4, vec3 } from '../../../core/vmath/index'; + +const vec3_temp = vec3.create(); +const _worldMatrix = mat4.create(); + +export function fillVertices (node, buffer, renderData, color) { + const data = renderData._data; + let vertexOffset = buffer.byteOffset >> 2; + + const vertexCount = renderData.vertexCount; + buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData; + + // let matrix = node._worldMatrix; + node.getWorldMatrix(_worldMatrix); + const matrix = _worldMatrix; + const a = matrix.m00; + const b = matrix.m01; + const c = matrix.m04; + const d = matrix.m05; + const tx = matrix.m12; + const ty = matrix.m13; + for (let i = 0; i < vertexCount; i++) { + const vert = data[i]; + vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; + vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; + vbuf[vertexOffset++] = vert.u; + vbuf[vertexOffset++] = vert.v; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + } +} + +export function fillMeshVertices (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; + + const vertexCount = renderData.vertexCount; + let indiceOffset = buffer.indiceOffset; + const vertexId = buffer.vertexOffset; + + buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData, + const ibuf = buffer._iData; + + // let matrix = node._worldMatrix; + node.getWorldMatrix(_worldMatrix); + const matrix = _worldMatrix; + const a = matrix.m00; + const b = matrix.m01; + const c = matrix.m04; + const d = matrix.m05; + const tx = matrix.m12; + const ty = matrix.m13; + for (let i = 0; i < vertexCount; i++) { + const vert = datas[i]; + vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; + vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; + vbuf[vertexOffset++] = vert.u; + vbuf[vertexOffset++] = vert.v; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + } + + // fill indice data + for (let i = 0, count = vertexCount / 4; i < count; i++) { + const start = vertexId + i * 4; + ibuf[indiceOffset++] = start; + ibuf[indiceOffset++] = start + 1; + ibuf[indiceOffset++] = start + 2; + ibuf[indiceOffset++] = start + 1; + ibuf[indiceOffset++] = start + 3; + ibuf[indiceOffset++] = start + 2; + } +} + +export function fillVertices3D (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; + + const vertexCount = renderData.vertexCount; + buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData; + + // let matrix = node._worldMatrix; + node.getWorldMatrix(_worldMatrix); + + for (let i = 0; i < vertexCount; i++) { + const vert = datas[i]; + vec3.set(vec3_temp, vert.x, vert.y, 0); + vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); + vbuf[vertexOffset++] = vec3_temp.x; + vbuf[vertexOffset++] = vec3_temp.y; + vbuf[vertexOffset++] = vec3_temp.z; + vbuf[vertexOffset++] = vert.u; + vbuf[vertexOffset++] = vert.v; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + // uintbuf[vertexOffset++] = color; + } +} + +export function fillMeshVertices3D (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; + + const vertexCount = renderData.vertexCount; + let indiceOffset = buffer.indiceOffset; + const vertexId = buffer.vertexOffset; + + buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData, + const ibuf = buffer.iData; + + // let matrix = node._worldMatrix; + node.getWorldMatrix(_worldMatrix); + + for (let i = 0; i < vertexCount; i++) { + const vert = datas[i]; + vec3.set(vec3_temp, vert.x, vert.y, 0); + vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); + vbuf[vertexOffset++] = vec3_temp.x; + vbuf[vertexOffset++] = vec3_temp.y; + vbuf[vertexOffset++] = vec3_temp.z; + vbuf[vertexOffset++] = vert.u; + vbuf[vertexOffset++] = vert.v; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + // uintbuf[vertexOffset++] = color; + } + + // fill indice data + for (let i = 0, count = vertexCount / 4; i < count; i++) { + const start = vertexId + i * 4; + ibuf[indiceOffset++] = start; + ibuf[indiceOffset++] = start + 1; + ibuf[indiceOffset++] = start + 2; + ibuf[indiceOffset++] = start + 1; + ibuf[indiceOffset++] = start + 3; + ibuf[indiceOffset++] = start + 2; + } +} + +export function fillVerticesWithoutCalc (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; + + const vertexCount = renderData.vertexCount; + buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData; + + for (let i = 0; i < vertexCount; i++) { + const vert = datas[i]; + vbuf[vertexOffset++] = vert.x; + vbuf[vertexOffset++] = vert.y; + vbuf[vertexOffset++] = vert.u; + vbuf[vertexOffset++] = vert.v; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + } +} + +export function fillVerticesWithoutCalc3D (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; + + const vertexCount = renderData.vertexCount; + buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + const vbuf = buffer.vData; + // const uintbuf = buffer._uintVData; + + for (let i = 0; i < vertexCount; i++) { + const vert = datas[i]; + vbuf[vertexOffset++] = vert.x; + vbuf[vertexOffset++] = vert.y; + vbuf[vertexOffset++] = vert.z; + vbuf[vertexOffset++] = vert.u; + vbuf[vertexOffset++] = vert.v; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + } +} diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts new file mode 100644 index 0000000000..95bd18b3e7 --- /dev/null +++ b/cocos/3d/ui/components/button-component.ts @@ -0,0 +1,813 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ +// @ts-check +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 { lerp } from '../../../core/utils/misc'; +import { Color, Enum, Vec3 } from '../../../core/value-types/index'; +import * as math from '../../../core/vmath/index'; +import { Node } from '../../../scene-graph'; +import { SpriteComponent } from './sprite-component'; + +/** + * !#en Enum for transition type. + * !#zh 过渡类型 + * @enum Button.Transition + */ +enum Transition { + /** + * !#en The none type. + * !#zh 不做任何过渡 + * @property {Number} NONE + */ + NONE = 0, + + /** + * !#en The color type. + * !#zh 颜色过渡 + * @property {Number} COLOR + */ + COLOR = 1, + + /** + * !#en The sprite type. + * !#zh 精灵过渡 + * @property {Number} SPRITE + */ + SPRITE = 2, + /** + * !#en The scale type + * !#zh 缩放过渡 + * @property {Number} SCALE + */ + SCALE = 3, +} + +Enum(Transition); + +/** + * !#en + * Button has 4 Transition types
+ * When Button state changed:
+ * If Transition type is Button.Transition.NONE, Button will do nothing
+ * If Transition type is Button.Transition.COLOR, Button will change target's color
+ * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite
+ * If Transition type is Button.Transition.SCALE, Button will change target node's scale
+ * + * Button will trigger 5 events:
+ * Button.EVENT_TOUCH_DOWN
+ * Button.EVENT_TOUCH_UP
+ * Button.EVENT_HOVER_IN
+ * Button.EVENT_HOVER_MOVE
+ * Button.EVENT_HOVER_OUT
+ * + * !#zh + * 按钮组件。可以被按下,或者点击。
+ * + * 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:
+ * -Button.Transition.NONE // 不做任何过渡
+ * -Button.Transition.COLOR // 进行颜色之间过渡
+ * -Button.Transition.SPRITE // 进行精灵之间过渡
+ * -Button.Transition.SCALE // 进行缩放过渡
+ * + * 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):
+ * // 以下事件可以在全平台上都触发
+ * -cc.Node.EventType.TOUCH_START // 按下时事件
+ * -cc.Node.EventType.TOUCH_Move // 按住移动后事件
+ * -cc.Node.EventType.TOUCH_END // 按下后松开后事件
+ * -cc.Node.EventType.TOUCH_CANCEL // 按下取消事件
+ * // 以下事件只在 PC 平台上触发
+ * -cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件
+ * -cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件
+ * -cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件
+ * -cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件
+ * -cc.Node.EventType.MOUSE_UP // 鼠标松开事件
+ * -cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件
+ * + * @class Button + * @extends Component + * @example + * + * // Add an event to the button. + * button.node.on(cc.Node.EventType.TOUCH_START, function (event) { + * cc.log("This is a callback after the trigger event"); + * }); + * // You could also add a click event + * //Note: In this way, you can't get the touch event info, so use it wisely. + * button.node.on('click', function (button) { + * //The event is a custom event, you could get the Button component via first argument + * }) + * + */ + +@ccclass('cc.ButtonComponent') +@executionOrder(100) +@menu('UI/Button') +@executeInEditMode +export class ButtonComponent extends Component { + + /** + * !#en + * Whether the Button is disabled. + * If true, the Button will trigger event and do transition. + * !#zh + * 按钮事件是否被响应,如果为 false,则按钮将被禁用。 + * @property {Boolean} interactable + * @default true + */ + @property + get interactable () { + return this._interactable; + } + + set interactable (value: boolean) { + if (CC_EDITOR) { + if (value) { + this._previousNormalSprite = this.normalSprite; + } else { + this.normalSprite = this._previousNormalSprite; + } + } + this._interactable = !this._interactable; + this._updateState(); + + if (!this._interactable) { + this._resetState(); + } + } + + set _resizeToTarget (value: boolean) { + if (value) { + this._resizeNodeToTargetNode(); + } + } + + /** + * !#en When this flag is true, Button target sprite will turn gray when interactable is false. + * !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰 + * @property {Boolean} enableAutoGrayEffect + */ + // enableAutoGrayEffect: { + // default: false, + // tooltip: CC_DEV && 'i18n:COMPONENT.button.auto_gray_effect', + // notify() { + // this._updateDisabledState(); + // } + // }, + + /** + * !#en Transition type + * !#zh 按钮状态改变时过渡方式。 + * @property {Button.Transition} transition + * @default Button.Transition.Node + */ + @property({ + type: Transition, + }) + get transition () { + return this._transition; + } + + set transition (value: Transition) { + if (this._transition === value) { + return; + } + + this._transition = value; + } + + // color transition + + /** + * !#en Normal state color. + * !#zh 普通状态下按钮所显示的颜色。 + * @property {Color} normalColor + */ + @property + get normalColor () { + return this._normalColor; + } + + set normalColor (value: Color) { + if (this._normalColor === value) { + return; + } + + this._normalColor = value; + this._updateState(); + } + + /** + * !#en Pressed state color + * !#zh 按下状态时按钮所显示的颜色。 + * @property {Color} pressedColor + */ + @property + get pressedColor () { + return this._pressColor; + } + + set pressedColor (value: Color) { + if (this._pressColor === value) { + return; + } + + this._pressColor = value; + } + + /** + * !#en Hover state color + * !#zh 悬停状态下按钮所显示的颜色。 + * @property {Color} hoverColor + */ + @property + get hoverColor () { + return this._hoverColor; + } + + set hoverColor (value: Color) { + if (this._hoverColor === value) { + return; + } + + this._hoverColor = value; + } + /** + * !#en Disabled state color + * !#zh 禁用状态下按钮所显示的颜色。 + * @property {Color} disabledColor + */ + @property + get disabledColor () { + return this._disabledColor; + } + + set disabledColor (value: Color) { + if (this._disabledColor === value) { + return; + } + + this._disabledColor = value; + this._updateState(); + } + + /** + * !#en Color and Scale transition duration + * !#zh 颜色过渡和缩放过渡时所需时间 + * @property {Number} duration + */ + @property({ + min: 0, + max: 10, + }) + get duration () { + return this._duration; + } + + set duration (value: number) { + if (this._duration === value) { + return; + } + + this._duration = 0.1; + } + + /** + * !#en When user press the button, the button will zoom to a scale. + * The final scale of the button equals (button original scale * zoomScale) + * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale + * @property {Number} zoomScale + */ + @property + get zoomScale () { + return this._zoomScale; + } + + set zoomScale (value: number) { + if (this._zoomScale === value) { + return; + } + + this._zoomScale = value; + } + + // sprite transition + /** + * !#en Normal state sprite + * !#zh 普通状态下按钮所显示的 Sprite 。 + * @property {SpriteFrame} normalSprite + */ + @property({ + type: SpriteFrame, + }) + get normalSprite () { + return this._normalSprite; + } + + set normalSprite (value: SpriteFrame) { + if (this._normalSprite === value) { + return; + } + + this._normalSprite = value; + this._updateState(); + } + + /** + * !#en Pressed state sprite + * !#zh 按下状态时按钮所显示的 Sprite 。 + * @property {SpriteFrame} pressedSprite + */ + @property({ + type: SpriteFrame, + }) + get pressedSprite () { + return this._pressedSprite; + } + + set pressedSprite (value: SpriteFrame) { + if (this._pressedSprite === value) { + return; + } + + this._pressedSprite = value; + this._updateState(); + } + + /** + * !#en Hover state sprite + * !#zh 悬停状态下按钮所显示的 Sprite 。 + * @property {SpriteFrame} hoverSprite + */ + @property({ + type: SpriteFrame, + }) + get hoverSprite () { + return this._hoverSprite; + } + + set hoverSprite (value: SpriteFrame) { + if (this._hoverSprite === value) { + return; + } + + this._hoverSprite = value; + this._updateState(); + } + + /** + * !#en Disabled state sprite + * !#zh 禁用状态下按钮所显示的 Sprite 。 + * @return {SpriteFrame} + */ + @property({ + type: SpriteFrame, + }) + get disabledSprite () { + return this._disabledSprite; + } + + set disabledSprite (value: SpriteFrame) { + if (this._disabledSprite === value) { + return; + } + + this._disabledSprite = value; + this._updateState(); + } + + /** + * !#en + * Transition target. + * When Button state changed: + * If Transition type is Button.Transition.NONE, Button will do nothing + * If Transition type is Button.Transition.COLOR, Button will change target's color + * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite + * !#zh + * 需要过渡的目标。 + * 当前按钮状态改变规则: + * -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。 + * -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。 + * -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 + * @property {Node} target + */ + @property + get target () { + return this._target; + } + + set target (value: Node) { + if (this._target === value) { + return; + } + + this._target = value; + this._applyTarget(); + } + + /** + * !#en If Button is clicked, it will trigger event's handler + * !#zh 按钮的点击事件列表。 + * @property {ComponentEventHandler[]} clickEvents + */ + @property({ + type: ComponentEventHandler, + }) + get clickEvents () { + return this._clickEvents; + } + + set clickEvents (value: ComponentEventHandler[]) { + this._clickEvents = value; + } + + public static Transition = Transition; + @property + public _interactable: boolean = true; + @property + public _transition: number = Transition.NONE; + @property + public _normalColor: Color = new Color(214, 214, 214); + @property + public _hoverColor: Color = new Color(211, 211, 211); + @property + public _pressColor: Color = Color.WHITE; + @property + public _disabledColor: Color = new Color(124, 124, 124); + @property + public _normalSprite: SpriteFrame | null = null; + @property + public _hoverSprite: SpriteFrame | null = null; + @property + public _pressedSprite: SpriteFrame | null = null; + @property + public _disabledSprite: SpriteFrame | null = null; + @property + public _duration: number = 0.1; + @property + public _zoomScale: number = 1.2; + @property + public _target: Node = null; + @property + public _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; + } + } + + public __preload () { + if (!this.target) { + this.target = this.node; + } + this._applyTarget(); + this._updateState(); + } + + public _resetState () { + this._pressed = false; + this._hovered = false; + // // Restore button status + const target = this.target; + const renderComp = this.target.getComponent(cc.RenderComponent); + const transition = this.transition; + if (transition === Transition.COLOR && this.interactable) { + renderComp.color = this.normalColor; + } else if (transition === Transition.SCALE) { + target.scale = this._originalScale; + } + this._transitionFinished = true; + } + + public onEnable () { + // check sprite frames + if (this._normalSprite) { + this._normalSprite.ensureLoadTexture(); + } + if (this._hoverSprite) { + this._hoverSprite.ensureLoadTexture(); + } + if (this._pressedSprite) { + this._pressedSprite.ensureLoadTexture(); + } + if (this._disabledSprite) { + this._disabledSprite.ensureLoadTexture(); + } + // + if (!CC_EDITOR) { + this._registerEvent(); + } 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(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'); + } + } + + public update (dt: number) { + const target = this._target; + if (this._transitionFinished) { + return; + } + + if (this._transition !== Transition.COLOR && this._transition !== Transition.SCALE) { + return; + } + + this._time += dt; + let ratio = 1.0; + if (this._duration > 0) { + ratio = this._time / this._duration; + } + + if (ratio >= 1) { + ratio = 1; + this._transitionFinished = true; + } + + const renderComp = target.getComponent(cc.RenderComponent); + 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); + } + } + + 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); + + this.node.on(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); + this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); + } + + public _getTargetSprite (target: Node | null) { + let sprite = null; + if (target) { + sprite = target.getComponent(cc.SpriteComponent); + } + return sprite; + } + + public _applyTarget () { + this._sprite = this._getTargetSprite(this._target); + if (this._target) { + math.vec3.copy(this._originalScale, this.target._lscale); + } + } + + // touch event handler + public _onTouchBegan (event: Event | null) { + if (!this._interactable || !this.enabledInHierarchy) { return; } + + this._pressed = true; + this._updateState(); + event && event.stopPropagation(); + } + + public _onTouchMove (event: Event | null) { + if (!this._interactable || !this.enabledInHierarchy || !this._pressed) { return; } + // mobile phone will not emit _onMouseMoveOut, + // so we have to do hit test when touch moving + if (!event) { + return false; + } + + const touch = (event as EventTouch).touch; + if (!touch) { + return false; + } + + const hit = this.node.uiTransfromComp!.isHit(touch.getLocation()); + + if (this._transition === Transition.SCALE && this._target) { + if (hit) { + 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; + } + } else { + let state; + if (hit) { + state = 'pressed'; + } else { + state = 'normal'; + } + this._applyTransition(state); + } + event.stopPropagation(); + } + + public _onTouchEnded (event: Event | null) { + if (!this._interactable || !this.enabledInHierarchy) { return; } + + if (this._pressed) { + ComponentEventHandler.emitEvents(this._clickEvents, event); + this.node.emit('click', this); + } + this._pressed = false; + this._updateState(); + event && event.stopPropagation(); + } + + public _onTouchCancel () { + if (!this._interactable || !this.enabledInHierarchy) { return; } + + this._pressed = false; + this._updateState(); + } + + public _onMouseMoveIn () { + if (this._pressed || !this.interactable || !this.enabledInHierarchy) { return; } + if (this._transition === Transition.SPRITE && !this._hoverSprite) { return; } + + if (!this._hovered) { + this._hovered = true; + this._updateState(); + } + } + + public _onMouseMoveOut () { + if (this._hovered) { + this._hovered = false; + this._updateState(); + } + } + + // state handler + public _updateState () { + const state = this._getButtonState(); + this._applyTransition(state); + // this._updateDisabledState(); + } + + public _getButtonState () { + let state; + if (!this._interactable) { + state = 'disabled'; + } else if (this._pressed) { + state = 'pressed'; + } else if (this._hovered) { + state = 'hover'; + } else { + state = 'normal'; + } + return state; + } + + public _updateColorTransition (state: string) { + const color = this[state + 'Color']; + const target = this._target; + + const renderComp = target.getComponent(cc.RenderComponent); + if (!renderComp) { + return; + } + + if (CC_EDITOR) { + renderComp.color = color; + } else { + this._fromColor = renderComp.color.clone(); + this._toColor = color; + this._time = 0; + this._transitionFinished = false; + } + } + + public _updateSpriteTransition (state: string) { + const sprite = this[state + 'Sprite']; + if (this._sprite && sprite) { + this._sprite.spriteFrame = sprite; + } + } + + public _updateScaleTransition (state: string) { + if (state === 'pressed') { + this._zoomUp(); + } else { + this._zoomBack(); + } + } + + public _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 () { + 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) { + const transition = this._transition; + if (transition === Transition.COLOR) { + this._updateColorTransition(state); + } else if (transition === Transition.SPRITE) { + this._updateSpriteTransition(state); + } else if (transition === Transition.SCALE) { + this._updateScaleTransition(state); + } + } + + public _resizeNodeToTargetNode () { + if (CC_EDITOR && this._target) { + this.node.setContentSize(this.target.getContentSize()); + } + } + + // _updateDisabledState() { + // if (this._sprite) { + // if (this.enableAutoGrayEffect) { + // if (!(this._transition === Transition.SPRITE && this._disabledSprite)) { + // if (!this._interactable) { + // this._sprite.setState(cc.SpriteComponent.State.GRAY); + // return; + // } + // } + // } + // this._sprite.setState(cc.SpriteComponent.State.NORMAL); + // } + // } +} + +/** + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event click + * @param {Event.EventCustom} event + * @param {Button} button - The Button component. + */ diff --git a/cocos/components/CCCanvas.js b/cocos/3d/ui/components/canvas-component.ts similarity index 53% rename from cocos/components/CCCanvas.js rename to cocos/3d/ui/components/canvas-component.ts index c74ac8df5f..fde3a3a512 100644 --- a/cocos/components/CCCanvas.js +++ b/cocos/3d/ui/components/canvas-component.ts @@ -24,9 +24,13 @@ THE SOFTWARE. ****************************************************************************/ -import Camera from '../camera/CCCamera'; -import Component from './CCComponent'; -import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from '../core/data/class-decorator'; +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'; /** * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 @@ -35,60 +39,37 @@ import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from * @class Canvas * @extends Component */ -@ccclass('cc.Canvas') +@ccclass('cc.CanvasComponent') +@executionOrder(100) @menu('UI/Canvas') -@help('i18n:COMPONENT.help_url.canvas') @executeInEditMode -@disallowMultiple -export default class Canvas extends Component { - /** - * !#en Current active canvas, the scene should only have one active canvas at the same time. - * !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。 - * @property {Canvas} instance - * @static - */ - static instance = null; +// @disallowMultiple +export class CanvasComponent extends Component { - /** - * !#en The desigin resolution for current scene. - * !#zh 当前场景设计分辨率。 - * @property {Size} designResolution - * @default new cc.Size(960, 640) - */ - @property - _designResolution = cc.size(960, 640); @property({ - tooltip: CC_DEV && 'i18n:COMPONENT.canvas.design_resolution', - type: cc.Size + type: Size, }) get designResolution () { return cc.size(this._designResolution); } - set designResolution (value) { + set designResolution (value: Size) { this._designResolution.width = value.width; this._designResolution.height = value.height; this.applySettings(); this.alignWithScreen(); } - @property - _fitWidth = false; - @property - _fitHeight = true; - /** * !#en TODO * !#zh: 是否优先将设计分辨率高度撑满视图高度。 * @property {Boolean} fitHeight * @default false */ - @property({ - tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_height' - }) + @property() get fitHeight () { return this._fitHeight; } - set fitHeight (value) { + set fitHeight (value: boolean) { if (this._fitHeight !== value) { this._fitHeight = value; this.applySettings(); @@ -102,13 +83,11 @@ export default class Canvas extends Component { * @property {Boolean} fitWidth * @default false */ - @property({ - tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_width' - }) + @property() get fitWidth () { return this._fitWidth; } - set fitWidth (value) { + set fitWidth (value: boolean) { if (this._fitWidth !== value) { this._fitWidth = value; this.applySettings(); @@ -116,28 +95,103 @@ export default class Canvas 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; + } + + return -1; + } + + get camera () { + return this._camera; + } + + public static views = []; + /** + * !#en The desigin resolution for current scene. + * !#zh 当前场景设计分辨率。 + * @property {Size} designResolution + * @default new cc.Size(960, 640) + */ + @property + private _designResolution = cc.size(960, 640); + @property + private _fitWidth = false; + @property + private _fitHeight = true; + // @property + // private _priority = 0; + + private _thisOnResized: ()=>void; + + private _camera: Camera | null = null; + private _cameraInfo: ICameraInfo | null = null; + + // /** + // * !#en Current active canvas, the scene should only have one active canvas at the same time. + // * !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。 + // * @property {CanvasComponent} instance + // * @static + // */ + // static instance = null; + constructor () { super(); this._thisOnResized = this.alignWithScreen.bind(this); } - resetInEditor () { - _Scene._applyCanvasPreferences(this); + // public onLoad () {} + + public resetInEditor () { + // _Scene._applyCanvasPreferences(this); } - __preload () { - if (CC_DEV) { - var Flags = cc.Object.Flags; - this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked); - } + public __preload () { + this._cameraInfo = { + name: 'ui', + node: this.node, + projection: CameraComponent.ProjectionType.ORTHO, + fov: 45, + stencil: 0, + orthoHeight: 10, + far: 4096, + near: -0.1, + color: cc.color(0, 0, 0, 255), + clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, + rect: new Rect(0, 0, 1, 1), + depth: 1, + isUI: true, + } as ICameraInfo; + this._camera = this._getRenderScene().createCamera(this._cameraInfo); + cc.director.root.ui.addScreen(this); - if (Canvas.instance) { - return cc.errorID(6700, - this.node.name, Canvas.instance.node.name); - } - Canvas.instance = this; + // if (CC_DEV) { + // var Flags = cc.Object.Flags; + // this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked); + // } + + // if (CanvasComponent.instance) { + // return cc.errorID(6700, + // this.node.name, CanvasComponent.instance.node.name); + // } + // CanvasComponent.instance = this; if (CC_EDITOR) { + cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); cc.engine.on('design-resolution-changed', this._thisOnResized); } else { @@ -151,57 +205,51 @@ export default class Canvas extends Component { this.applySettings(); this.alignWithScreen(); - - // Camera could be removed in canvas render mode - // let cameraNode = cc.find('Main Camera', this.node); - // if (!cameraNode) { - // cameraNode = new cc.Node('Main Camera'); - // cameraNode.parent = this.node; - // cameraNode.setSiblingIndex(0); - // } - // let camera = cameraNode.getComponent(Camera); - // if (!camera) { - // camera = cameraNode.addComponent(Camera); - - // let ClearFlags = Camera.ClearFlags; - // camera.clearFlags = ClearFlags.COLOR | ClearFlags.DEPTH | ClearFlags.STENCIL; - // camera.depth = -1; - // } - // Camera.main = camera; } - onDestroy () { + public onDisable () { + if (this._camera) { + this._getRenderScene().destroyCamera(this._camera); + cc.director.root.ui.removeScreen(this); + } + } + + public onDestroy () { if (CC_EDITOR) { + cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); cc.engine.off('design-resolution-changed', this._thisOnResized); } else { if (cc.sys.isMobile) { window.removeEventListener('resize', this._thisOnResized); - } - else { + } else { cc.view.off('canvas-resize', this._thisOnResized); } } - if (Canvas.instance === this) { - Canvas.instance = null; - } + cc.view.off('design-resolution-changed', this._thisOnResized); + + // if (CanvasComponent.instance === this) { + // CanvasComponent.instance = null; + // } } // - alignWithScreen () { - var designSize, nodeSize; + public alignWithScreen() { + let nodeSize, designSize; if (CC_EDITOR) { - nodeSize = designSize = cc.engine.getDesignResolutionSize(); + // nodeSize = designSize = cc.engine.getDesignResolutionSize(); + nodeSize = designSize = this._designResolution; this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1); } else { - var canvasSize = nodeSize = cc.visibleRect; - designSize = cc.view.getDesignResolutionSize(); - var clipTopRight = !this.fitHeight && !this.fitWidth; - var offsetX = 0; - var offsetY = 0; + const canvasSize = cc.visibleRect; + nodeSize = canvasSize; + const designSize = cc.view.getDesignResolutionSize(); + const clipTopRight = !this.fitHeight && !this.fitWidth; + let offsetX = 0; + let offsetY = 0; if (clipTopRight) { // offset the canvas to make it in the center of screen offsetX = (designSize.width - canvasSize.width) * 0.5; @@ -213,31 +261,26 @@ export default class Canvas extends Component { this.node.height = nodeSize.height; } - applySettings () { - var ResolutionPolicy = cc.ResolutionPolicy; - var policy; + public applySettings () { + const ResolutionPolicy = cc.ResolutionPolicy; + let policy; if (this.fitHeight && this.fitWidth) { policy = ResolutionPolicy.SHOW_ALL; - } - else if (!this.fitHeight && !this.fitWidth) { + } else if (!this.fitHeight && !this.fitWidth) { policy = ResolutionPolicy.NO_BORDER; - } - else if (this.fitWidth) { + } else if (this.fitWidth) { policy = ResolutionPolicy.FIXED_WIDTH; - } - else { // fitHeight + } else { // fitHeight policy = ResolutionPolicy.FIXED_HEIGHT; } - var designRes = this._designResolution; + const designRes = this._designResolution; if (CC_EDITOR) { - cc.engine.setDesignResolutionSize(designRes.width, designRes.height); + // cc.engine.setDesignResolutionSize(designRes.width, designRes.height); } else { cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy); } } } - -cc.Canvas = Canvas; \ No newline at end of file diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/3d/ui/components/editbox/edit-box-component.ts new file mode 100644 index 0000000000..fc6f9a32f8 --- /dev/null +++ b/cocos/3d/ui/components/editbox/edit-box-component.ts @@ -0,0 +1,825 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { 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 macro from '../../../../core/platform/CCMacro'; +import Color from '../../../../core/value-types/color'; +import { LabelComponent } from '../label-component'; +import { SpriteComponent } from '../sprite-component'; +import { UIRenderComponent } from '../ui-render-component'; +import { UITransformComponent } from '../ui-transfrom-component'; +import { EditBoxImpl} from './edit-box-impl'; +import { InputFlag, InputMode, KeyboardReturnType } from './types'; + +const LEFT_PADDING = 2; + +function capitalize (string) { + return string.replace(/(?:^|\s)\S/g, (a) => { + return a.toUpperCase(); + }); +} + +function capitalizeFirstLetter (string) { + return string.charAt(0).toUpperCase() + string.slice(1); +} + +/** + * !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users. + * !#zh EditBox 组件,用于获取用户的输入文本。 + * @class EditBox + * @extends Component + */ + +@ccclass('cc.EditBoxComponent') +@executionOrder(100) +@menu('UI/EditBox') +@executeInEditMode +export class EditBoxComponent extends Component { + + /** + * !#en Input string of EditBox. + * !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。 + * @property {String} string + */ + @property + get string () { + return this._string; + } + + set string (value) { + if (this._maxLength >= 0 && value.length >= this._maxLength) { + value = value.slice(0, this._maxLength); + } + + this._string = value; + if (this._impl) { + this._updateString(value); + } + } + + /** + * !#en The background image of EditBox. + * !#zh 输入框的背景图片 + * @property {SpriteFrame} backgroundImage + */ + @property({ + type: SpriteFrame, + }) + get backgroundImage () { + return this._backgroundImage; + } + + set backgroundImage (value: SpriteFrame | null) { + if (this._backgroundImage === value) { + return; + } + + this._backgroundImage = value; + this._createBackgroundSprite(); + } + + /** + * !#en + * The return key type of EditBox. + * Note: it is meaningless for web platforms and desktop platforms. + * !#zh + * 指定移动设备上面回车按钮的样式。 + * 注意:这个选项对 web 平台与 desktop 平台无效。 + * @property {EditBox.KeyboardReturnType} returnType + * @default KeyboardReturnType.DEFAULT + */ + @property({ + type: KeyboardReturnType, + }) + get returnType () { + return this._returnType; + } + + set returnType (value: KeyboardReturnType) { + this._returnType = value; + if (this._impl) { + this._impl.returnType = this._returnType; + } + } + + /** + * !#en Set the input flags that are to be applied to the EditBox. + * !#zh 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。 + * @property {EditBox.InputFlag} inputFlag + * @default InputFlag.DEFAULT + */ + @property({ + type: InputFlag, + }) + get inputFlag () { + return this._inputFlag; + } + + set inputFlag (value: InputFlag) { + this._inputFlag = value; + if (this._impl) { + this._impl.setInputFlag(this._inputFlag); + this._updateString(this._string); + } + } + /** + * !#en + * Set the input mode of the edit box. + * If you pass ANY, it will create a multiline EditBox. + * !#zh + * 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。 + * @property {EditBox.InputMode} inputMode + * @default InputMode.ANY + */ + @property({ + type: InputMode, + }) + get inputMode () { + return this._inputMode; + } + + set inputMode (value: InputMode) { + this._inputMode = value; + if (this._impl) { + this._impl.setInputMode(this._inputMode); + } + } + + /** + * !#en Font size of the input text. + * !#zh 输入框文本的字体大小 + * @property {Number} fontSize + */ + @property + get fontSize () { + return this._fontSize; + } + + set fontSize (value) { + if (this._fontSize === value) { + return; + } + + this._fontSize = value; + if (this._textLabel) { + this._textLabel.fontSize = this._fontSize; + } + if (this._impl) { + this._impl.setFontSize(this._fontSize); + } + } + + /** + * !#en Change the lineHeight of displayed text. + * !#zh 输入框文本的行高。 + * @property {Number} lineHeight + */ + @property + get lineHeight () { + return this._lineHeight; + } + + set lineHeight (value) { + if (this._lineHeight === value) { + return; + } + + this._lineHeight = value; + if (this._textLabel) { + this._textLabel.lineHeight = this._lineHeight; + } + } + + /** + * !#en Font color of the input text. + * !#zh 输入框文本的颜色。 + * @property {Color} fontColor + */ + @property({ + type: Color, + }) + get fontColor () { + return this._fontColor; + } + + set fontColor (value: Color) { + if (this._fontColor === value) { + return; + } + + this._fontColor = value; + if (this._textLabel) { + // this._textLabel.node.opacity = this._fontColor.a; + const renderComp = this._textLabel.node.getComponent(UIRenderComponent); + if (renderComp) { + renderComp.color = this._fontColor; + } + } + if (this._impl) { + this._impl.setFontColor(this._fontColor); + } + } + + /** + * !#en The display text of placeholder. + * !#zh 输入框占位符的文本内容。 + * @property {String} placeholder + */ + @property + get placeholder () { + return this._placeholder; + } + + set placeholder (value) { + if (this._placeholder === value) { + return; + } + + this._placeholder = value; + if (this._placeholderLabel) { + this._placeholderLabel.string = this._placeholder; + } + if (this._impl) { + this._impl.setPlaceholderText(this._placeholder); + } + } + + /** + * !#en The font size of placeholder. + * !#zh 输入框占位符的字体大小。 + * @property {Number} placeholderFontSize + */ + @property + get placeholderFontSize () { + return this._placeholderFontSize; + } + + set placeholderFontSize (value) { + if (this._placeholderFontSize === value) { + return; + } + + this._placeholderFontSize = value; + if (this._placeholderLabel) { + this._placeholderLabel.fontSize = this._placeholderFontSize; + } + } + + /** + * !#en The font color of placeholder. + * !#zh 输入框占位符的字体颜色。 + * @property {Color} placeholderFontColor + */ + @property + get placeholderFontColor () { + return this._placeholderFontColor; + } + + set placeholderFontColor (value: Color) { + if (this._placeholderFontColor === value) { + return; + } + + this._placeholderFontColor = value; + if (this._placeholderLabel) { + const comp = this._placeholderLabel.node.getComponent(UIRenderComponent); + if (comp) { + comp.color = this._placeholderFontColor; + } + // this._placeholderLabel.node.opacity = this._placeholderFontColor.a; + } + } + + /** + * !#en The maximize input length of EditBox. + * - If pass a value less than 0, it won't limit the input number of characters. + * - If pass 0, it doesn't allow input any characters. + * !#zh 输入框最大允许输入的字符个数。 + * - 如果值为小于 0 的值,则不会限制输入字符个数。 + * - 如果值为 0,则不允许用户进行任何输入。 + * @property {Number} maxLength + */ + @property + get maxLength () { + return this._maxLength; + } + set maxLength (value) { + if (this._maxLength === value) { + return; + } + + this._maxLength = value; + if (this._impl) { + this._impl.setMaxLength(this._maxLength); + } + } + + /** + * !#en The input is always visible and be on top of the game view (only useful on Web). + * !zh 输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义) + * Note: only available on Web at the moment. + * @property {Boolean} stayOnTop + */ + @property + get stayOnTop () { + return this._stayOnTop; + } + + set stayOnTop (value) { + this._stayOnTop = value; + if (this._impl) { + this._updateStayOnTop(); + } + } + + /** + * !#en Set the tabIndex of the DOM input element (only useful on Web). + * !#zh 修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)。 + * @property {Number} tabIndex + */ + @property + get tabIndex () { + return this._tabIndex; + } + + set tabIndex (value) { + this._tabIndex = value; + if (this._impl) { + this._impl.setTabIndex(value); + } + } + + public static _EditBoxImpl = EditBoxImpl; + public static KeyboardReturnType = KeyboardReturnType; + public static InputFlag = InputFlag; + public static InputMode = InputMode; + @property + public _useOriginalSize = true; + @property + public _string = ''; + @property + public _tabIndex = 0; + @property + public _backgroundImage: SpriteFrame | null = null; + @property + public _returnType = KeyboardReturnType.DEFAULT; + @property + public _inputFlag = InputFlag.DEFAULT; + @property + public _inputMode = InputMode.SINGLE_LINE; + @property + public _fontSize = 20; + @property + public _lineHeight = 40; + @property + public _maxLength = 20; + @property + public _fontColor: Color = Color.WHITE; + @property + public _placeholder = 'Enter text here...'; + @property + public _placeholderFontSize = 20; + @property + public _placeholderFontColor: Color = Color.GRAY; + @property + public _stayOnTop = false; + /** + * !#en The event handler to be called when EditBox began to edit text. + * !#zh 开始编辑文本输入框触发的事件回调。 + * @property {Component.EventHandler[]} editingDidBegan + */ + @property + public editingDidBegan: ComponentEventHandler[] = []; + + /** + * !#en The event handler to be called when EditBox text changes. + * !#zh 编辑文本输入框时触发的事件回调。 + * @property {Component.EventHandler[]} textChanged + */ + @property + public textChanged: ComponentEventHandler[] = []; + + /** + * !#en The event handler to be called when EditBox edit ends. + * !#zh 结束编辑文本输入框时触发的事件回调。 + * @property {Component.EventHandler[]} editingDidEnded + */ + @property + public editingDidEnded: ComponentEventHandler[] = []; + + /** + * !#en The event handler to be called when return key is pressed. Windows is not supported. + * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台 + * @property {Component.EventHandler[]} editingReturn + */ + @property + public editingReturn: ComponentEventHandler[] = []; + + public _impl: EditBoxImpl | null = null; + public _textLabel: LabelComponent | null = null; + public _placeholderLabel: LabelComponent | null = null; + public _background: SpriteComponent | null = null; + + public onEnable () { + this._impl && this._impl.onEnable(); + } + + public onDisable () { + this._impl && this._impl.onDisable(); + } + + public onDestroy () { + this._impl && this._impl.clear(); + } + + public _init () { + this._createBackgroundSprite(); + this._createLabels(); + this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this); + + const impl = this._impl = new EditBoxImpl(); + + impl.setDelegate(this); + impl.setNode(this.node); + impl.setInputMode(this._inputMode); + impl.setMaxLength(this._maxLength); + impl.setInputFlag(this._inputFlag); + impl.setReturnType(this._returnType); + impl.setTabIndex(this._tabIndex); + impl.setFontColor(this._fontColor); + impl.setFontSize(this._fontSize); + impl.setPlaceholderText(this._placeholder); + + this._updateStayOnTop(); + this._updateString(this._string); + this._syncSize(); + } + + public __preload () { + if (!CC_EDITOR) { + this._registerEvent(); + } + this._init(); + } + + public _registerEvent () { + this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + } + + public _updateStayOnTop () { + if (this.stayOnTop) { + this._hideLabels(); + } else { + this._showLabels(); + } + this._impl && this._impl.stayOnTop(this.stayOnTop); + } + + public _syncSize () { + const size = this.node.getContentSize(); + + this._background && this._background.node.setAnchorPoint(this.node.getAnchorPoint()); + this._background && this._background.node.setContentSize(size); + + this._updateLabelPosition(size); + this._impl && this._impl.setSize(size.width, size.height); + } + + public _updateLabelPosition (size) { + const node = this.node; + const offx = -node.anchorX * node.width; + const offy = -node.anchorY * node.height; + + const placeholderLabel = this._placeholderLabel; + const textLabel = this._textLabel; + if (textLabel) { + textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, textLabel.node.getPosition().z); + textLabel.verticalAlign = this._inputMode === InputMode.ANY ? macro.VerticalTextAlignment.TOP : macro.VerticalTextAlignment.CENTER; + textLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; + } + + if (placeholderLabel) { + placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + placeholderLabel.lineHeight = size.height; + placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, placeholderLabel.node.getPosition().z); + placeholderLabel.verticalAlign = this._inputMode === InputMode.ANY ? + macro.VerticalTextAlignment.TOP : macro.VerticalTextAlignment.CENTER; + placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; + } + } + + public _createBackgroundSprite () { + if (!this._background) { + this._background = this.node.getComponent(cc.SpriteComponent); + if (!this._background) { + this._background = this.node.addComponent(cc.SpriteComponent); + } + + } + + this._background!.type = cc.SpriteComponent.Type.SLICED; + this._background!.spriteFrame = this._backgroundImage; + // let background = this._background; + // if (!background) { + // let node = this.node.getChildByName('BACKGROUND_SPRITE'); + // if (!node) { + // node = new cc.Node('BACKGROUND_SPRITE'); + // } + + // background = node.getComponent(cc.SpriteComponent); + // if (!background) { + // background = node.addComponent(cc.SpriteComponent); + // } + // background.type = cc.SpriteComponent.Type.SLICED; + + // node.parent = this.node; + // this._background = background; + // } + // background.spriteFrame = this._backgroundImage; + } + + public _createLabels () { + if (!this._textLabel) { + let node = this.node.getChildByName('TEXT_LABEL'); + if (!node) { + node = new cc.Node('TEXT_LABEL'); + } + let textLabel = node!.getComponent(LabelComponent); + node!.parent = this.node; + + if (!textLabel) { + textLabel = node!.addComponent(LabelComponent); + } + + const transformComp = node!.getComponent(UITransformComponent); + transformComp!.setAnchorPoint(0, 1); + textLabel!.color = this._fontColor; + textLabel!.overflow = LabelComponent.Overflow.CLAMP; + textLabel!.fontSize = this._fontSize; + textLabel!.lineHeight = this.lineHeight; + this._textLabel = textLabel; + } + + if (!this._placeholderLabel) { + let node = this.node.getChildByName('PLACEHOLDER_LABEL'); + if (!node) { + node = new cc.Node('PLACEHOLDER_LABEL'); + } + let placeholderLabel = node!.getComponent(LabelComponent); + if (!placeholderLabel) { + placeholderLabel = node!.addComponent(LabelComponent); + } + const transform = node!.getComponent(UITransformComponent); + + node!.parent = this.node; + placeholderLabel!.color = this._placeholderFontColor; + transform!.setAnchorPoint(0, 1); + + placeholderLabel!.overflow = LabelComponent.Overflow.CLAMP; + placeholderLabel!.fontSize = this._placeholderFontSize; + placeholderLabel!.string = this._placeholder; + this._placeholderLabel = placeholderLabel; + } + } + + public _resizeChildNodes () { + const textLabelNode = this._textLabel && this._textLabel.node; + if (textLabelNode) { + textLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, textLabelNode.getPosition().z); + textLabelNode.width = this.node.width; + textLabelNode.height = this.node.height; + } + const placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node; + if (placeholderLabelNode) { + placeholderLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, placeholderLabelNode.getPosition().z); + placeholderLabelNode.width = this.node.width; + placeholderLabelNode.height = this.node.height; + } + const backgroundNode = this._background && this._background.node; + if (backgroundNode) { + backgroundNode.width = this.node.width; + backgroundNode.height = this.node.height; + } + } + + public _showLabels () { + if (this._textLabel) { + const displayText = this._textLabel.string; + this._textLabel.node.active = displayText !== ''; + if (this._placeholderLabel) { + this._placeholderLabel.node.active = displayText === ''; + } + } + } + + public _hideLabels () { + if (this._textLabel) { + this._textLabel.node.active = false; + } + if (this._placeholderLabel) { + this._placeholderLabel.node.active = false; + } + } + + public _updateString (text) { + const textLabel = this._textLabel; + // Not inited yet + if (!textLabel) { + return; + } + + let displayText = text; + if (displayText) { + displayText = this._updateLabelStringStyle(displayText); + } + + textLabel.string = displayText; + if (this._impl) { + this._impl.setString(text); + if (!this._impl.editing && !this.stayOnTop) { + this._showLabels(); + } + } + } + + public _updateLabelStringStyle (text: string, ignorePassword: boolean = false) { + const inputFlag = this._inputFlag; + if (!ignorePassword && inputFlag === InputFlag.PASSWORD) { + let passwordString = ''; + const len = text.length; + for (let i = 0; i < len; ++i) { + passwordString += '\u25CF'; + } + text = passwordString; + } else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + text = text.toUpperCase(); + } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + text = capitalize(text); + } else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) { + text = capitalizeFirstLetter(text); + } + + return text; + } + + public editBoxEditingDidBegan () { + this._hideLabels(); + ComponentEventHandler.emitEvents(this.editingDidBegan, this); + this.node.emit('editing-did-began', this); + } + + public editBoxEditingDidEnded () { + if (!this.stayOnTop) { + this._showLabels(); + } + ComponentEventHandler.emitEvents(this.editingDidEnded, this); + this.node.emit('editing-did-ended', this); + } + + public editBoxTextChanged (text) { + text = this._updateLabelStringStyle(text, true); + this.string = text; + ComponentEventHandler.emitEvents(this.textChanged, text, this); + this.node.emit('text-changed', this); + } + + public editBoxEditingReturn () { + ComponentEventHandler.emitEvents(this.editingReturn, this); + this.node.emit('editing-return', this); + } + + public _onTouchBegan (event) { + if (this._impl) { + this._impl._onTouchBegan(event.touch); + } + event.stopPropagation(); + } + + public _onTouchCancel (event) { + // if (this._impl) { + // this._impl._onTouchCancel(); + // } + event.stopPropagation(); + } + + public _onTouchEnded (event) { + if (this._impl) { + this._impl._onTouchEnded(); + } + event.stopPropagation(); + } + + /** + * !#en Let the EditBox get focus + * !#zh 让当前 EditBox 获得焦点 + * @method setFocus + */ + public setFocus () { + if (this._impl) { + this._impl.setFocus(); + } + } + + /** + * !#en Determine whether EditBox is getting focus or not. + * !#zh 判断 EditBox 是否获得了焦点 + * Note: only available on Web at the moment. + * @method isFocused + */ + public isFocused () { + let isFocused = false; + if (this._impl) { + isFocused = this._impl.isFocused(); + } + return isFocused; + } + + public update () { + if (this._impl) { + this._impl.update(); + } + } +} + +/** + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event editing-did-began + * @param {Event.EventCustom} event + * @param {EditBox} editbox - The EditBox component. + */ + +/** + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event editing-did-ended + * @param {Event.EventCustom} event + * @param {EditBox} editbox - The EditBox component. + */ + +/** + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event text-changed + * @param {Event.EventCustom} event + * @param {EditBox} editbox - The EditBox component. + */ + +/** + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event editing-return + * @param {Event.EventCustom} event + * @param {EditBox} editbox - The EditBox component. + */ + +/** + * !#en if you don't need the EditBox and it isn't in any running Scene, you should + * call the destroy method on this component or the associated node explicitly. + * Otherwise, the created DOM element won't be removed from web page. + * !#zh + * 如果你不再使用 EditBox,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。 + * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。 + * @example + * editbox.node.parent = null; // or editbox.node.removeFromParent(false); + * // when you don't need editbox anymore + * editbox.node.destroy(); + * @method destroy + * @return {Boolean} whether it is the first time the destroy being called + */ diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts new file mode 100644 index 0000000000..47aa5c7fdb --- /dev/null +++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts @@ -0,0 +1,714 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2012 James Chen + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { ccclass } from '../../../../core/data/class-decorator'; +import macro from '../../../../core/platform/CCMacro'; +import { contains } from '../../../../core/utils/misc'; +import { Color, Size } from '../../../../core/value-types'; +import * as math from '../../../../core/vmath'; +import { Node } from '../../../../scene-graph/node'; +import { UIRenderComponent } from '../ui-render-component'; +import { EditBoxComponent} from './edit-box-component'; +// import { InputMode, InputFlag, KeyboardReturnType } from './types'; +import * as Types from './types'; +const InputMode = Types.InputMode; +const InputFlag = Types.InputFlag; +const KeyboardReturnType = Types.KeyboardReturnType; + +// https://segmentfault.com/q/1010000002914610 +const SCROLLY = 40; +const LEFT_PADDING = 2; +const DELAY_TIME = 400; +const FOCUS_DELAY_UC = 400; +const FOCUS_DELAY_FIREFOX = 0; + +const _matrix = cc.mat4(); +const _matrix_temp = cc.mat4(); +const _vec3 = cc.v3(); + +let _currentEditBoxImpl: EditBoxImpl | null = null; + +// polyfill +const polyfill = { + zoomInvalid: false, +}; + +if (cc.sys.OS_ANDROID === cc.sys.os && + (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU || + cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { + polyfill.zoomInvalid = true; +} + +function getKeyboardReturnType (type) { + switch (type) { + case KeyboardReturnType.DEFAULT: + case KeyboardReturnType.DONE: + return 'done'; + case KeyboardReturnType.SEND: + return 'send'; + case KeyboardReturnType.SEARCH: + return 'search'; + case KeyboardReturnType.GO: + return 'go'; + case KeyboardReturnType.NEXT: + return 'next'; + } + return 'done'; +} + +@ccclass +export class EditBoxImpl { + private _delegate: EditBoxComponent | null = null; + private _inputMode = -1; + private _inputFlag = -1; + private _returnType = KeyboardReturnType.DEFAULT; + private _maxLength = 50; + private _text = ''; + private _placeholderText = ''; + private _alwaysOnTop = false; + private _size: Size = cc.size(); + private _node: Node | null = null; + private _editing = false; + private __eventListeners: any = {}; + private __fullscreen = false; + private __autoResize = false; + private __rotateScreen = false; + private __orientationChanged: any; + private _edTxt: HTMLElement | null = null; + private _textColor: Color = Color.WHITE; + private _edFontSize = 14; + + get text () { + return this._text; + } + + set text (value: string) { + this._text = value; + } + + get textColor () { + return this._textColor; + } + + get fontSize () { + return this._edFontSize; + } + + set returnType (value: Types.KeyboardReturnType) { + this._returnType = value; + } + + get alwayOnTop () { + return this._alwaysOnTop; + } + + set editing (value: boolean) { + this._editing = value; + } + + get delegate () { + return this._delegate; + } + + get eventListeners () { + return this.__eventListeners; + } + + public onEnable () { + if (!this._edTxt) { + return; + } + if (this._alwaysOnTop) { + this._edTxt.style.display = ''; + } else { + this._edTxt.style.display = 'none'; + } + } + + public onDisable () { + if (!this._edTxt) { + return; + } + this._edTxt.style.display = 'none'; + } + + public setTabIndex (index) { + if (this._edTxt) { + this._edTxt.tabIndex = index; + } + } + + public setFocus () { + this._beginEditing(); + } + + public isFocused () { + if (this._edTxt) { + return document.activeElement === this._edTxt; + } + cc.warnID(4700); + return false; + } + + public stayOnTop (flag) { + if (this._alwaysOnTop === flag || !this._edTxt) { return; } + + this._alwaysOnTop = flag; + + if (flag) { + this._edTxt.style.display = ''; + } else { + this._edTxt.style.display = 'none'; + } + } + + public setMaxLength (maxLength) { + if (!isNaN(maxLength)) { + if (maxLength < 0) { + // we can't set Number.MAX_VALUE to input's maxLength property + // so we use a magic number here, it should works at most use cases. + maxLength = 65535; + } + this._maxLength = maxLength; + if (this._edTxt) { + this._edTxt.maxLength = maxLength; + } + } + } + + public setString (text) { + this._text = text; + if (this._edTxt) { + this._edTxt.value = text; + } + } + + public getString () { + return this._text; + } + + public setPlaceholderText (text) { + this._placeholderText = text; + } + + public getPlaceholderText () { + return this._placeholderText; + } + + public setDelegate (delegate) { + this._delegate = delegate; + } + + public setInputMode (inputMode) { + if (this._inputMode === inputMode) { return; } + + this._inputMode = inputMode; + this.createInput(); + + this._updateDomInputType(); + this._updateSize(this._size.width, this._size.height); + } + + public setInputFlag (inputFlag) { + if (this._inputFlag === inputFlag) { return; } + + this._inputFlag = inputFlag; + this._updateDomInputType(); + + let textTransform = 'none'; + + if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + textTransform = 'uppercase'; + } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + textTransform = 'capitalize'; + } + + if (this._edTxt) { + this._edTxt.style.textTransform = textTransform; + this._edTxt.value = this._text; + } + } + + public setReturnType (returnType) { + this._returnType = returnType; + this._updateDomInputType(); + } + + public setFontSize (fontSize) { + this._edFontSize = fontSize || this._edFontSize; + if (this._edTxt) { + this._edTxt.style.fontSize = this._edFontSize + 'px'; + } + } + + public setFontColor (color) { + this._textColor = color; + if (this._edTxt) { + this._edTxt.style.color = color.toCSS('rgba'); + } + } + + public setSize (width, height) { + this._size.width = width; + this._size.height = height; + this._updateSize(width, height); + } + + public setNode (node) { + this._node = node; + } + + public update () { + // TODO: find better way to update matrix + // if (this._editing) { + this._updateMatrix(); + // } + } + + public clear () { + this._node = null; + this.setDelegate(null); + this.removeDom(); + } + + public _onTouchBegan (touch) { + + } + + public _onTouchEnded () { + this._beginEditing(); + } + + public _beginEditing () { + if (cc.sys.isMobile && !this._editing) { + // Pre adaptation + this._beginEditingOnMobile(); + } + + if (this._edTxt) { + this._edTxt.style.display = ''; + + const self = this; + function startFocus () { + self._edTxt!.focus(); + } + + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { + setTimeout(startFocus, FOCUS_DELAY_UC); + } else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { + setTimeout(startFocus, FOCUS_DELAY_FIREFOX); + } else { + startFocus(); + } + } + + this._editing = true; + } + + public _endEditing () { + const self = this; + const hideDomInputAndShowLabel = () => { + if (!self._alwaysOnTop && self._edTxt) { + self._edTxt.style.display = 'none'; + } + if (self._delegate && self._delegate.editBoxEditingDidEnded) { + self._delegate.editBoxEditingDidEnded(); + } + }; + if (this._editing) { + if (cc.sys.isMobile) { + // Delay end editing adaptation to ensure virtual keyboard is disapeared + setTimeout(() => { + self._endEditingOnMobile(); + hideDomInputAndShowLabel(); + }, DELAY_TIME); + } else { + hideDomInputAndShowLabel(); + } + } + this._editing = false; + } + + public _updateDomInputType () { + const inputMode = this._inputMode; + const edTxt = this._edTxt as HTMLInputElement; + if (!edTxt) { return; } + + if (this._inputFlag === InputFlag.PASSWORD) { + edTxt!.type = 'password'; + return; + } + + let type = edTxt.type; + if (inputMode === InputMode.EMAIL_ADDR) { + type = 'email'; + } else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) { + type = 'number'; + } else if (inputMode === InputMode.PHONE_NUMBER) { + type = 'number'; + edTxt.pattern = '[0-9]*'; + } else if (inputMode === InputMode.URL) { + type = 'url'; + } else { + type = 'text'; + + if (this._returnType === KeyboardReturnType.SEARCH) { + type = 'search'; + } + } + + edTxt.type = type; + } + + public _updateSize (newWidth, newHeight) { + const edTxt = this._edTxt; + if (!edTxt) { return; } + + edTxt.style.width = newWidth + 'px'; + edTxt.style.height = newHeight + 'px'; + } + + public _updateMatrix () { + if (!this._edTxt) { return; } + + const node = this._node; + let scaleX = cc.view._scaleX; + let scaleY = cc.view._scaleY; + const viewport = cc.view._viewportRect; + const dpr = cc.view._devicePixelRatio; + + node!.getWorldMatrix(_matrix); + const transform = node!.uiTransfromComp; + if (transform) { + _vec3.x = -transform.anchorX.x * transform.width; + _vec3.y = -transform.anchorY.y * transform.height; + } + + math.mat4.translate(_matrix, _matrix, _vec3); + + // let camera; + // can't find camera in editor + // if (CC_EDITOR) { + // camera = cc.Camera.main; + // } + // else { + // camera = cc.Camera.findCamera(node); + // } + const renderComp = node!.getComponent(UIRenderComponent); + if (!renderComp) { + return false; + } + // let canvas = cc.CanvasComponent.findView(renderComp); + const canvas = cc.director.root.ui.getScreen(renderComp.visibility); + if (!canvas) { + return; + } + + // camera.getWorldToCameraMatrix(_matrix_temp); + canvas.node.getWorldRT(_matrix_temp); + const m12 = _matrix_temp.m12; + const m13 = _matrix_temp.m13; + const center = cc.visibleRect.center; + _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13); + _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13); + + math.mat4.mul(_matrix_temp, _matrix_temp, _matrix); + + scaleX /= dpr; + scaleY /= dpr; + + const container = cc.game.container; + let a = _matrix_temp.m00 * scaleX; + const b = _matrix.m01; + const c = _matrix.m04; + let d = _matrix_temp.m05 * scaleY; + + let offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); + offsetX += viewport.x / dpr; + let offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); + offsetY += viewport.y / dpr; + const tx = _matrix_temp.m12 * scaleX + offsetX; + const ty = _matrix_temp.m13 * scaleY + offsetY; + + if (polyfill.zoomInvalid) { + this._updateSize(this._size.width * a, this._size.height * d); + a = 1; + d = 1; + } + + const matrix = 'matrix(' + a + ',' + -b + ',' + -c + ',' + d + ',' + tx + ',' + -ty + ')'; + this._edTxt.style.transform = matrix; + this._edTxt.style['-webkit-transform'] = matrix; + this._edTxt.style['transform-origin'] = '0px 100% 0px'; + this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; + } + + public _adjustEditBoxPosition () { + this._node!.getWorldMatrix(_matrix); + const y = _matrix.m13; + const windowHeight = cc.visibleRect.height; + const windowWidth = cc.visibleRect.width; + let factor = 0.5; + if (windowWidth > windowHeight) { + factor = 0.7; + } + setTimeout(() => { + if (window.scrollY < SCROLLY && y < windowHeight * factor) { + let scrollOffset = windowHeight * factor - y - window.scrollY; + if (scrollOffset < 35) { scrollOffset = 35; } + if (scrollOffset > 320) { scrollOffset = 320; } + window.scrollTo(0, scrollOffset); + } + }, DELAY_TIME); + } + + public createInput () { + if (this._inputMode === InputMode.ANY) { + this._createDomTextArea(); + } else { + this._createDomInput(); + } + } + + // Called before editbox focus to register cc.view status + public _beginEditingOnMobile () { + const self = this; + this.__orientationChanged = () => { + self._adjustEditBoxPosition(); + }; + window.addEventListener('orientationchange', this.__orientationChanged); + + if (cc.view.isAutoFullScreenEnabled()) { + this.__fullscreen = true; + cc.view.enableAutoFullScreen(false); + cc.screen.exitFullScreen(); + } else { + this.__fullscreen = false; + } + this.__autoResize = cc.view._resizeWithBrowserSize; + cc.view.resizeWithBrowserSize(false); + _currentEditBoxImpl = this; + } + + // Called after keyboard disappeared to readapte the game view + public _endEditingOnMobile () { + if (this.__rotateScreen) { + cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; + cc.game.container.style.transform = 'rotate(90deg)'; + + const view = cc.view; + const width = view._originalDesignResolutionSize.width; + const height = view._originalDesignResolutionSize.height; + if (width > 0) { + view.setDesignResolutionSize(width, height, view._resolutionPolicy); + } + this.__rotateScreen = false; + } + + if (this.__orientationChanged) { + window.removeEventListener('orientationchange', this.__orientationChanged); + } + + if (this.__fullscreen) { + cc.view.enableAutoFullScreen(true); + } + + // In case focus on editBox A from editBox B + // A disable resizeWithBrowserSize + // whilte B enable resizeWithBrowserSize + // Only _currentEditBoxImpl can enable resizeWithBrowserSize + if (this.__autoResize && _currentEditBoxImpl === this) { + cc.view.resizeWithBrowserSize(true); + } + } + + public _createDomInput () { + this.removeDom(); + + const tmpEdTxt = this._edTxt = document.createElement('input'); + tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontSize = this._edFontSize + 'px'; + tmpEdTxt.style.color = '#000000'; + tmpEdTxt.style.border = '0px'; + tmpEdTxt.style.background = 'transparent'; + tmpEdTxt.style.width = '100%'; + tmpEdTxt.style.height = '100%'; + // tmpEdTxt.style.active = 0; + tmpEdTxt.style.outline = 'medium'; + tmpEdTxt.style.padding = '0'; + tmpEdTxt.style.textTransform = 'uppercase'; + tmpEdTxt.style.display = 'none'; + tmpEdTxt.style.position = 'absolute'; + tmpEdTxt.style.bottom = '0px'; + tmpEdTxt.style.left = LEFT_PADDING + 'px'; + tmpEdTxt.style['-moz-appearance'] = 'textfield'; + tmpEdTxt.className = 'cocosEditBox'; + tmpEdTxt.style.fontFamily = 'Arial'; + + registerInputEventListener(tmpEdTxt, this); + + return tmpEdTxt; + } + + public _createDomTextArea () { + this.removeDom(); + + const tmpEdTxt = this._edTxt = document.createElement('textarea'); + // tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontSize = this._edFontSize + 'px'; + tmpEdTxt.style.color = '#000000'; + tmpEdTxt.style.border = '0'; + tmpEdTxt.style.background = 'transparent'; + tmpEdTxt.style.width = '100%'; + tmpEdTxt.style.height = '100%'; + // tmpEdTxt.style.active = 0; + tmpEdTxt.style.outline = 'medium'; + tmpEdTxt.style.padding = '0'; + tmpEdTxt.style.resize = 'none'; + tmpEdTxt.style.textTransform = 'uppercase'; + tmpEdTxt.style.overflowY = 'scroll'; + tmpEdTxt.style.display = 'none'; + tmpEdTxt.style.position = 'absolute'; + tmpEdTxt.style.bottom = '0px'; + tmpEdTxt.style.left = LEFT_PADDING + 'px'; + tmpEdTxt.className = 'cocosEditBox'; + tmpEdTxt.style.fontFamily = 'Arial'; + + registerInputEventListener(tmpEdTxt, this, true); + + return tmpEdTxt; + } + + public _addDomToGameContainer () { + cc.game.container.appendChild(this._edTxt); + } + + public removeDom () { + const edTxt = this._edTxt; + if (edTxt) { + // Remove listeners + const cbs = this.__eventListeners; + edTxt.removeEventListener('compositionstart', cbs.compositionstart); + edTxt.removeEventListener('compositionend', cbs.compositionend); + edTxt.removeEventListener('input', cbs.input); + edTxt.removeEventListener('focus', cbs.focus); + edTxt.removeEventListener('keypress', cbs.keypress); + edTxt.removeEventListener('blur', cbs.blur); + cbs.compositionstart = null; + cbs.compositionend = null; + cbs.input = null; + cbs.focus = null; + cbs.keypress = null; + cbs.blur = null; + + const hasChild = contains(cc.game.container, edTxt); + if (hasChild) { + cc.game.container.removeChild(edTxt); + } + } + this._edTxt = null; + } +} + +function _inputValueHandle (input, editBoxImpl) { + if (input.value.length > editBoxImpl._maxLength) { + input.value = input.value.slice(0, editBoxImpl._maxLength); + } + if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxTextChanged) { + if (editBoxImpl._text !== input.value) { + editBoxImpl._text = input.value; + editBoxImpl._delegate.editBoxTextChanged(editBoxImpl._text); + } + } +} + +function registerInputEventListener (tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea = false) { + let inputLock = false; + const cbs = editBoxImpl.eventListeners; + cbs.compositionstart = () => { + inputLock = true; + }; + tmpEdTxt.addEventListener('compositionstart', cbs.compositionstart); + + cbs.compositionend = function () { + inputLock = false; + _inputValueHandle(this, editBoxImpl); + }; + tmpEdTxt.addEventListener('compositionend', cbs.compositionend); + + cbs.input = function () { + if (inputLock) { + return; + } + _inputValueHandle(this, editBoxImpl); + }; + tmpEdTxt.addEventListener('input', cbs.input); + + cbs.focus = function () { + this.style.fontSize = editBoxImpl.fontSize + 'px'; + this.style.color = editBoxImpl.textColor.toCSS('rgba'); + // When stayOnTop, input will swallow touch event + if (editBoxImpl.alwayOnTop) { + editBoxImpl.editing = true; + } + + if (cc.sys.isMobile) { + editBoxImpl._beginEditingOnMobile(); + } + + if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingDidBegan) { + editBoxImpl.delegate.editBoxEditingDidBegan(); + } + + }; + tmpEdTxt.addEventListener('focus', cbs.focus); + + cbs.keypress = function (e) { + if (e.keyCode === macro.KEY.enter) { + e.stopPropagation(); + + if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingReturn) { + editBoxImpl.delegate.editBoxEditingReturn(); + } + if (!isTextarea) { + editBoxImpl.text = this.value; + editBoxImpl._endEditing(); + cc.game.canvas.focus(); + } + } + }; + tmpEdTxt.addEventListener('keypress', cbs.keypress); + + cbs.blur = function () { + editBoxImpl.text = this.value; + editBoxImpl._endEditing(); + }; + tmpEdTxt.addEventListener('blur', cbs.blur); + + editBoxImpl._addDomToGameContainer(); +} diff --git a/cocos/2d/ui/editbox/types.js b/cocos/3d/ui/components/editbox/types.ts similarity index 90% rename from cocos/2d/ui/editbox/types.js rename to cocos/3d/ui/components/editbox/types.ts index ca1757d2e4..49b1bb0570 100644 --- a/cocos/2d/ui/editbox/types.js +++ b/cocos/3d/ui/components/editbox/types.ts @@ -22,50 +22,53 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + +import { Enum } from '../../../../core/value-types'; /** * !#en Enum for keyboard return types * !#zh 键盘的返回键类型 * @readonly * @enum EditBox.KeyboardReturnType */ -let KeyboardReturnType = cc.Enum({ +export enum KeyboardReturnType { /** * !#en TODO * !#zh 默认 * @property {Number} DEFAULT */ - DEFAULT: 0, + DEFAULT = 0, /** * !#en TODO * !#zh 完成类型 * @property {Number} DONE */ - DONE: 1, + DONE = 1, /** * !#en TODO * !#zh 发送类型 * @property {Number} SEND */ - SEND: 2, + SEND = 2, /** * !#en TODO * !#zh 搜索类型 * @property {Number} SEARCH */ - SEARCH: 3, + SEARCH = 3, /** * !#en TODO * !#zh 跳转类型 * @property {Number} GO */ - GO: 4, + GO = 4, /** * !#en TODO * !#zh 下一个类型 * @property {Number} NEXT */ - NEXT: 5 -}); + NEXT = 5, +} +Enum(KeyboardReturnType); /** * !#en The EditBox's InputMode defines the type of text that the user is allowed to enter. @@ -73,37 +76,37 @@ let KeyboardReturnType = cc.Enum({ * @readonly * @enum EditBox.InputMode */ -let InputMode = cc.Enum({ +export enum InputMode { /** * !#en TODO * !#zh 用户可以输入任何文本,包括换行符。 * @property {Number} ANY */ - ANY: 0, + ANY = 0, /** * !#en The user is allowed to enter an e-mail address. * !#zh 允许用户输入一个电子邮件地址。 * @property {Number} EMAIL_ADDR */ - EMAIL_ADDR: 1, + EMAIL_ADDR = 1, /** * !#en The user is allowed to enter an integer value. * !#zh 允许用户输入一个整数值。 * @property {Number} NUMERIC */ - NUMERIC: 2, + NUMERIC = 2, /** * !#en The user is allowed to enter a phone number. * !#zh 允许用户输入一个电话号码。 * @property {Number} PHONE_NUMBER */ - PHONE_NUMBER: 3, + PHONE_NUMBER = 3, /** * !#en The user is allowed to enter a URL. * !#zh 允许用户输入一个 URL。 * @property {Number} URL */ - URL: 4, + URL = 4, /** * !#en * The user is allowed to enter a real number value. @@ -112,14 +115,16 @@ let InputMode = cc.Enum({ * 允许用户输入一个实数。 * @property {Number} DECIMAL */ - DECIMAL: 5, + DECIMAL = 5, /** * !#en The user is allowed to enter any text, except for line breaks. * !#zh 除了换行符以外,用户可以输入任何文本。 * @property {Number} SINGLE_LINE */ - SINGLE_LINE: 6 -}); + SINGLE_LINE = 6, +} + +Enum(InputMode); /** * !#en Enum for the EditBox's input flags @@ -127,7 +132,7 @@ let InputMode = cc.Enum({ * @readonly * @enum EditBox.InputFlag */ -let InputFlag = cc.Enum({ +export enum InputFlag { /** * !#en * Indicates that the text entered is confidential data that should be @@ -136,7 +141,7 @@ let InputFlag = cc.Enum({ * 表明输入的文本是保密的数据,任何时候都应该隐藏起来,它隐含了 EDIT_BOX_INPUT_FLAG_SENSITIVE。 * @property {Number} PASSWORD */ - PASSWORD: 0, + PASSWORD = 0, /** * !#en * Indicates that the text entered is sensitive data that the @@ -148,7 +153,7 @@ let InputFlag = cc.Enum({ * 一个信用卡号码就是一个敏感数据的例子。 * @property {Number} SENSITIVE */ - SENSITIVE: 1, + SENSITIVE = 1, /** * !#en * This flag is a hint to the implementation that during text editing, @@ -157,7 +162,7 @@ let InputFlag = cc.Enum({ * 这个标志用来指定在文本编辑的时候,是否把每一个单词的首字母大写。 * @property {Number} INITIAL_CAPS_WORD */ - INITIAL_CAPS_WORD: 2, + INITIAL_CAPS_WORD = 2, /** * !#en * This flag is a hint to the implementation that during text editing, @@ -166,22 +171,18 @@ let InputFlag = cc.Enum({ * 这个标志用来指定在文本编辑是否每个句子的首字母大写。 * @property {Number} INITIAL_CAPS_SENTENCE */ - INITIAL_CAPS_SENTENCE: 3, + INITIAL_CAPS_SENTENCE = 3, /** * !#en Capitalize all characters automatically. * !#zh 自动把输入的所有字符大写。 * @property {Number} INITIAL_CAPS_ALL_CHARACTERS */ - INITIAL_CAPS_ALL_CHARACTERS: 4, + INITIAL_CAPS_ALL_CHARACTERS = 4, /** * Don't do anything with the input text. * @property {Number} DEFAULT */ - DEFAULT: 5 -}); + DEFAULT = 5, +} -module.exports = { - KeyboardReturnType: KeyboardReturnType, - InputMode: InputMode, - InputFlag: InputFlag -}; +Enum(InputFlag); diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts new file mode 100644 index 0000000000..79b96d186c --- /dev/null +++ b/cocos/3d/ui/components/label-component.ts @@ -0,0 +1,693 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ +// @ts-check +import Font from '../../../assets/CCFont'; +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 macro from '../../../core/platform/CCMacro'; +import { Enum } from '../../../core/value-types'; +import { MeshBuffer } from '../mesh-buffer'; +import { UIRenderComponent } from './ui-render-component'; +// import { value } from '../../../core/utils/js'; + +/** + * !#en Enum for text alignment. + * !#zh 文本横向对齐类型 + * @enum Label.HorizontalAlign + */ +/** + * !#en Alignment left for text. + * !#zh 文本内容左对齐。 + * @property {Number} LEFT + */ +/** + * !#en Alignment center for text. + * !#zh 文本内容居中对齐。 + * @property {Number} CENTER + */ +/** + * !#en Alignment right for text. + * !#zh 文本内容右边对齐。 + * @property {Number} RIGHT + */ +const HorizontalAlign = macro.TextAlignment; + +/** + * !#en Enum for vertical text alignment. + * !#zh 文本垂直对齐类型 + * @enum Label.VerticalAlign + */ +/** + * !#en Vertical alignment top for text. + * !#zh 文本顶部对齐。 + * @property {Number} TOP + */ +/** + * !#en Vertical alignment center for text. + * !#zh 文本居中对齐。 + * @property {Number} CENTER + */ +/** + * !#en Vertical alignment bottom for text. + * !#zh 文本底部对齐。 + * @property {Number} BOTTOM + */ +const VerticalAlign = macro.VerticalTextAlignment; + +/** + * !#en Enum for Overflow. + * !#zh Overflow 类型 + * @enum Label.Overflow + */ +/** + * !#en NONE. + * !#zh 不做任何限制。 + * @property {Number} NONE + */ +/** + * !#en In CLAMP mode, when label content goes out of the bounding box, it will be clipped. + * !#zh CLAMP 模式中,当文本内容超出边界框时,多余的会被截断。 + * @property {Number} CLAMP + */ +/** + * !#en In SHRINK mode, the font size will change dynamically to adapt the content size. + * !#zh SHRINK 模式,字体大小会动态变化,以适应内容大小。 + * @property {Number} SHRINK + */ +/** + * !#en In RESIZE_HEIGHT mode, you can only change the width of label and the height is changed automatically. + * !#zh 在 RESIZE_HEIGHT 模式下,只能更改文本的宽度,高度是自动改变的。 + * @property {Number} RESIZE_HEIGHT + */ +const Overflow = Enum({ + NONE: 0, + CLAMP: 1, + SHRINK: 2, + RESIZE_HEIGHT: 3, +}); + +/** + * !#en Enum for font type. + * !#zh Type 类型 + * @enum Label.Type + */ +/** + * !#en The TTF font type. + * !#zh TTF字体 + * @property {Number} TTF + */ +/** + * !#en The bitmap font type. + * !#zh 位图字体 + * @property {Number} BMFont + */ +/** + * !#en The system font type. + * !#zh 系统字体 + * @property {Number} SystemFont + */ + +/** + * !#en The Label Component. + * !#zh 文字标签组件 + * @class Label + * @extends UIRenderComponent + */ +@ccclass('cc.LabelComponent') +@executionOrder(100) +@menu('UI/Label') +@executeInEditMode +export class LabelComponent extends UIRenderComponent { + + /** + * !#en Content string of label. + * !#zh 标签显示的文本内容。 + * @property {String} string + */ + @property + get string () { + return this._string; + } + set string (value: string) { + value = value.toString(); + if (this._string === value) { + return; + } + + this._string = value; + this._updateRenderData(); + this._checkStringEmpty(); + } + + /** + * !#en Horizontal Alignment of label. + * !#zh 文本内容的水平对齐方式。 + * @property {Label.HorizontalAlign} horizontalAlign + */ + @property({ + type: HorizontalAlign, + }) + get horizontalAlign () { + return this._horizontalAlign; + } + + set horizontalAlign (value: number) { + if (this._horizontalAlign === value) { + return; + } + + this._horizontalAlign = value; + this._updateRenderData(); + } + + /** + * !#en Vertical Alignment of label. + * !#zh 文本内容的垂直对齐方式。 + * @property {Label.VerticalAlign} verticalAlign + */ + @property({ + type: VerticalAlign, + }) + get verticalAlign () { + return this._verticalAlign; + } + + set verticalAlign (value: number) { + if (this._verticalAlign === value) { + return; + } + + this._verticalAlign = value; + this._updateRenderData(); + } + + /** + * !#en The actual rendering font size in shrink mode + * !#zh SHRINK 模式下面文本实际渲染的字体大小 + * @property {Number} actualFontSize + */ + @property + get actualFontSize () { + return this._actualFontSize; + } + + /** + * !#en Font size of label. + * !#zh 文本字体大小。 + * @property {Number} fontSize + */ + @property + get fontSize () { + return this._fontSize; + } + + set fontSize (value: number) { + if (this._fontSize === value) { + return; + } + + this._fontSize = value; + this._updateRenderData(); + } + + /** + * !#en Font family of label, only take effect when useSystemFont property is true. + * !#zh 文本字体名称, 只在 useSystemFont 属性为 true 的时候生效。 + * @property {String} fontFamily + */ + get fontFamily () { + return this._fontFamily; + } + + set fontFamily (value: string) { + if (this._fontFamily === value) { + return; + } + + this._fontFamily = value; + this._updateRenderData(); + } + + /** + * !#en Line Height of label. + * !#zh 文本行高。 + * @property {Number} lineHeight + */ + @property + get lineHeight () { + return this._lineHeight; + } + set lineHeight (value: number) { + if (this._lineHeight === value) { + return; + } + + this._lineHeight = value; + this._updateRenderData(); + } + + /** + * !#en Overflow of label. + * !#zh 文字显示超出范围时的处理方式。 + * @property {Label.Overflow} overflow + */ + @property + get overflow () { + return this._overflow; + } + + set overflow (value: number) { + if (this._overflow === value) { + return; + } + + this._overflow = value; + this._updateRenderData(); + } + + /** + * !#en Whether auto wrap label when string width is large than label width. + * !#zh 是否自动换行。 + * @property {Boolean} enableWrapText + */ + @property + get enableWrapText () { + return this._enableWrapText; + } + set enableWrapText (value: boolean) { + if (this._enableWrapText === value) { + return; + } + + this._enableWrapText = value; + this._updateRenderData(); + } + + /** + * !#en The font of label. + * !#zh 文本字体。 + * @property {Font} font + */ + @property({ + type: Font, + }) + get font () { + // return this._N$file; + return this._font; + } + + set font (value: Font | null) { + if (this._font === value) { return; } + + // if delete the font, we should change isSystemFontUsed to true + this._isSystemFontUsed = !value; + + if (CC_EDITOR && value) { + this._userDefinedFont = value; + } + + // this._N$file = value; + this._font = value; + this._bmFontOriginalSize = -1; + // if (value && this._isSystemFontUsed) + // this._isSystemFontUsed = false; + + if (typeof value === 'string') { + cc.warnID(4000); + } + + if (value instanceof cc.BitmapFont) { + this._bmFontOriginalSize = value.fontSize; + } + + if (this._renderData) { + this.destroyRenderData(); + this._renderData = null; + } + // this._fontAtlas = null; + this._updateAssembler(); + this._applyFontTexture(true); + this._updateRenderData(); + } + + /** + * !#en Whether use system font name or not. + * !#zh 是否使用系统字体。 + * @property {Boolean} isSystemFontUsed + */ + @property + get useSystemFont () { + return this._isSystemFontUsed; + } + + set useSystemFont (value: boolean) { + if (this._isSystemFontUsed === value) { + return; + } + + this.destroyRenderData(); + this._renderData = null; + + if (CC_EDITOR) { + if (!value && this._isSystemFontUsed && this._userDefinedFont) { + this.font = this._userDefinedFont; + this.spacingX = this._spacingX; + return; + } + } + + this._isSystemFontUsed = !!value; + if (value) { + this.font = null; + this._updateAssembler(); + this._updateRenderData(); + this._checkStringEmpty(); + } + // else if (!this._userDefinedFont) { + // this.disableRender(); + // } + + } + + @property + get spacingX () { + return this._spacingX; + } + + set spacingX (value: number) { + if (this._spacingX === value) { + return; + } + + this._spacingX = value; + this._updateRenderData(); + } + + /** + * !#en Whether the font is bold or not. + * !#zh 字体是否加粗。 + * @property {Boolean} isBold + */ + get isBold () { + return this._isBold; + } + + set isBold (value: boolean) { + if (this._isBold === value) { + return; + } + + this._isBold = value; + } + + /** + * !#en Whether the font is tilted or not. + * !#zh 字体是否倾斜。 + * @property {Boolean} isBold + */ + get isItalic () { + return this._isItalic; + } + + set isItalic (value: boolean) { + if (this._isItalic === value) { + return; + } + + this._isItalic = value; + } + + /** + * !#en Whether the font is underlined. + * !#zh 字体是否加下划线。 + * @property {Boolean} isBold + */ + get isUnderline () { + return this._isUnderline; + } + + set isUnderline (value: boolean) { + if (this._isUnderline === value) { + return; + } + + this._isUnderline = value; + } + + public static HorizontalAlign = HorizontalAlign; + public static VerticalAlign = VerticalAlign; + public static Overflow = Overflow; + @property + public _useOriginalSize: boolean = true; + @property + public _string: string = 'label'; + @property + public _horizontalAlign: number = HorizontalAlign.LEFT; + @property + public _verticalAlign: number = VerticalAlign.TOP; + @property + public _actualFontSize: number = 0; + @property + public _fontSize: number = 40; + @property + public _fontFamily: string = 'Arial'; + @property + public _lineHeight: number = 40; + @property + public _overflow: number = Overflow.NONE; + @property + public _enableWrapText: boolean = true; + // // 这个保存了旧项目的 file 数据 + // _N$file = null; + @property + public _font: Font | null = null; + @property + public _isSystemFontUsed: boolean = true; + @property + public _bmFontOriginalSize: number = -1; + @property + public _spacingX: number = 0; + @property + public _isItalic: boolean = false; + @property + public _isBold: boolean = false; + @property + public _isUnderline: boolean = false; + + // don't need serialize + private _texture: Texture2D | null = null; + private _ttfTexture: Texture2D | null = null; + private _userDefinedFont: Font | null = null; + private _assemblerData: object|null = null; + + constructor () { + super(); + if (CC_EDITOR) { + this._userDefinedFont = null; + } + + this._assemblerData = null; + + this._ttfTexture = null; + } + + public onEnable () { + // this._super(); + super.onEnable(); + + // TODO: Hack for barbarians + if (!this._font && !this._isSystemFontUsed) { + this.useSystemFont = true; + } + // Reapply default font family if necessary + if (this._isSystemFontUsed && !this._fontFamily) { + this.fontFamily = 'Arial'; + } + + // Keep track of Node size + this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this); + this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this); + + this._checkStringEmpty(); + this._updateRenderData(true); + // this._updateAssembler(); + // this._activateMaterial(); + } + + public onDisable () { + super.onDisable(); + // this._super(); + this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this); + this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this); + } + + public onDestroy () { + if (this._assembler && this._assembler._resetAssemblerData) { + this._assembler._resetAssemblerData(this._assemblerData); + } + + this._assemblerData = null; + if (this._ttfTexture) { + this._ttfTexture.destroy(); + this._ttfTexture = null; + } + // 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; + } + } + return result; + } + + public _checkStringEmpty () { + // this.markForRender(!!this.string); + } + + public _updateAssembler () { + const assembler = LabelComponent.Assembler.getAssembler(this); + + if (this._assembler !== assembler) { + this.destroyRenderData(); + this._assembler = assembler; + } + + if (!this._renderData) { + this._renderData = this._assembler!.createData(this); + this._renderData.material = this.material; + } + } + + public _activateMaterial (force: boolean) { + let material = this.material; + if (material && !force) { + return; + } + + if (!material) { + // material = new SpriteMaterial(); + this.material = cc.builtinResMgr.get('sprite-material'); + material = this.material; + } + // Setup blend function for premultiplied ttf label texture + if (this._texture === this._ttfTexture) { + this._srcBlendFactor = cc.macro.BlendFactor.ONE; + } else { + this._srcBlendFactor = cc.macro.BlendFactor.SRC_ALPHA; + } + material!.setProperty('u_texSampler', this._texture); + // For batch rendering, do not use uniform color. + // material!.useColor = false; + // this._updateMaterial(material); + } + + public _applyFontTexture (force: boolean) { + const font = this._font; + if (font instanceof cc.BitmapFont) { + const spriteFrame = font.spriteFrame; + const self = this; + const onBMFontTextureLoaded = function () { + // TODO: old texture in material have been released by loader + self._texture = spriteFrame; + self._activateMaterial(force); + + if (force) { + self._assembler && self._assembler.updateRenderData(self); + } + }; + // cannot be activated if texture not loaded yet + if (spriteFrame && spriteFrame.textureLoaded()) { + onBMFontTextureLoaded(); + } else { + // this.disableRender(); + + if (spriteFrame) { + spriteFrame.once('load', onBMFontTextureLoaded, this); + spriteFrame.ensureLoadTexture(); + } + } + } else { + if (!this._ttfTexture) { + this._ttfTexture = new cc.SpriteFrame(); + // this._ttfTexture.setFilters(cc.Texture2D.Filter.LINEAR, cc.Texture2D.Filter.LINEAR); + // this._ttfTexture.setWrapMode(cc.Texture2D.WrapMode.CLAMP_TO_EDGE, cc.Texture2D.WrapMode.CLAMP_TO_EDGE); + // TTF texture in web will blend with canvas or body background color + if (!CC_JSB) { + // this._ttfTexture.setPremultiplyAlpha(true); + } + this._assemblerData = this._assembler._getAssemblerData(); + 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) { + this._assembler.updateRenderData(this); + } + } + } + + public _updateColor () { + const font = this.font; + if (font instanceof cc.BitmapFont) { + // this._super(); + } else { + this._updateRenderData(false); + // this.node._renderFlag &= ~RenderFlow.FLAG_COLOR; + } + } + + public _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); + } + } +} diff --git a/cocos/2d/ui/CCLayout.js b/cocos/3d/ui/components/layout-component.ts similarity index 52% rename from cocos/2d/ui/CCLayout.js rename to cocos/3d/ui/components/layout-component.ts index ad0c8b7ff9..c19b245d94 100644 --- a/cocos/2d/ui/CCLayout.js +++ b/cocos/3d/ui/components/layout-component.ts @@ -24,66 +24,72 @@ THE SOFTWARE. ****************************************************************************/ -const NodeEvent = require('../CCNode').EventType; - +import { Component } from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { Enum, Size } from '../../../core/value-types'; +import { Node } from '../../../scene-graph/node'; +const NodeEvent = Node.EventType; /** * !#en Enum for Layout type * !#zh 布局类型 * @enum Layout.Type */ -var Type = cc.Enum({ +enum Type { /** * !#en None Layout * !#zh 取消布局 - *@property {Number} NONE */ - NONE: 0, + NONE = 0, /** * !#en Horizontal Layout * !#zh 水平布局 * @property {Number} HORIZONTAL */ - HORIZONTAL: 1, + HORIZONTAL = 1, /** * !#en Vertical Layout * !#zh 垂直布局 * @property {Number} VERTICAL */ - VERTICAL: 2, + VERTICAL = 2, /** * !#en Grid Layout * !#zh 网格布局 * @property {Number} GRID */ - GRID: 3, -}); + GRID = 3, +} + +Enum(Type); /** * !#en Enum for Layout Resize Mode * !#zh 缩放模式 * @enum Layout.ResizeMode */ -var ResizeMode = cc.Enum({ +enum ResizeMode { /** * !#en Don't do any scale. * !#zh 不做任何缩放 * @property {Number} NONE */ - NONE: 0, + NONE = 0, /** * !#en The container size will be expanded with its children's size. * !#zh 容器的大小会根据子节点的大小自动缩放。 * @property {Number} CONTAINER */ - CONTAINER: 1, + CONTAINER = 1, /** * !#en Child item size will be adjusted with the container's size. * !#zh 子节点的大小会随着容器的大小自动缩放。 * @property {Number} CHILDREN */ - CHILDREN: 2 -}); + CHILDREN = 2, +} + +Enum(ResizeMode); /** * !#en Enum for Grid Layout start axis direction. @@ -91,20 +97,22 @@ var ResizeMode = cc.Enum({ * !#zh 布局轴向,只用于 GRID 布局。 * @enum Layout.AxisDirection */ -var AxisDirection = cc.Enum({ +enum AxisDirection { /** * !#en The horizontal axis. * !#zh 进行水平方向布局 * @property {Number} HORIZONTAL */ - HORIZONTAL: 0, + HORIZONTAL = 0, /** * !#en The vertical axis. * !#zh 进行垂直方向布局 * @property {Number} VERTICAL */ - VERTICAL: 1, -}); + VERTICAL = 1, +} + +Enum(AxisDirection); /** * !#en Enum for vertical layout direction. @@ -112,20 +120,22 @@ var AxisDirection = cc.Enum({ * !#zh 垂直方向布局方式 * @enum Layout.VerticalDirection */ -var VerticalDirection = cc.Enum({ +enum VerticalDirection { /** * !#en Items arranged from bottom to top. * !#zh 从下到上排列 * @property {Number} BOTTOM_TO_TOP */ - BOTTOM_TO_TOP: 0, + BOTTOM_TO_TOP = 0, /** * !#en Items arranged from top to bottom. * !#zh 从上到下排列 * @property {Number} TOP_TO_BOTTOM */ - TOP_TO_BOTTOM: 1, -}); + TOP_TO_BOTTOM = 1, +} + +Enum(VerticalDirection); /** * !#en Enum for horizontal layout direction. @@ -133,20 +143,20 @@ var VerticalDirection = cc.Enum({ * !#zh 水平方向布局方式 * @enum Layout.HorizontalDirection */ -var HorizontalDirection = cc.Enum({ +enum HorizontalDirection { /** * !#en Items arranged from left to right. * !#zh 从左往右排列 - * @property {Number} LEFT_TO_RIGHT */ - LEFT_TO_RIGHT: 0, + LEFT_TO_RIGHT = 0, /** * !#en Items arranged from right to left. * !#zh 从右往左排列 - *@property {Number} RIGHT_TO_LEFT */ - RIGHT_TO_LEFT: 1, -}); + RIGHT_TO_LEFT = 1, +} + +Enum(HorizontalDirection); /** * !#en @@ -163,257 +173,333 @@ var HorizontalDirection = cc.Enum({ * @class Layout * @extends Component */ -var Layout = cc.Class({ - name: 'cc.Layout', - extends: require('./CCComponent'), +@ccclass('cc.LayoutComponent') +@executionOrder(100) +@menu('UI/Layout') +@executeInEditMode +export class LayoutComponent extends Component { - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/Layout', - help: 'i18n:COMPONENT.help_url.layout', - inspector: 'packages://inspector/inspectors/comps/cclayout.js', - executeInEditMode: true, - }, + /** + * !#en The layout type. + * !#zh 布局类型 + * @property {Layout.Type} type + * @default Layout.Type.NONE + */ + @property + get type () { + return this._N$layoutType; + } - properties: { - _layoutSize: cc.size(300, 200), - _layoutDirty: { - default: true, - serializable: false, - }, + set type (value) { + this._N$layoutType = value; - _resize: ResizeMode.NONE, + if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + // if (reLayouted) { + // return; + // } + } + this._doLayoutDirty(); + } + /** + * !#en + * The are three resize modes for Layout. + * None, resize Container and resize children. + * !#zh 缩放模式 + * @property {Layout.ResizeMode} resizeMode + * @default ResizeMode.NONE + */ + @property({ + type: ResizeMode, + }) + get resizeMode () { + return this._resize; + } + set resizeMode (value) { + if (this.type === Type.NONE && value === ResizeMode.CHILDREN) { + return; + } - //TODO: refactoring this name after data upgrade machanism is out. - _N$layoutType: Type.NONE, - /** - * !#en The layout type. - * !#zh 布局类型 - * @property {Layout.Type} type - * @default Layout.Type.NONE - */ - type: { - type: Type, - get: function () { - return this._N$layoutType; - }, - set: function (value) { - this._N$layoutType = value; + this._resize = value; + if (CC_EDITOR && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + // if (reLayouted) { + // return; + // } + } + this._doLayoutDirty(); + } - if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { - var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); - if (reLayouted) { - return; - } - } - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.layout_type', - animatable: false, - }, + /** + * !#en The cell size for grid layout. + * !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。 + * @property {Size} cellSize + * @default cc.size(40, 40) + */ + @property + get cellSize () { + return this._cellSize; + } + set cellSize (value: Size) { + if (this._cellSize === value) { + return; + } - /** - * !#en - * The are three resize modes for Layout. - * None, resize Container and resize children. - * !#zh 缩放模式 - * @property {Layout.ResizeMode} resizeMode - * @default ResizeMode.NONE - */ - resizeMode: { - type: ResizeMode, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.resize_mode', - animatable: false, - get: function () { - return this._resize; - }, - set: function (value) { - if (this.type === Type.NONE && value === ResizeMode.CHILDREN) { - return; - } + this._cellSize = value; + this._doLayoutDirty(); + } - this._resize = value; - if (CC_EDITOR && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) { - var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); - if (reLayouted) { - return; - } - } - this._doLayoutDirty(); - }, - }, + /** + * !#en + * The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first, + * and then break line on demand. Choose vertical if you want to layout vertically at first . + * !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 + * @property {Layout.AxisDirection} startAxis + */ + @property + get startAxis () { + return this._startAxis; + } - /** - * !#en The cell size for grid layout. - * !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。 - * @property {Size} cellSize - * @default cc.size(40, 40) - */ - cellSize: { - default: cc.size(40, 40), - tooltip: CC_DEV && 'i18n:COMPONENT.layout.cell_size', - type: cc.Size, - notify: function () { - this._doLayoutDirty(); - }, - }, + set startAxis (value) { + if (this._startAxis === value) { + return; + } - /** - * !#en - * The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first, - * and then break line on demand. Choose vertical if you want to layout vertically at first . - * !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 - * @property {Layout.AxisDirection} startAxis - */ - startAxis: { - default: AxisDirection.HORIZONTAL, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.start_axis', - type: AxisDirection, - notify: function () { - if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { - var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); - if (reLayouted) { - return; - } - } - this._doLayoutDirty(); - }, - animatable: false - }, + if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + // if (reLayouted) { + // return; + // } + } - _N$padding: { - default: 0 - }, - /** - * !#en The left padding of layout, it only effect the layout in one direction. - * !#zh 容器内左边距,只会在一个布局方向上生效。 - * @property {Number} paddingLeft - */ - paddingLeft: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_left', - notify: function () { - this._doLayoutDirty(); - }, - }, + this._startAxis = value; + this._doLayoutDirty(); + } + /** + * !#en The left padding of layout, it only effect the layout in one direction. + * !#zh 容器内左边距,只会在一个布局方向上生效。 + * @property {Number} paddingLeft + */ + @property + get paddingLeft () { + return this._paddingLeft; + } + set paddingLeft (value) { + if (this._paddingLeft === value) { + return; + } - /** - * !#en The right padding of layout, it only effect the layout in one direction. - * !#zh 容器内右边距,只会在一个布局方向上生效。 - * @property {Number} paddingRight - */ - paddingRight: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_right', - notify: function () { - this._doLayoutDirty(); - }, - }, + this._paddingLeft = value; + this._doLayoutDirty(); + } - /** - * !#en The top padding of layout, it only effect the layout in one direction. - * !#zh 容器内上边距,只会在一个布局方向上生效。 - * @property {Number} paddingTop - */ - paddingTop: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_top', - notify: function () { - this._doLayoutDirty(); - }, - }, + /** + * !#en The right padding of layout, it only effect the layout in one direction. + * !#zh 容器内右边距,只会在一个布局方向上生效。 + * @property {Number} paddingRight + */ + @property + get paddingRight () { + return this._paddingRight; + } + set paddingRight (value) { + if (this._paddingRight === value) { + return; + } - /** - * !#en The bottom padding of layout, it only effect the layout in one direction. - * !#zh 容器内下边距,只会在一个布局方向上生效。 - * @property {Number} paddingBottom - */ - paddingBottom: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_bottom', - notify: function () { - this._doLayoutDirty(); - }, - }, + this._paddingRight = value; + this._doLayoutDirty(); + } - /** - * !#en The distance in x-axis between each element in layout. - * !#zh 子节点之间的水平间距。 - * @property {Number} spacingX - */ - spacingX: { - default: 0, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.space_x' - }, + /** + * !#en The top padding of layout, it only effect the layout in one direction. + * !#zh 容器内上边距,只会在一个布局方向上生效。 + * @property {Number} paddingTop + */ + @property + get paddingTop () { + return this._paddingTop; + } + set paddingTop (value) { + if (this._paddingTop === value) { + return; + } - /** - * !#en The distance in y-axis between each element in layout. - * !#zh 子节点之间的垂直间距。 - * @property {Number} spacingY - */ - spacingY: { - default: 0, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.space_y' - }, + this._paddingTop = value; + this._doLayoutDirty(); + } - /** - * !#en - * Only take effect in Vertical layout mode. - * This option changes the start element's positioning. - * !#zh 垂直排列子节点的方向。 - * @property {Layout.VerticalDirection} verticalDirection - */ - verticalDirection: { - default: VerticalDirection.TOP_TO_BOTTOM, - type: VerticalDirection, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.vertical_direction', - animatable: false - }, + /** + * !#en The bottom padding of layout, it only effect the layout in one direction. + * !#zh 容器内下边距,只会在一个布局方向上生效。 + * @property {Number} paddingBottom + */ + @property + get paddingBottom () { + return this._paddingBottom; + } + set paddingBottom (value) { + if (this._paddingBottom === value) { + return; + } - /** - * !#en - * Only take effect in Horizontal layout mode. - * This option changes the start element's positioning. - * !#zh 水平排列子节点的方向。 - * @property {Layout.HorizontalDirection} horizontalDirection - */ - horizontalDirection: { - default: HorizontalDirection.LEFT_TO_RIGHT, - type: HorizontalDirection, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.horizontal_direction', - animatable: false - }, - }, + this._paddingBottom = value; + this._doLayoutDirty(); + } - statics: { - Type: Type, - VerticalDirection: VerticalDirection, - HorizontalDirection: HorizontalDirection, - ResizeMode: ResizeMode, - AxisDirection: AxisDirection, - }, + /** + * !#en The distance in x-axis between each element in layout. + * !#zh 子节点之间的水平间距。 + * @property {Number} spacingX + */ + get spacingX () { + return this._spacingX; + } - _migratePaddingData: function () { + set spacingX (value) { + if (this._spacingX === value) { + return; + } + + this._spacingX = value; + this._doLayoutDirty(); + } + + /** + * !#en The distance in y-axis between each element in layout. + * !#zh 子节点之间的垂直间距。 + * @property {Number} spacingY + */ + @property + get spacingY () { + return this._spacingY; + } + + set spacingY (value) { + if (this._spacingY === value) { + return; + } + + this._spacingY = value; + this._doLayoutDirty(); + } + + /** + * !#en + * Only take effect in Vertical layout mode. + * This option changes the start element's positioning. + * !#zh 垂直排列子节点的方向。 + * @property {VerticalDirection} verticalDirection + */ + @property({ + type: VerticalDirection, + }) + get verticalDirection () { + return this._verticalDirection; + } + + set verticalDirection (value: VerticalDirection) { + if (this._verticalDirection === value) { + return; + } + + this._verticalDirection = value; + this._doLayoutDirty(); + } + + /** + * !#en + * Only take effect in Horizontal layout mode. + * This option changes the start element's positioning. + * !#zh 水平排列子节点的方向。 + * @property {Layout.HorizontalDirection} horizontalDirection + */ + @property({ + type: HorizontalDirection, + }) + get horizontalDirection () { + return this._horizontalDirection; + } + + set horizontalDirection (value: HorizontalDirection) { + if (this._horizontalDirection === value) { + return; + } + + this._horizontalDirection = value; + this._doLayoutDirty(); + } + + /** + * !#en The padding of layout, it effects the layout in four direction. + * !#zh 容器内边距,该属性会在四个布局方向上生效。 + * @property {Number} padding + */ + @property + get padding() { + return this._paddingLeft; + } + + set padding(value) { + this._N$padding = value; + + this._migratePaddingData(); + this._doLayoutDirty(); + } + + /** + * !#en Adjust the layout if the children scaled. + * !#zh 子节点缩放比例是否影响布局。 + * @property affectedByScale + * @type {Boolean} + * @default false + */ + @property + get affectedByScale() { + return this._affectedByScale; + } + + set affectedByScale(value) { + this._affectedByScale = value; + this._doLayoutDirty(); + } + + public static Type = Type; + public static VerticalDirection = VerticalDirection; + public static HorizontalDirection = HorizontalDirection; + public static ResizeMode = ResizeMode; + public static AxisDirection = AxisDirection; + + private _layoutDirty = true; + private _resize = ResizeMode.NONE; + + // TODO: refactoring this name after data upgrade machanism is out. + private _N$layoutType = Type.NONE; + private _N$padding = 0; + private _cellSize = cc.size(40, 40); + private _startAxis = AxisDirection.HORIZONTAL; + private _paddingLeft = 0; + private _paddingRight = 0; + private _paddingTop = 0; + private _paddingBottom = 0; + private _spacingX = 0; + private _spacingY = 0; + private _layoutSize = cc.size(300, 200); + private _verticalDirection = VerticalDirection.TOP_TO_BOTTOM; + private _horizontalDirection = HorizontalDirection.LEFT_TO_RIGHT; + 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; this._N$padding = 0; - }, + } - onEnable: function () { + protected onEnable () { this._addEventListeners(); if (this.node.getContentSize().equals(cc.size(0, 0))) { @@ -425,17 +511,13 @@ var Layout = cc.Class({ } this._doLayoutDirty(); - }, + } - onDisable: function () { + protected onDisable () { this._removeEventListeners(); - }, + } - _doLayoutDirty: function () { - this._layoutDirty = true; - }, - - _addEventListeners: function () { + 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); @@ -443,9 +525,9 @@ var Layout = cc.Class({ this.node.on(NodeEvent.CHILD_REMOVED, this._childRemoved, this); this.node.on(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._addChildrenEventListeners(); - }, + } - _removeEventListeners: function () { + 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); @@ -453,96 +535,98 @@ var Layout = cc.Class({ this.node.off(NodeEvent.CHILD_REMOVED, this._childRemoved, this); this.node.off(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._removeChildrenEventListeners(); - }, + } - _addChildrenEventListeners: function () { - var children = this.node.children; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + private _addChildrenEventListeners () { + const children = this.node.children; + for (const child of children) { + child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on('active-in-hierarchy-changed', this._doLayoutDirty, this); } - }, + } - _removeChildrenEventListeners: function () { - var children = this.node.children; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + private _removeChildrenEventListeners () { + const children = this.node.children; + for (const child of children) { + child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off('active-in-hierarchy-changed', this._doLayoutDirty, this); } - }, + } - _childAdded: function (child) { + private _childAdded (child) { + child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on('active-in-hierarchy-changed', this._doLayoutDirty, this); this._doLayoutDirty(); - }, + } - _childRemoved: function (child) { + private _childRemoved (child) { + child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off('active-in-hierarchy-changed', this._doLayoutDirty, this); this._doLayoutDirty(); - }, + } - _resized: function () { + private _resized () { this._layoutSize = this.node.getContentSize(); this._doLayoutDirty(); - }, + } - _doLayoutHorizontally: function (baseWidth, rowBreak, fnPositionY, applyChildren) { - var layoutAnchor = this.node.getAnchorPoint(); - var children = this.node.children; + private _doLayoutHorizontally (baseWidth, rowBreak, fnPositionY, applyChildren) { + const layoutAnchor = this.node.getAnchorPoint(); + const children = this.node.children; - var sign = 1; - var paddingX = this.paddingLeft; - var leftBoundaryOfLayout = -layoutAnchor.x * baseWidth; + let sign = 1; + let paddingX = this.paddingLeft; + let leftBoundaryOfLayout = -layoutAnchor.x * baseWidth; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * baseWidth; paddingX = this.paddingRight; } - var nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX; - var rowMaxHeight = 0; - var tempMaxHeight = 0; - var secondMaxHeight = 0; - var row = 0; - var containerResizeBoundary = 0; + let nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX; + let rowMaxHeight = 0; + let tempMaxHeight = 0; + let secondMaxHeight = 0; + let row = 0; + let containerResizeBoundary = 0; - var maxHeightChildAnchorY = 0; + let maxHeightChildAnchorY = 0; + + let activeChildCount = 0; + for (const child of children) { - var activeChildCount = 0; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; if (child.activeInHierarchy) { activeChildCount++; } } - var newChildWidth = this.cellSize.width; + 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; } - for (var i = 0; i < children.length; ++i) { - var child = children[i]; - let childScaleX = Math.abs(child.scaleX); - let childScaleY = Math.abs(child.scaleY); + for (const child of children) { + + const childScaleX = this._getUsedScaleValue(child.scaleX); + const childScaleY = this._getUsedScaleValue(child.scaleY); if (!child.activeInHierarchy) { continue; } - //for resizing children + // for resizing children if (this._resize === ResizeMode.CHILDREN) { child.width = newChildWidth / childScaleX; if (this.type === Type.GRID) { @@ -550,9 +634,9 @@ var Layout = cc.Class({ } } - var anchorX = child.anchorX; - var childBoundingBoxWidth = child.width * childScaleX; - var childBoundingBoxHeight = child.height * childScaleY; + let anchorX = child.anchorX; + const childBoundingBoxWidth = child.width * childScaleX; + const childBoundingBoxHeight = child.height * childScaleY; if (secondMaxHeight > tempMaxHeight) { tempMaxHeight = secondMaxHeight; @@ -568,12 +652,12 @@ var Layout = cc.Class({ anchorX = 1 - child.anchorX; } nextX = nextX + sign * anchorX * childBoundingBoxWidth + sign * this.spacingX; - var rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth; + const rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth; if (rowBreak) { - var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft); - var leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth; - var 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) { @@ -583,8 +667,7 @@ var Layout = cc.Class({ } rowMaxHeight += secondMaxHeight; secondMaxHeight = tempMaxHeight; - } - else { + } else { rowMaxHeight += tempMaxHeight; secondMaxHeight = childBoundingBoxHeight; tempMaxHeight = 0; @@ -594,16 +677,16 @@ var Layout = cc.Class({ } } - var finalPositionY = fnPositionY(child, rowMaxHeight, row); + const finalPositionY = fnPositionY(child, rowMaxHeight, row); if (baseWidth >= (childBoundingBoxWidth + this.paddingLeft + this.paddingRight)) { if (applyChildren) { child.setPosition(cc.v2(nextX, finalPositionY)); } } - var signX = 1; - var tempFinalPositionY; - var topMarign = (tempMaxHeight === 0) ? childBoundingBoxHeight : tempMaxHeight; + let signX = 1; + let tempFinalPositionY; + const topMarign = (tempMaxHeight === 0) ? childBoundingBoxHeight : tempMaxHeight; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { containerResizeBoundary = containerResizeBoundary || this.node._contentSize.height; @@ -612,8 +695,7 @@ var Layout = cc.Class({ if (tempFinalPositionY < containerResizeBoundary) { containerResizeBoundary = tempFinalPositionY; } - } - else { + } else { containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.height; tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingTop); if (tempFinalPositionY > containerResizeBoundary) { @@ -625,71 +707,68 @@ var Layout = cc.Class({ } return containerResizeBoundary; - }, + } - _getVerticalBaseHeight: function (children) { - var newHeight = 0; - var activeChildCount = 0; + private _getVerticalBaseHeight (children) { + let newHeight = 0; + let activeChildCount = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + for (const child of children) { if (child.activeInHierarchy) { activeChildCount++; - newHeight += child.height * Math.abs(child.scaleY); + newHeight += child.height * this._getUsedScaleValue(child.scaleY); } } newHeight += (activeChildCount - 1) * this.spacingY + this.paddingBottom + this.paddingTop; - } - else { + } else { newHeight = this.node.getContentSize().height; } return newHeight; - }, + } - _doLayoutVertically: function (baseHeight, columnBreak, fnPositionX, applyChildren) { - var layoutAnchor = this.node.getAnchorPoint(); - var children = this.node.children; + private _doLayoutVertically (baseHeight, columnBreak, fnPositionX, applyChildren) { + const layoutAnchor = this.node.getAnchorPoint(); + const children = this.node.children; - var sign = 1; - var paddingY = this.paddingBottom; - var bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight; + let sign = 1; + let paddingY = this.paddingBottom; + let bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * baseHeight; paddingY = this.paddingTop; } - var nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY; - var columnMaxWidth = 0; - var tempMaxWidth = 0; - var secondMaxWidth = 0; - var column = 0; - var containerResizeBoundary = 0; - var maxWidthChildAnchorX = 0; + let nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY; + let columnMaxWidth = 0; + let tempMaxWidth = 0; + let secondMaxWidth = 0; + let column = 0; + let containerResizeBoundary = 0; + let maxWidthChildAnchorX = 0; - var activeChildCount = 0; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + let activeChildCount = 0; + for (const child of children) { if (child.activeInHierarchy) { activeChildCount++; } } - var newChildHeight = this.cellSize.height; + 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; } - for (var i = 0; i < children.length; ++i) { - var child = children[i]; - let childScaleX = Math.abs(child.scaleX); - let childScaleY = Math.abs(child.scaleY); + for (const child of children) { + + const childScaleX = this._getUsedScaleValue(child.scaleX); + const childScaleY = this._getUsedScaleValue(child.scaleY); if (!child.activeInHierarchy) { continue; } - //for resizing children + // for resizing children if (this.resizeMode === ResizeMode.CHILDREN) { child.height = newChildHeight / childScaleY; if (this.type === Type.GRID) { @@ -697,9 +776,9 @@ var Layout = cc.Class({ } } - var anchorY = child.anchorY; - var childBoundingBoxWidth = child.width * childScaleX; - var childBoundingBoxHeight = child.height * childScaleY; + let anchorY = child.anchorY; + const childBoundingBoxWidth = child.width * childScaleX; + const childBoundingBoxHeight = child.height * childScaleY; if (secondMaxWidth > tempMaxWidth) { tempMaxWidth = secondMaxWidth; @@ -715,12 +794,12 @@ var Layout = cc.Class({ anchorY = 1 - child.anchorY; } nextY = nextY + sign * anchorY * childBoundingBoxHeight + sign * this.spacingY; - var topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight; + const topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight; if (columnBreak) { - var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom); - var bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight; - var 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) { @@ -729,8 +808,7 @@ var Layout = cc.Class({ } columnMaxWidth += secondMaxWidth; secondMaxWidth = tempMaxWidth; - } - else { + } else { columnMaxWidth += tempMaxWidth; secondMaxWidth = childBoundingBoxWidth; tempMaxWidth = 0; @@ -740,17 +818,17 @@ var Layout = cc.Class({ } } - var finalPositionX = fnPositionX(child, columnMaxWidth, column); + const finalPositionX = fnPositionX(child, columnMaxWidth, column); if (baseHeight >= (childBoundingBoxHeight + (this.paddingTop + this.paddingBottom))) { if (applyChildren) { child.setPosition(cc.v2(finalPositionX, nextY)); } } - var signX = 1; - var tempFinalPositionX; - //when the item is the last column break item, the tempMaxWidth will be 0. - var rightMarign = (tempMaxWidth === 0) ? childBoundingBoxWidth : tempMaxWidth; + let signX = 1; + let tempFinalPositionX; + // 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) { signX = -1; @@ -759,8 +837,7 @@ var Layout = cc.Class({ if (tempFinalPositionX < containerResizeBoundary) { containerResizeBoundary = tempFinalPositionX; } - } - else { + } else { containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.width; tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingRight); if (tempFinalPositionX > containerResizeBoundary) { @@ -773,66 +850,67 @@ var Layout = cc.Class({ } return containerResizeBoundary; - }, + } - _doLayoutBasic: function () { - var children = this.node.children; + private _doLayoutBasic () { + const children = this.node.children; - var allChildrenBoundingBox = null; + let allChildrenBoundingBox = null; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + for (const child of children) { if (child.activeInHierarchy) { if (!allChildrenBoundingBox) { allChildrenBoundingBox = child.getBoundingBoxToWorld(); } else { - allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld()); + // allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld()); } } } if (allChildrenBoundingBox) { - var leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); + let leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); leftBottomInParentSpace = cc.v2(leftBottomInParentSpace.x - this.paddingLeft, leftBottomInParentSpace.y - this.paddingBottom); - var rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, - allChildrenBoundingBox.y + allChildrenBoundingBox.height)); + let rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, + allChildrenBoundingBox.y + allChildrenBoundingBox.height)); rightTopInParentSpace = cc.v2(rightTopInParentSpace.x + this.paddingRight, rightTopInParentSpace.y + this.paddingTop); - var newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), - parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); + const newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), + parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); - var layoutPosition = this.node.getPosition(); - var newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width; - var newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height; - var newAnchor = cc.v2(parseFloat(newAnchorX.toFixed(2)), parseFloat(newAnchorY.toFixed(2))); - - this.node.setAnchorPoint(newAnchor); + const layoutPosition = this.node.getPosition(); + if (newSize.width !== 0) { + const newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width; + this.node.anchorX = parseFloat(newAnchorX.toFixed(2)); + } + if (newSize.height !== 0) { + const newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height; + this.node.anchorY = parseFloat(newAnchorY.toFixed(2)); + } this.node.setContentSize(newSize); } - }, + } - _doLayoutGridAxisHorizontal: function (layoutAnchor, layoutSize) { - var baseWidth = layoutSize.width; + private _doLayoutGridAxisHorizontal (layoutAnchor, layoutSize) { + const baseWidth = layoutSize.width; - var sign = 1; - var bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height; - var paddingY = this.paddingBottom; + let sign = 1; + let bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height; + let paddingY = this.paddingBottom; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height; paddingY = this.paddingTop; } - var fnPositionY = function (child, topOffset, row) { - return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * Math.abs(child.scaleY) + paddingY + row * this.spacingY); + const fnPositionY = function (child, topOffset, row) { + return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * this._getUsedScaleValue(child.scaleY) + paddingY + row * this.spacingY); }.bind(this); - - var newHeight = 0; + let newHeight = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - //calculate the new height of container, it won't change the position of it's children - var boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false); + // 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; if (newHeight < 0) { newHeight *= -1; @@ -851,27 +929,27 @@ var Layout = cc.Class({ if (this.resizeMode === ResizeMode.CONTAINER) { this.node.setContentSize(baseWidth, newHeight); } - }, + } - _doLayoutGridAxisVertical: function (layoutAnchor, layoutSize) { - var baseHeight = layoutSize.height; + private _doLayoutGridAxisVertical (layoutAnchor, layoutSize) { + const baseHeight = layoutSize.height; - var sign = 1; - var leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width; - var paddingX = this.paddingLeft; + let sign = 1; + let leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width; + let paddingX = this.paddingLeft; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width; paddingX = this.paddingRight; } - var fnPositionX = function (child, leftOffset, column) { - return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * Math.abs(child.scaleX) + paddingX + column * this.spacingX); + const fnPositionX = function (child, leftOffset, column) { + return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * this._getUsedScaleValue(child.scaleX) + paddingX + column * this.spacingX); }.bind(this); - var newWidth = 0; + let newWidth = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - var boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false); + const boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false); newWidth = leftBoundaryOfLayout - boundary; if (newWidth < 0) { newWidth *= -1; @@ -890,74 +968,72 @@ var Layout = cc.Class({ if (this.resizeMode === ResizeMode.CONTAINER) { this.node.setContentSize(newWidth, baseHeight); } - }, + } - _doLayoutGrid: function () { - var layoutAnchor = this.node.getAnchorPoint(); - var layoutSize = this.node.getContentSize(); + private _doLayoutGrid () { + const layoutAnchor = this.node.getAnchorPoint(); + const layoutSize = this.node.getContentSize(); if (this.startAxis === AxisDirection.HORIZONTAL) { this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize); - } - else if (this.startAxis === AxisDirection.VERTICAL) { + } else if (this.startAxis === AxisDirection.VERTICAL) { this._doLayoutGridAxisVertical(layoutAnchor, layoutSize); } - }, + } - _getHorizontalBaseWidth: function (children) { - var newWidth = 0; - var activeChildCount = 0; + private _getHorizontalBaseWidth (children) { + let newWidth = 0; + let activeChildCount = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + for (const child of children) { if (child.activeInHierarchy) { activeChildCount++; - newWidth += child.width * Math.abs(child.scaleX); + newWidth += child.width * this._getUsedScaleValue(child.scaleX); } } newWidth += (activeChildCount - 1) * this.spacingX + this.paddingLeft + this.paddingRight; - } - else { + } else { newWidth = this.node.getContentSize().width; } return newWidth; - }, + } - _doLayout: function () { + private _doLayout () { if (this.type === Type.HORIZONTAL) { - var newWidth = this._getHorizontalBaseWidth(this.node.children); + const newWidth = this._getHorizontalBaseWidth(this.node.children); - var fnPositionY = function (child) { + const fnPositionY = (child) => { return child.y; }; this._doLayoutHorizontally(newWidth, false, fnPositionY, true); this.node.width = newWidth; - } - else if (this.type === Type.VERTICAL) { - var newHeight = this._getVerticalBaseHeight(this.node.children); + } else if (this.type === Type.VERTICAL) { + const newHeight = this._getVerticalBaseHeight(this.node.children); - var fnPositionX = function (child) { + const fnPositionX = (child) => { return child.x; }; this._doLayoutVertically(newHeight, false, fnPositionX, true); this.node.height = newHeight; - } - else if (this.type === Type.NONE) { + } else if (this.type === Type.NONE) { if (this.resizeMode === ResizeMode.CONTAINER) { this._doLayoutBasic(); } - } - else if (this.type === Type.GRID) { + } else if (this.type === Type.GRID) { this._doLayoutGrid(); } - }, + } + + private _getUsedScaleValue (value) { + return this.affectedByScale ? Math.abs(value) : 1; + } /** * !#en Perform the layout update @@ -972,31 +1048,19 @@ var Layout = cc.Class({ * layout.updateLayout(); * cc.log(childNode.x); // changed */ - updateLayout: function () { + public updateLayout () { if (this._layoutDirty && this.node.children.length > 0) { this._doLayout(); this._layoutDirty = false; } } -}); - -/** - * !#en The padding of layout, it effects the layout in four direction. - * !#zh 容器内边距,该属性会在四个布局方向上生效。 - * @property {Number} padding - */ -Object.defineProperty(Layout.prototype, "padding", { - get: function () { - cc.warnID(4100); - return this.paddingLeft; - }, - set: function (value) { - this._N$padding = value; - - this._migratePaddingData(); - this._doLayoutDirty(); + private _doLayoutDirty () { + this._layoutDirty = true; } -}); -cc.Layout = module.exports = Layout; + 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 new file mode 100644 index 0000000000..dd8eee5516 --- /dev/null +++ b/cocos/3d/ui/components/mask-component.ts @@ -0,0 +1,328 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 {SpriteFrame} from '../../../assets/CCSpriteFrame'; +import { ccclass, executeInEditMode, executionOrder, + menu, property, requireComponent } from '../../../core/data/class-decorator'; +import { ccenum } from '../../../core/value-types/enum'; +import { clamp } from '../../../core/vmath'; +import { Material } from '../../assets/material'; +import circle from '../../primitive/circle'; +import { IGeometry } from '../../primitive/define'; +import quad from '../../primitive/quad'; +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'; + +/** + * !#en the type for mask. + * !#zh 遮罩组件类型 + */ +export enum MaskType { + /** + * !#en Rect mask. + * !#zh 使用矩形作为遮罩 + */ + RECT = 0, + + /** + * !#en Ellipse Mask. + * !#zh 使用椭圆作为遮罩 + */ + ELLIPSE = 1, + + /** + * !#en Image Stencil Mask. + * !#zh 使用图像模版作为遮罩 + */ + IMAGE_STENCIL = 2, +} + +ccenum(MaskType); + +const SEGEMENTS_MIN = 3; +const SEGEMENTS_MAX = 10000; + +/** + * !#en The Mask Component. + * !#zh 遮罩组件。 + */ +@ccclass('cc.Mask') +@executionOrder(100) +@menu('UI/Mask') +@requireComponent(UITransformComponent) +@executeInEditMode +export class MaskComponent extends UIRenderComponent { + public static Type = MaskType; + + /** + * !#en The mask type. + * !#zh 遮罩类型。 + */ + public get type () { + return this._type; + } + + public set type (value) { + this._type = value; + if (this._type !== MaskType.IMAGE_STENCIL) { + this.spriteFrame = null; + this.alphaThreshold = 0; + this._updateGraphics(); + } + if (this._renderData) { + this.destroyRenderData(); + this._renderData = null; + } + this._activateMaterial(); + } + + /** + * !#en The mask image + * !#zh 遮罩所需要的贴图 + */ + public get spriteFrame () { + return this._spriteFrame; + } + + public set spriteFrame (value) { + if (this._spriteFrame === value) { + return; + } + this._applySpriteFrame(value); + } + + /** + * !#en + * The alpha threshold.(Not supported in Canvas Mode)
+ * The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
+ * Should be a float between 0 and 1.
+ * This default to 0 (so alpha test is disabled). + * When it's set to 1, the stencil will discard all pixels, nothing will be shown, + * In previous version, it act as if the alpha test is disabled, which is incorrect. + * !#zh + * Alpha 阈值(不支持 Canvas 模式)
+ * 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。
+ * 该数值 0 ~ 1 之间的浮点数,默认值为 0(因此禁用 alpha 测试) + * 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容,在之前的版本中,设置为 1 等同于 0,这种效果其实是不正确的 + */ + // @range: [0, 1, 0.1], + // slide: true, + @property({type: cc.Float}) + public get alphaThreshold () { + return this._alphaThreshold; + } + + public set alphaThreshold (value) { + this._alphaThreshold = value; + } + + /** + * !#en Reverse mask(Not supported in Canvas Mode). + * !#zh 反向遮罩(不支持 Canvas 模式)。 + */ + @property({type: Boolean}) + public get inverted () { + return this._inverted; + } + + public set inverted (value) { + this._inverted = value; + if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { + cc.warnID(4202); + return; + } + } + + /** + * TODO: remove segments, not supported by graphics + * !#en The segements for ellipse mask. + * !#zh 椭圆遮罩的曲线细分数 + */ + public get segments () { + return this._segments; + } + + public set segments (value) { + this._segments = clamp(value, SEGEMENTS_MIN, SEGEMENTS_MAX); + } + + @property + private _spriteFrame: SpriteFrame | null = null; + + @property + private _type = MaskType.RECT; + + @property + private _alphaThreshold: number = 0; + + @property + private _inverted: boolean = false; + + @property + private _segments: number = 64; + + private _maskMaterial: Material | null = null; + + private _clearMaskMaterial: Material | null = null; + + private _maskGeometry: IGeometry | null = null; + + private _clearGeometry: IGeometry | null = null; + + public onLoad () { + this._activateMaterial(); + } + + public onEnable () { + super.onEnable(); + this._activateMaterial(); + } + + 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._renderFlag &= ~RenderFlow.FLAG_POST_RENDER; + } + + public onDestroy () { + super.onDestroy(); + } + + // _resizeNodeToTargetNode: CC_EDITOR && function () { + // if (this.spriteFrame) { + // const rect = this.spriteFrame.getRect(); + // this.node.setContentSize(rect.width, rect.height); + // } + // } + + public _onTextureLoaded () { + // Mark render data dirty + if (this._renderData) { + this._renderData.uvDirty = true; + this._renderData.vertDirty = true; + } + // Reactivate material + if (this.enabledInHierarchy) { + this._activateMaterial(); + } + } + + public _applySpriteFrame (oldFrame) { + if (oldFrame && oldFrame.off) { + oldFrame.off('load', this._onTextureLoaded, this); + } + const spriteFrame = this._spriteFrame; + if (spriteFrame) { + if (spriteFrame.textureLoaded()) { + this._onTextureLoaded(); + } else { + spriteFrame.once('load', this._onTextureLoaded, this); + spriteFrame.ensureLoadTexture(); + } + } + } + + public _activateMaterial () { + if (!this._maskMaterial) { + this._maskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this); + setupMaskMaterial(this._maskMaterial); + } + + if (!this._clearMaskMaterial) { + this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this); + setupClearMaskMaterial(this._clearMaskMaterial); + } + } + + public _getMaskGeometry () { + return this._maskGeometry; + } + + public _getClearGeometry () { + return this._clearGeometry; + } + + public _getMaskMaterial (): Material | null { + return this._maskMaterial; + } + + public _getClearMaterial (): Material | null { + return this._clearMaskMaterial; + } + + private _updateGraphics () { + this._maskGeometry = this._getGraphics(); + this._clearGeometry = this._drawRect( + 0, 0, cc.visibleRect.width, cc.visibleRect.height); + } + + private _getGraphics () { + const uiTransform = this.node.getComponent(UITransformComponent); + if (!uiTransform) { + return null; + } + const width = uiTransform.width; + const height = uiTransform.height; + const x = -width * uiTransform.anchorPoint.x; + const y = -height * uiTransform.anchorPoint.y; + switch (this._type) { + case MaskType.RECT: + case MaskType.IMAGE_STENCIL: + return this._drawRect(x, y, width, height); + case MaskType.ELLIPSE: + const cx = x + width / 2; + const cy = y + height / 2; + const rx = width / 2; + const ry = height / 2; + return this._drawEllipse(cx, cy, rx, ry); + } + return null; + } + + private _drawRect (x: number, y: number, width: number, height: number) { + 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) { + const geometry = circle({ includeNormal: false, includeUV: false }); + scale(geometry, { x: rx, y: ry }); + translate(geometry, { x: cx, y: cy }); + return geometry; + } +} + +// tslint:disable-next-line +cc['MaskComponent'] = MaskComponent; diff --git a/cocos/3d/ui/components/progress-bar-component.ts b/cocos/3d/ui/components/progress-bar-component.ts new file mode 100644 index 0000000000..019653a675 --- /dev/null +++ b/cocos/3d/ui/components/progress-bar-component.ts @@ -0,0 +1,316 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { Component} from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { clamp01 } from '../../../core/utils/misc'; +import { Enum } from '../../../core/value-types'; +import { SpriteComponent } from './sprite-component'; + +/** + * !#en Enum for ProgressBar mode + * !#zh 进度条模式 + * @enum ProgressBar.Mode + */ +enum Mode { + /** + * !#en TODO + * !#zh 水平方向模式 + * @property {Number} HORIZONTAL + */ + HORIZONTAL = 0, + + /** + * !#en TODO + * !#zh 垂直方向模式 + * @property {Number} VERTICAL + */ + VERTICAL = 1, + /** + * !#en TODO + * !#zh 填充模式 + * @property {Number} FILLED + */ + FILLED = 2, +} + +Enum(Mode); + +/** + * !#en + * Visual indicator of progress in some operation. + * Displays a bar to the user representing how far the operation has progressed. + * !#zh + * 进度条组件,可用于显示加载资源时的进度。 + * @class ProgressBar + * @extends Component + * @example + * // update progressBar + * update(dt) { + * var progress = progressBar.progress; + * if (progress > 0) { + * progress += dt; + * } + * else { + * progress = 1; + * } + * progressBar.progress = progress; + * } + * + */ +@ccclass('cc.ProgressBarComponent') +@executionOrder(100) +@menu('UI/ProgressBar') +// @executeInEditMode +export class ProgressBarComponent extends Component { + + /** + * !#en The targeted Sprite which will be changed progressively. + * !#zh 用来显示进度条比例的 Sprite 对象。 + * @property {Sprite} barSprite + */ + @property({ + type: SpriteComponent, + }) + get barSprite () { + return this._barSprite; + } + + set barSprite (value: SpriteComponent) { + if (this._barSprite === value) { + return; + } + + this._barSprite = value; + this._initBarSprite(); + } + + /** + * !#en The progress mode, there are two modes supported now: horizontal and vertical. + * !#zh 进度条的模式 + * @property {ProgressBar.Mode} mode + */ + @property({ + type: Mode, + }) + get mode () { + return this._mode; + } + + set mode (value: Mode) { + if (this._mode === value) { + return; + } + + this._mode = value; + if (this._barSprite) { + const entity = this._barSprite.node; + if (!entity) { return; } + + const entitySize = entity.getContentSize(); + if (this._mode === Mode.HORIZONTAL) { + this.totalLength = entitySize.width; + } else if (this._mode === Mode.VERTICAL) { + this.totalLength = entitySize.height; + } else if (this._mode === Mode.FILLED) { + this.totalLength = this._barSprite.fillRange; + } + } + } + + /** + * !#en The total width or height of the bar sprite. + * !#zh 进度条实际的总长度 + * @property {Number} totalLength - range[[0, Number.MAX_VALUE]] + */ + @property + get totalLength () { + return this._N$totalLength; + } + + set totalLength (value: number) { + if (this._mode === Mode.FILLED) { + value = clamp01(value); + } + this._N$totalLength = value; + this._updateBarStatus(); + } + + /** + * !#en The current progress of the bar sprite. The valid value is between 0-1. + * !#zh 当前进度值,该数值的区间是 0-1 之间。 + * @property {Number} progress + */ + @property({ + range: [0, 1, 0.1], + slide: true, + }) + get progress () { + return this._progress; + } + + set progress (value: number) { + if (this._progress === value) { + return; + } + + this._progress = value; + this._updateBarStatus(); + } + + /** + * !#en Whether reverse the progress direction of the bar sprite. + * !#zh 进度条是否进行反方向变化。 + * @property {Boolean} reverse + */ + @property + get reverse () { + return this._reverse; + } + + set reverse (value: boolean) { + if (this._reverse === value) { + return; + } + + this._reverse = value; + if (this._barSprite) { + this._barSprite.fillStart = 1 - this._barSprite.fillStart; + } + this._updateBarStatus(); + } + + public static Mode = Mode; + @property + private _barSprite: SpriteComponent | null = null; + @property + private _mode: number = Mode.HORIZONTAL; + private _N$totalLength: number = 1; + @property + private _progress: number = 0.1; + @property + private _reverse: boolean = false; + + public _initBarSprite () { + if (this._barSprite) { + const entity = this._barSprite.node; + if (!entity) { return; } + + const nodeSize = this.node.getContentSize(); + const nodeAnchor = this.node.getAnchorPoint(); + + const entitySize = entity.getContentSize(); + + if (entity.parent === this.node) { + this.node.setContentSize(entitySize); + } + + if (this._barSprite.fillType === cc.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) { + this.totalLength = barSpriteSize.height; + } else { + this.totalLength = this._barSprite.fillRange; + } + + if (entity.parent === this.node) { + const x = - nodeSize.width * nodeAnchor.x; + const y = 0; + entity.setPosition(cc.v2(x, y)); + } + } + } + + public _updateBarStatus () { + if (this._barSprite) { + const entity = this._barSprite.node; + + if (!entity) { return; } + + const entityAnchorPoint = entity.getAnchorPoint(); + const entitySize = entity.getContentSize(); + const entityPosition = entity.getPosition(); + + let anchorPoint = cc.v2(0, 0.5); + const progress = clamp01(this._progress); + let actualLenth = this.totalLength * progress; + let finalContentSize; + let totalWidth; + let totalHeight; + switch (this._mode) { + case Mode.HORIZONTAL: + if (this._reverse) { + anchorPoint = cc.v2(1, 0.5); + } + finalContentSize = cc.size(actualLenth, entitySize.height); + totalWidth = this.totalLength; + totalHeight = entitySize.height; + break; + case Mode.VERTICAL: + if (this._reverse) { + anchorPoint = cc.v2(0.5, 1); + } else { + anchorPoint = cc.v2(0.5, 0); + } + finalContentSize = cc.size(entitySize.width, actualLenth); + totalWidth = entitySize.width; + totalHeight = this.totalLength; + break; + } + + // handling filled mode + if (this._mode === Mode.FILLED) { + if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) { + cc.warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!'); + } else { + if (this._reverse) { + actualLenth = actualLenth * -1; + } + this._barSprite.fillRange = actualLenth; + } + } else { + if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) { + + const anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; + const anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; + const finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); + + entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entity.getPosition().z); + + entity.setAnchorPoint(anchorPoint); + entity.setContentSize(finalContentSize); + } else { + cc.warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!'); + } + } + } + } +} diff --git a/cocos/3d/ui/components/scroll-bar-component.ts b/cocos/3d/ui/components/scroll-bar-component.ts new file mode 100644 index 0000000000..2910c625de --- /dev/null +++ b/cocos/3d/ui/components/scroll-bar-component.ts @@ -0,0 +1,408 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { 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 { Node } from '../../../scene-graph/node'; + +var GETTINGSHORTERFACTOR = 20; + +/** + * Enum for Scrollbar direction + * @enum Scrollbar.Direction + */ +var Direction = cc.Enum({ + /** + * @property {Number} HORIZONTAL + */ + HORIZONTAL: 0, + + /** + * @property {Number} VERTICAL + */ + VERTICAL: 1 +}); + +/** + * !#en + * The Scrollbar control allows the user to scroll an image or other view that is too large to see completely + * !#zh 滚动条组件 + * @class Scrollbar + * @extends Component + */ +@ccclass('cc.ScrollBarComponent') +@executionOrder(100) +@executeInEditMode +export class ScrollBarComponent extends Component { + @property + private _scrollView: Component | null = null; + @property + private _handle: UIRenderComponent | null = null; + @property + private _direction = Direction.HORIZONTAL; + @property + private _enableAutoHide = false; + @property + private _autoHideTime = 1.0; + + private _touching = false; + private _opacity = 0; + private _autoHideRemainingTime = 0; + + /** + * !#en The "handle" part of the scrollbar. + * !#zh 作为当前滚动区域位置显示的滑块 Sprite。 + * @property {Sprite} handle + */ + @property({ + type: UIRenderComponent + }) + get handle() { + return this._handle; + } + + set handle(value: UIRenderComponent) { + if (this._handle === value) { + return + } + this._handle = value; + this.onScroll(cc.v2(0, 0)); + } + + /** + * !#en The direction of scrollbar. + * !#zh ScrollBar 的滚动方向。 + * @property {Scrollbar.Direction} direction + */ + @property({ + type: Direction + }) + get direction() { + return this._direction; + } + + set direction(value) { + if (this._direction === value) { + return; + } + + this._direction = value; + this.onScroll(cc.v2(0, 0)); + } + + /** + * !#en Whether enable auto hide or not. + * !#zh 是否在没有滚动动作时自动隐藏 ScrollBar。 + * @property {Boolean} enableAutoHide + */ + get enableAutoHide() { + return this._enableAutoHide; + } + + set enableAutoHide(value) { + if (this._enableAutoHide === value) { + return; + } + + this._enableAutoHide = value; + if(this._enableAutoHide){ + this._setOpacity(0); + } + } + + /** + * !#en + * The time to hide scrollbar when scroll finished. + * Note: This value is only useful when enableAutoHide is true. + * !#zh + * 没有滚动动作后经过多久会自动隐藏。 + * 注意:只要当 “enableAutoHide” 为 true 时,才有效。 + * @property {Number} autoHideTime + */ + @property + get autoHideTime() { + return this._autoHideTime; + } + + set autoHideTime(value) { + if (this._autoHideTime === value) { + return; + } + + this._autoHideTime = value; + } + + static Direction = Direction; + + protected onEnable() { + let renderComp = this.node.getComponent(UIRenderComponent); + if (renderComp) { + this._opacity = renderComp.color.a; + } + } + + protected start() { + if (this._enableAutoHide) { + this._setOpacity(0); + } + } + + public hide() { + this._autoHideRemainingTime = 0; + this._setOpacity(0); + } + + public show() { + this._autoHideRemainingTime = this._autoHideTime; + this._setOpacity(this._opacity); + } + + protected update(dt) { + this._processAutoHide(dt); + } + + private _convertToScrollViewSpace(content: Node) { + return new Vec2(0, 0); + if (!this._scrollView){ + return; + } + + // TODO: + // var worldSpacePos = content.convertToWorldSpace(new Vec2(0, 0)); + // var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos); + // return scrollViewSpacePos; + } + + private _setOpacity(opacity: number) { + if (this._handle) { + let renderComp = this.node.getComponent(UIRenderComponent); + if (renderComp){ + renderComp.color.a = opacity; + } + + renderComp = this._handle.getComponent(UIRenderComponent); + if (renderComp) { + renderComp.color.a = opacity; + } + } + } + + 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); + } + } + } + + // FIXME: use ScrollViewComponent + public setScrollView(scrollView: Component) { + this._scrollView = scrollView; + } + + private _updateHanlderPosition(position) { + if (this._handle) { + var oldPosition = this._fixupHandlerPosition(); + + this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y); + } + } + + private _fixupHandlerPosition() { + if(!this._handle){ + return; + } + + var barSize = this.node.getContentSize(); + var barAnchor = this.node.getAnchorPoint(); + var handleSize = this._handle.node.getContentSize(); + + 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); + + if (this._direction === Direction.HORIZONTAL) { + fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2); + } else if (this._direction === Direction.VERTICAL) { + fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y); + } + + this._handle.node.setPosition(fixupPosition); + + return fixupPosition; + } + + public onTouchBegan() { + if (!this._enableAutoHide) { + return; + } + this._touching = true; + } + + private _conditionalDisableScrollBar(contentSize, scrollViewSize) { + if (contentSize.width <= scrollViewSize.width + && this._direction === Direction.HORIZONTAL) { + return true; + } + + if (contentSize.height <= scrollViewSize.height + && this._direction === Direction.VERTICAL) { + return true; + } + return false; + } + + public onTouchEnded() { + if (!this._enableAutoHide) { + return; + } + + this._touching = false; + + if (this._autoHideTime <= 0) { + return; + } + + + if (this._scrollView) { + var content = this._scrollView.content; + if (content) { + var contentSize = content.getContentSize(); + var scrollViewSize = this._scrollView.node.getContentSize(); + + if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) { + return; + } + } + } + + this._autoHideRemainingTime = this._autoHideTime; + } + + private _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) { + var denominatorValue = contentMeasure; + if (outOfBoundary) { + denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR; + } + + var lengthRation = scrollViewMeasure / denominatorValue; + return handleNodeMeasure * lengthRation; + } + + private _calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) { + var denominatorValue = contentMeasure - scrollViewMeasure; + if (outOfBoundary) { + denominatorValue += Math.abs(outOfBoundary); + } + + var positionRatio = 0; + if (denominatorValue) { + positionRatio = contentPosition / denominatorValue; + positionRatio = clamp01(positionRatio); + } + + var position = (handleNodeMeasure - actualLenth) * positionRatio; + if (this._direction === Direction.VERTICAL) { + return cc.v2(0, position); + } else { + return cc.v2(position, 0); + } + } + + private _updateLength(length) { + if (this._handle) { + var handleNode = this._handle.node; + var handleNodeSize = handleNode.getContentSize(); + handleNode.setAnchorPoint(cc.v2(0, 0)); + if (this._direction === Direction.HORIZONTAL) { + handleNode.setContentSize(length, handleNodeSize.height); + } else { + handleNode.setContentSize(handleNodeSize.width, length); + } + } + } + + private _processAutoHide(deltaTime) { + if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) { + return; + } else if (this._touching) { + return; + } + + + this._autoHideRemainingTime -= deltaTime; + if (this._autoHideRemainingTime <= this._autoHideTime) { + this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); + // var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime); + // this._setOpacity(opacity); + } + } +} diff --git a/cocos/2d/ui/CCScrollView.js b/cocos/3d/ui/components/scroll-view-component.ts similarity index 70% rename from cocos/2d/ui/CCScrollView.js rename to cocos/3d/ui/components/scroll-view-component.ts index 8c32b746b0..8c96d96499 100644 --- a/cocos/2d/ui/CCScrollView.js +++ b/cocos/3d/ui/components/scroll-view-component.ts @@ -23,20 +23,28 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +import { Node } from '../../../scene-graph/node'; +import { Enum, Vec2, Vec3, Size } from '../../../core/value-types'; +import { ViewGroupComponent } from './view-group-component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ScrollBarComponent } from './scroll-bar-component'; +import ComponentEventHandler from '../../../components/CCComponentEventHandler'; +import { LayoutComponent } from './layout-component'; -const NodeEvent = require('../CCNode').EventType; +const NodeEvent = Node.EventType; const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05; const EPSILON = 1e-4; const MOVEMENT_FACTOR = 0.7; +const _vec3Zero = new Vec3(); -let quintEaseOut = function(time) { +let quintEaseOut = function (time) { time -= 1; return (time * time * time * time * time + 1); }; -let getTimeInMilliseconds = function() { +let getTimeInMilliseconds = function () { let currentTime = new Date(); return currentTime.getMilliseconds(); }; @@ -46,100 +54,102 @@ let getTimeInMilliseconds = function() { * !#zh 滚动视图事件类型 * @enum ScrollView.EventType */ -const EventType = cc.Enum({ +enum EventType { /** * !#en The event emmitted when ScrollView scroll to the top boundary of inner container * !#zh 滚动视图滚动到顶部边界事件 * @property {Number} SCROLL_TO_TOP */ - SCROLL_TO_TOP : 0, + SCROLL_TO_TOP = 0, /** * !#en The event emmitted when ScrollView scroll to the bottom boundary of inner container * !#zh 滚动视图滚动到底部边界事件 * @property {Number} SCROLL_TO_BOTTOM */ - SCROLL_TO_BOTTOM : 1, + SCROLL_TO_BOTTOM = 1, /** * !#en The event emmitted when ScrollView scroll to the left boundary of inner container * !#zh 滚动视图滚动到左边界事件 * @property {Number} SCROLL_TO_LEFT */ - SCROLL_TO_LEFT : 2, + SCROLL_TO_LEFT = 2, /** * !#en The event emmitted when ScrollView scroll to the right boundary of inner container * !#zh 滚动视图滚动到右边界事件 * @property {Number} SCROLL_TO_RIGHT */ - SCROLL_TO_RIGHT : 3, + SCROLL_TO_RIGHT = 3, /** * !#en The event emmitted when ScrollView is scrolling * !#zh 滚动视图正在滚动时发出的事件 * @property {Number} SCROLLING */ - SCROLLING : 4, + SCROLLING = 4, /** * !#en The event emmitted when ScrollView scroll to the top boundary of inner container and start bounce * !#zh 滚动视图滚动到顶部边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_TOP */ - BOUNCE_TOP : 5, + BOUNCE_TOP = 5, /** * !#en The event emmitted when ScrollView scroll to the bottom boundary of inner container and start bounce * !#zh 滚动视图滚动到底部边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_BOTTOM */ - BOUNCE_BOTTOM : 6, + BOUNCE_BOTTOM = 6, /** * !#en The event emmitted when ScrollView scroll to the left boundary of inner container and start bounce * !#zh 滚动视图滚动到左边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_LEFT */ - BOUNCE_LEFT : 7, + BOUNCE_LEFT = 7, /** * !#en The event emmitted when ScrollView scroll to the right boundary of inner container and start bounce * !#zh 滚动视图滚动到右边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_RIGHT */ - BOUNCE_RIGHT : 8, + BOUNCE_RIGHT = 8, /** * !#en The event emmitted when ScrollView auto scroll ended * !#zh 滚动视图滚动结束的时候发出的事件 * @property {Number} SCROLL_ENDED */ - SCROLL_ENDED : 9, + SCROLL_ENDED = 9, /** * !#en The event emmitted when user release the touch * !#zh 当用户松手的时候会发出一个事件 * @property {Number} TOUCH_UP */ - TOUCH_UP : 10, + TOUCH_UP = 10, /** * !#en The event emmitted when ScrollView auto scroll ended with a threshold * !#zh 滚动视图自动滚动快要结束的时候发出的事件 * @property {Number} AUTOSCROLL_ENDED_WITH_THRESHOLD */ - AUTOSCROLL_ENDED_WITH_THRESHOLD: 11, + AUTOSCROLL_ENDED_WITH_THRESHOLD = 11, /** * !#en The event emmitted when ScrollView scroll began * !#zh 滚动视图滚动开始时发出的事件 * @property {Number} SCROLL_BEGAN */ - SCROLL_BEGAN: 12 -}); + SCROLL_BEGAN = 12 +} + +Enum(EventType); const eventMap = { - 'scroll-to-top' : EventType.SCROLL_TO_TOP, + 'scroll-to-top': EventType.SCROLL_TO_TOP, 'scroll-to-bottom': EventType.SCROLL_TO_BOTTOM, - 'scroll-to-left' : EventType.SCROLL_TO_LEFT, - 'scroll-to-right' : EventType.SCROLL_TO_RIGHT, - 'scrolling' : EventType.SCROLLING, - 'bounce-bottom' : EventType.BOUNCE_BOTTOM, - 'bounce-left' : EventType.BOUNCE_LEFT, - 'bounce-right' : EventType.BOUNCE_RIGHT, - 'bounce-top' : EventType.BOUNCE_TOP, + 'scroll-to-left': EventType.SCROLL_TO_LEFT, + 'scroll-to-right': EventType.SCROLL_TO_RIGHT, + 'scrolling': EventType.SCROLLING, + 'bounce-bottom': EventType.BOUNCE_BOTTOM, + 'bounce-left': EventType.BOUNCE_LEFT, + 'bounce-right': EventType.BOUNCE_RIGHT, + 'bounce-top': EventType.BOUNCE_TOP, 'scroll-ended': EventType.SCROLL_ENDED, - 'touch-up' : EventType.TOUCH_UP, - 'scroll-ended-with-threshold' : EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD, + 'touch-up': EventType.TOUCH_UP, + 'scroll-ended-with-threshold': EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD, 'scroll-began': EventType.SCROLL_BEGAN }; @@ -153,197 +163,190 @@ const eventMap = { * @class ScrollView * @extends Component */ -let ScrollView = cc.Class({ - name: 'cc.ScrollView', - extends: require('./CCViewGroup'), - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/ScrollView', - help: 'i18n:COMPONENT.help_url.scrollview', - executeInEditMode: false, - }, +@ccclass('cc.ScrollViewComponent') +@executionOrder(100) +@menu('UI/ScrollView') +@executeInEditMode +export class ScrollViewComponent extends ViewGroupComponent { + /** + * !#en Enable horizontal scroll. + * !#zh 是否开启水平滚动。 + * @property {Boolean} horizontal + */ + @property + public horizontal = true; - ctor () { - this._topBoundary = 0; - this._bottomBoundary = 0; - this._leftBoundary = 0; - this._rightBoundary = 0; + /** + * !#en Enable vertical scroll. + * !#zh 是否开启垂直滚动。 + * @property {Boolean} vertical + */ + @property + public vertical = true; - this._touchMoveDisplacements = []; - this._touchMoveTimeDeltas = []; - this._touchMovePreviousTimestamp = 0; - this._touchMoved = false; + /** + * !#en When inertia is set, the content will continue to move when touch ended. + * !#zh 是否开启滚动惯性。 + * @property {Boolean} inertia + */ + @property + public inertia = true; - this._autoScrolling = false; - this._autoScrollAttenuate = false; - this._autoScrollStartPosition = cc.v2(0, 0); - this._autoScrollTargetDelta = cc.v2(0, 0); - this._autoScrollTotalTime = 0; - this._autoScrollAccumulatedTime = 0; - this._autoScrollCurrentlyOutOfBoundary = false; - this._autoScrollBraking = false; - this._autoScrollBrakingStartPosition = cc.v2(0, 0); + /** + * !#en + * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. + * A value of 0 will never stop the movement until it reaches to the boundary of scrollview. + * !#zh + * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 + * @property {Number} brake + */ + @property({ + range: [0, 1, 0.1] + }) + public brake = 0.5; - this._outOfBoundaryAmount = cc.v2(0, 0); - this._outOfBoundaryAmountDirty = true; - this._stopMouseWheel = false; - this._mouseWheelEventElapsedTime = 0.0; - this._isScrollEndedWithThresholdEventFired = false; - //use bit wise operations to indicate the direction - this._scrollEventEmitMask = 0; - this._isBouncing = false; - this._scrolling = false; - }, + /** + * !#en When elastic is set, the content will be bounce back when move out of boundary. + * !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。 + */ + @property + public elastic = true; - properties: { - /** - * !#en This is a reference to the UI element to be scrolled. - * !#zh 可滚动展示内容的节点。 - * @property {Node} content - */ - content: { - default: undefined, - type: cc.Node, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.content', - formerlySerializedAs: 'content', - notify (oldValue) { - this._calculateBoundary(); - } - }, + /** + * !#en The elapse time of bouncing back. A value of 0 will bounce back immediately. + * !#zh 回弹持续的时间,0 表示将立即反弹。 + * @property {Number} bounceDuration + */ + @property({ + range: [1, 10] + }) + public bounceDuration = 1; - /** - * !#en Enable horizontal scroll. - * !#zh 是否开启水平滚动。 - * @property {Boolean} horizontal - */ - horizontal: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.horizontal', - }, + /** + * !#en Scrollview events callback + * !#zh 滚动视图的事件回调函数 + * @property {Component.EventHandler[]} scrollEvents + */ + @property + public scrollEvents: ComponentEventHandler[] = []; - /** - * !#en Enable vertical scroll. - * !#zh 是否开启垂直滚动。 - * @property {Boolean} vertical - */ - vertical: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.vertical', - }, + /** + * !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes + * It's set to true by default. + * !#zh 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。 + * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 + * @property {Boolean} cancelInnerEvents + */ + @property + public cancelInnerEvents = true; + @property + private _content: Node | null = null; + @property + private _horizontalScrollBar: ScrollBarComponent | null = null; + @property + private _verticalScrollBar: ScrollBarComponent | null = null; - /** - * !#en When inertia is set, the content will continue to move when touch ended. - * !#zh 是否开启滚动惯性。 - * @property {Boolean} inertia - */ - inertia: { - default: true, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.inertia', - }, + private _topBoundary = 0; + private _bottomBoundary = 0; + private _leftBoundary = 0; + private _rightBoundary = 0; - /** - * !#en - * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. - * A value of 0 will never stop the movement until it reaches to the boundary of scrollview. - * !#zh - * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 - * @property {Number} brake - */ - brake: { - default: 0.5, - type: 'Float', - range: [0, 1, 0.1], - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.brake', - }, + private _touchMoveDisplacements: Vec3[] = []; + private _touchMoveTimeDeltas: number[] = []; + private _touchMovePreviousTimestamp = 0; + private _touchMoved = false; - /** - * !#en When elastic is set, the content will be bounce back when move out of boundary. - * !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。 - * @property {Boolean} elastic - */ - elastic: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.elastic', - }, + private _autoScrolling = false; + private _autoScrollAttenuate = false; + private _autoScrollStartPosition = new Vec3(0, 0); + private _autoScrollTargetDelta = new Vec3(0, 0); + private _autoScrollTotalTime = 0; + private _autoScrollAccumulatedTime = 0; + private _autoScrollCurrentlyOutOfBoundary = false; + private _autoScrollBraking = false; + private _autoScrollBrakingStartPosition = new Vec3(0, 0); - /** - * !#en The elapse time of bouncing back. A value of 0 will bounce back immediately. - * !#zh 回弹持续的时间,0 表示将立即反弹。 - * @property {Number} bounceDuration - */ - bounceDuration: { - default: 1, - range: [0, 10], - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.bounceDuration', - }, + private _outOfBoundaryAmount = new Vec3(0, 0); + private _outOfBoundaryAmountDirty = true; + private _stopMouseWheel = false; + private _mouseWheelEventElapsedTime = 0.0; + private _isScrollEndedWithThresholdEventFired = false; + //use bit wise operations to indicate the direction + private _scrollEventEmitMask = 0; + private _isBouncing = false; + private _scrolling = false; + private _contentPos = new Vec3(); - /** - * !#en The horizontal scrollbar reference. - * !#zh 水平滚动的 ScrollBar。 - * @property {Scrollbar} horizontalScrollBar - */ - horizontalScrollBar: { - default: undefined, - type: cc.Scrollbar, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.horizontal_bar', - notify () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.setTargetScrollView(this); - this._updateScrollBar(0); - } - }, - animatable: false - }, - - /** - * !#en The vertical scrollbar reference. - * !#zh 垂直滚动的 ScrollBar。 - * @property {Scrollbar} verticalScrollBar - */ - verticalScrollBar: { - default: undefined, - type: cc.Scrollbar, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.vertical_bar', - notify () { - if (this.verticalScrollBar) { - this.verticalScrollBar.setTargetScrollView(this); - this._updateScrollBar(0); - } - }, - animatable: false - }, - - /** - * !#en Scrollview events callback - * !#zh 滚动视图的事件回调函数 - * @property {Component.EventHandler[]} scrollEvents - */ - scrollEvents: { - default: [], - type: cc.Component.EventHandler, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.scrollEvents' - }, - - /** - * !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes - * It's set to true by default. - * !#zh 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。 - * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 - * @property {Boolean} cancelInnerEvents - */ - cancelInnerEvents: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.cancelInnerEvents' + /** + * !#en This is a reference to the UI element to be scrolled. + * !#zh 可滚动展示内容的节点。 + * @property {Node} content + */ + @property({ + type: Node + }) + get content() { + return this._content; + } + set content(value: Node) { + if(this._content === value){ + return; } - }, - statics: { - EventType: EventType, - }, + this._content = value; + this._calculateBoundary(); + } + + /** + * !#en The horizontal scrollbar reference. + * !#zh 水平滚动的 ScrollBar。 + * @property {Scrollbar} horizontalScrollBar + */ + @property({ + type: ScrollBarComponent + }) + get horizontalScrollBar() { + return this._horizontalScrollBar; + } + + set horizontalScrollBar(value: ScrollBarComponent) { + if(this._horizontalScrollBar === value){ + return; + } + + this._horizontalScrollBar = value; + + if (this._horizontalScrollBar) { + this._horizontalScrollBar.setScrollView(this); + this._updateScrollBar(0); + } + } + + /** + * !#en The vertical scrollbar reference. + * !#zh 垂直滚动的 ScrollBar。 + * @property {Scrollbar} verticalScrollBar + */ + @property + get verticalScrollBar() { + return this._verticalScrollBar; + } + + set verticalScrollBar(value: ScrollBarComponent) { + if (this._verticalScrollBar === value) { + return; + } + + this._verticalScrollBar = value; + + if (this._verticalScrollBar) { + this._verticalScrollBar.setScrollView(this); + this._updateScrollBar(0); + } + } + + static EventType = EventType; /** * !#en Scroll the content to the bottom boundary of ScrollView. @@ -356,9 +359,9 @@ let ScrollView = cc.Class({ * // Scroll to the bottom of the view. * scrollView.scrollToBottom(0.1); */ - scrollToBottom (timeInSecond, attenuated) { + scrollToBottom(timeInSecond: number, attenuated: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 0), + anchor: new Vec2(0, 0), applyToHorizontal: false, applyToVertical: true, }); @@ -368,7 +371,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta, true); } - }, + } /** * !#en Scroll the content to the top boundary of ScrollView. @@ -381,9 +384,9 @@ let ScrollView = cc.Class({ * // Scroll to the top of the view. * scrollView.scrollToTop(0.1); */ - scrollToTop (timeInSecond, attenuated) { + scrollToTop(timeInSecond: number, attenuated: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 1), + anchor: new Vec2(0, 1), applyToHorizontal: false, applyToVertical: true, }); @@ -393,7 +396,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the left boundary of ScrollView. @@ -406,9 +409,9 @@ let ScrollView = cc.Class({ * // Scroll to the left of the view. * scrollView.scrollToLeft(0.1); */ - scrollToLeft (timeInSecond, attenuated) { + scrollToLeft(timeInSecond: number, attenuated: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 0), + anchor: new Vec2(0, 0), applyToHorizontal: true, applyToVertical: false, }); @@ -418,7 +421,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the right boundary of ScrollView. @@ -431,9 +434,9 @@ let ScrollView = cc.Class({ * // Scroll to the right of the view. * scrollView.scrollToRight(0.1); */ - scrollToRight (timeInSecond, attenuated) { + scrollToRight(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(1, 0), + anchor: new Vec2(1, 0), applyToHorizontal: true, applyToVertical: false, }); @@ -443,7 +446,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the top left boundary of ScrollView. @@ -456,9 +459,9 @@ let ScrollView = cc.Class({ * // Scroll to the upper left corner of the view. * scrollView.scrollToTopLeft(0.1); */ - scrollToTopLeft (timeInSecond, attenuated) { + scrollToTopLeft(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 1), + anchor: new Vec2(0, 1), applyToHorizontal: true, applyToVertical: true, }); @@ -468,7 +471,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the top right boundary of ScrollView. @@ -481,9 +484,9 @@ let ScrollView = cc.Class({ * // Scroll to the top right corner of the view. * scrollView.scrollToTopRight(0.1); */ - scrollToTopRight (timeInSecond, attenuated) { + scrollToTopRight(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(1, 1), + anchor: new Vec2(1, 1), applyToHorizontal: true, applyToVertical: true, }); @@ -493,7 +496,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the bottom left boundary of ScrollView. @@ -506,9 +509,9 @@ let ScrollView = cc.Class({ * // Scroll to the lower left corner of the view. * scrollView.scrollToBottomLeft(0.1); */ - scrollToBottomLeft (timeInSecond, attenuated) { + scrollToBottomLeft(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 0), + anchor: new Vec2(0, 0), applyToHorizontal: true, applyToVertical: true, }); @@ -518,7 +521,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the bottom right boundary of ScrollView. @@ -531,9 +534,9 @@ let ScrollView = cc.Class({ * // Scroll to the lower right corner of the view. * scrollView.scrollToBottomRight(0.1); */ - scrollToBottomRight (timeInSecond, attenuated) { + scrollToBottomRight(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(1, 0), + anchor: new Vec2(1, 0), applyToHorizontal: true, applyToVertical: true, }); @@ -543,7 +546,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** @@ -558,12 +561,12 @@ let ScrollView = cc.Class({ * @example * // Scroll to middle position in 0.1 second in x-axis * let maxScrollOffset = this.getMaxScrollOffset(); - * scrollView.scrollToOffset(cc.v2(maxScrollOffset.x / 2, 0), 0.1); + * scrollView.scrollToOffset(new Vec3(maxScrollOffset.x / 2, 0, 0), 0.1); */ - scrollToOffset (offset, timeInSecond, attenuated) { + scrollToOffset(offset, timeInSecond, attenuated) { let maxScrollOffset = this.getMaxScrollOffset(); - let anchor = cc.v2(0, 0); + let anchor = new Vec2(0, 0); //if maxScrollOffset is 0, then always align the content's top left origin to the top left corner of its parent if (maxScrollOffset.x === 0) { anchor.x = 0; @@ -574,11 +577,11 @@ let ScrollView = cc.Class({ if (maxScrollOffset.y === 0) { anchor.y = 1; } else { - anchor.y = (maxScrollOffset.y - offset.y ) / maxScrollOffset.y; + anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y; } this.scrollTo(anchor, timeInSecond, attenuated); - }, + } /** * !#en Get the positive offset value corresponds to the content's top left boundary. @@ -586,12 +589,12 @@ let ScrollView = cc.Class({ * @method getScrollOffset * @return {Vec2} - A Vec2 value indicate the current scroll offset. */ - getScrollOffset () { - let topDelta = this._getContentTopBoundary() - this._topBoundary; + getScrollOffset() { + let topDelta = this._getContentTopBoundary() - this._topBoundary; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; - return cc.v2(leftDeta, topDelta); - }, + return new Vec2(leftDeta, topDelta); + } /** * !#en Get the maximize available scroll offset @@ -599,16 +602,16 @@ let ScrollView = cc.Class({ * @method getMaxScrollOffset * @return {Vec2} - A Vec2 value indicate the maximize scroll offset in x and y axis. */ - getMaxScrollOffset () { + getMaxScrollOffset() { let scrollSize = this.node.getContentSize(); - let contentSize = this.content.getContentSize(); - let horizontalMaximizeOffset = contentSize.width - scrollSize.width; + let contentSize = this._content!.getContentSize(); + let horizontalMaximizeOffset = contentSize.width - scrollSize.width; let verticalMaximizeOffset = contentSize.height - scrollSize.height; horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0; - verticalMaximizeOffset = verticalMaximizeOffset >=0 ? verticalMaximizeOffset : 0; + verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0; - return cc.v2(horizontalMaximizeOffset, verticalMaximizeOffset); - }, + return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset); + } /** * !#en Scroll the content to the horizontal percent position of ScrollView. @@ -622,9 +625,9 @@ let ScrollView = cc.Class({ * // Scroll to middle position. * scrollView.scrollToBottomRight(0.5, 0.1); */ - scrollToPercentHorizontal (percent, timeInSecond, attenuated) { + scrollToPercentHorizontal(percent, timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(percent, 0), + anchor: new Vec2(percent, 0), applyToHorizontal: true, applyToVertical: false, }); @@ -634,36 +637,36 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the percent position of ScrollView in any direction. * !#zh 视图内容在规定时间内进行垂直方向和水平方向的滚动,并且滚动到指定百分比位置上。 * @method scrollTo - * @param {Vec2} anchor - A point which will be clamp between cc.v2(0,0) and cc.v2(1,1). + * @param {Vec2} anchor - A point which will be clamp between new Vec2(0,0) and new Vec2(1,1). * @param {Number} [timeInSecond=0] - Scroll time in second, if you don't pass timeInSecond, * the content will jump to the percent position of ScrollView immediately. * @param {Boolean} [attenuated=true] - Whether the scroll acceleration attenuated, default is true. * @example * // Vertical scroll to the bottom of the view. - * scrollView.scrollTo(cc.v2(0, 1), 0.1); + * scrollView.scrollTo(new Vec2(0, 1), 0.1); * * // Horizontal scroll to view right. - * scrollView.scrollTo(cc.v2(1, 0), 0.1); + * scrollView.scrollTo(new Vec2(1, 0), 0.1); */ - scrollTo (anchor, timeInSecond, attenuated) { + scrollTo(anchor: Vec2, timeInSecond: number, attenuated?: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(anchor), + anchor: new Vec2(anchor), applyToHorizontal: true, applyToVertical: true, }); if (timeInSecond) { - this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false); + this._startAutoScroll(moveDelta, timeInSecond, attenuated); } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the vertical percent position of ScrollView. @@ -676,29 +679,29 @@ let ScrollView = cc.Class({ * // Scroll to middle position. * scrollView.scrollToPercentVertical(0.5, 0.1); */ - scrollToPercentVertical (percent, timeInSecond, attenuated) { + scrollToPercentVertical(percent: number, timeInSecond: number, attenuated?: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, percent), + anchor: new Vec2(0, percent), applyToHorizontal: false, applyToVertical: true, }); if (timeInSecond) { - this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false); + this._startAutoScroll(moveDelta, timeInSecond, attenuated); } else { this._moveContent(moveDelta); } - }, + } /** * !#en Stop auto scroll immediately * !#zh 停止自动滚动, 调用此 API 可以让 Scrollview 立即停止滚动 * @method stopAutoScroll */ - stopAutoScroll () { + stopAutoScroll() { this._autoScrolling = false; this._autoScrollAccumulatedTime = this._autoScrollTotalTime; - }, + } /** * !#en Modify the content position. @@ -706,14 +709,14 @@ let ScrollView = cc.Class({ * @method setContentPosition * @param {Vec2} position - The position in content's parent space. */ - setContentPosition (position) { + setContentPosition(position: Vec3) { if (position.fuzzyEquals(this.getContentPosition(), EPSILON)) { return; } - this.content.setPosition(position); + this._content!.setPosition(position); this._outOfBoundaryAmountDirty = true; - }, + } /** * !#en Query the content's position in its parent space. @@ -721,19 +724,20 @@ let ScrollView = cc.Class({ * @method getContentPosition * @returns {Position} - The content's position in its parent space. */ - getContentPosition () { - return this.content.getPosition(); - }, - + getContentPosition() { + this._content!.getPosition(this._contentPos); + return this._contentPos; + } + /** * !#en Query whether the user is currently dragging the ScrollView to scroll it * !#zh 用户是否在拖拽当前滚动视图 * @method isScrolling * @returns {Boolean} - Whether the user is currently dragging the ScrollView to scroll it */ - isScrolling () { + isScrolling() { return this._scrolling; - }, + } /** * !#en Query whether the ScrollView is currently scrolling because of a bounceback or inertia slowdown. @@ -741,60 +745,60 @@ let ScrollView = cc.Class({ * @method isAutoScrolling * @returns {Boolean} - Whether the ScrollView is currently scrolling because of a bounceback or inertia slowdown. */ - isAutoScrolling () { + isAutoScrolling() { return this._autoScrolling; - }, - + } + //private methods - _registerEvent () { + _registerEvent() { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.on(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); - }, + } - _unregisterEvent () { + _unregisterEvent() { this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.off(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); - }, + } - _onMouseWheel (event, captureListeners) { + _onMouseWheel(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this._hasNestedViewGroup(event, captureListeners)) return; - let deltaMove = cc.v2(0, 0); + let deltaMove = new Vec3(); let wheelPrecision = -0.1; - if(CC_JSB) { + if (CC_JSB) { wheelPrecision = -7; } - if(this.vertical) { - deltaMove = cc.v2(0, event.getScrollY() * wheelPrecision); + if (this.vertical) { + deltaMove = new Vec3(0, event.getScrollY() * wheelPrecision); } - else if(this.horizontal) { - deltaMove = cc.v2(event.getScrollY() * wheelPrecision, 0); + else if (this.horizontal) { + deltaMove = new Vec3(event.getScrollY() * wheelPrecision, 0); } this._mouseWheelEventElapsedTime = 0; this._processDeltaMove(deltaMove); - if(!this._stopMouseWheel) { + if (!this._stopMouseWheel) { this._handlePressLogic(); this.schedule(this._checkMouseWheel, 1.0 / 60); this._stopMouseWheel = true; } this._stopPropagationIfTargetIsMe(event); - }, + } - _checkMouseWheel (dt) { + _checkMouseWheel(dt: number) { let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); let maxElapsedTime = 0.1; - if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { this._processInertiaScroll(); this.unschedule(this._checkMouseWheel); this._stopMouseWheel = false; @@ -809,25 +813,25 @@ let ScrollView = cc.Class({ this.unschedule(this._checkMouseWheel); this._stopMouseWheel = false; } - }, + } - _calculateMovePercentDelta (options) { + _calculateMovePercentDelta(options) { let anchor = options.anchor; let applyToHorizontal = options.applyToHorizontal; let applyToVertical = options.applyToVertical; this._calculateBoundary(); - anchor = anchor.clampf(cc.v2(0, 0), cc.v2(1, 1)); + anchor = anchor.clampf(new Vec2(0, 0), new Vec2(1, 1)); let scrollSize = this.node.getContentSize(); - let contentSize = this.content.getContentSize(); + let contentSize = this._content!.getContentSize(); let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; leftDeta = -leftDeta; - let moveDelta = cc.v2(0, 0); + let moveDelta = new Vec3(0, 0); let totalScrollDelta = 0; if (applyToHorizontal) { totalScrollDelta = contentSize.width - scrollSize.width; @@ -840,14 +844,14 @@ let ScrollView = cc.Class({ } return moveDelta; - }, + } - _moveContentToTopLeft (scrollViewSize) { - let contentSize = this.content.getContentSize(); + _moveContentToTopLeft(scrollViewSize: Size) { + let contentSize = this._content!.getContentSize(); let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; - let moveDelta = cc.v2(0, 0); + let moveDelta = new Vec3(0, 0); let totalScrollDelta = 0; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; @@ -870,54 +874,57 @@ let ScrollView = cc.Class({ totalScrollDelta = contentSize.width - scrollViewSize.width; moveDelta.x = leftDeta; - if (this.horizontalScrollBar) { - this.horizontalScrollBar.hide(); + if (this._horizontalScrollBar) { + this._horizontalScrollBar.hide(); } } else { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.show(); + if (this._horizontalScrollBar) { + this._horizontalScrollBar.show(); } } this._moveContent(moveDelta); this._adjustContentOutOfBoundary(); - }, + } - _calculateBoundary () { - if (this.content) { - //refresh content size - let layout = this.content.getComponent(cc.Layout); - if(layout && layout.enabledInHierarchy) { - layout.updateLayout(); - } - let viewSize = this.content.parent.getContentSize(); - - let leftBottomPosition = this._convertToContentParentSpace(cc.v2(0, 0)); - this._leftBoundary = leftBottomPosition.x; - this._bottomBoundary = leftBottomPosition.y; - - let topRightPosition = this._convertToContentParentSpace(cc.v2(viewSize.width, viewSize.height)); - this._rightBoundary = topRightPosition.x; - this._topBoundary = topRightPosition.y; - - this._moveContentToTopLeft(viewSize); + _calculateBoundary() { + if (this._content) { + return; } - }, + //refresh content size + let layout = this._content!.getComponent(LayoutComponent); + if (layout && layout.enabledInHierarchy) { + layout!.updateLayout(); + } + let viewSize = this._content!.parent!.getContentSize(); - _convertToContentParentSpace (position) { - let contentParent = this.content.parent; + let leftBottomPosition = this._convertToContentParentSpace(new Vec3(0, 0)); + this._leftBoundary = leftBottomPosition.x; + this._bottomBoundary = leftBottomPosition.y; + + let topRightPosition = this._convertToContentParentSpace(new Vec3(viewSize.width, viewSize.height)); + this._rightBoundary = topRightPosition.x; + this._topBoundary = topRightPosition.y; + + this._moveContentToTopLeft(viewSize); + + } + + _convertToContentParentSpace(position: Vec3) { + let contentParent = this._content!.parent; + // TODO: let viewPositionInWorldSpace = contentParent.convertToWorldSpace(position); return contentParent.convertToNodeSpaceAR(viewPositionInWorldSpace); - }, + } //this is for nested scrollview - _hasNestedViewGroup (event, captureListeners) { + _hasNestedViewGroup(event, captureListeners) { if (event.eventPhase !== cc.Event.CAPTURING_PHASE) return; if (captureListeners) { //captureListeners are arranged from child to parent - for (let i = 0; i < captureListeners.length; ++i){ + for (let i = 0; i < captureListeners.length; ++i) { let item = captureListeners[i]; if (this.node === item) { @@ -927,40 +934,40 @@ let ScrollView = cc.Class({ return false; } - if(item.getComponent(cc.ViewGroup)) { + if (item.getComponent(cc.ViewGroup)) { return true; } } } return false; - }, + } //This is for Scrollview as children of a Button - _stopPropagationIfTargetIsMe (event) { + _stopPropagationIfTargetIsMe(event) { if (event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) { event.stopPropagation(); } - }, + } // touch event handler - _onTouchBegan (event, captureListeners) { - if (!this.enabledInHierarchy) return; + _onTouchBegan(event, captureListeners) { + if (!this.enabledInHierarchy||!this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; let touch = event.touch; - if (this.content) { - this._handlePressLogic(touch); + if (this._content) { + this._handlePressLogic(); } this._touchMoved = false; this._stopPropagationIfTargetIsMe(event); - }, + } - _onTouchMoved (event, captureListeners) { - if (!this.enabledInHierarchy) return; + _onTouchMoved(event, captureListeners) { + if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; let touch = event.touch; - if (this.content) { + if (this._content) { this._handleMoveLogic(touch); } // Do not prevent touch events in inner nodes @@ -982,16 +989,16 @@ let ScrollView = cc.Class({ } } this._stopPropagationIfTargetIsMe(event); - }, + } - _onTouchEnded (event, captureListeners) { - if (!this.enabledInHierarchy) return; + _onTouchEnded(event, captureListeners) { + if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; this._dispatchEvent('touch-up'); let touch = event.touch; - if (this.content) { + if (this._content) { this._handleReleaseLogic(touch); } if (this._touchMoved) { @@ -999,33 +1006,33 @@ let ScrollView = cc.Class({ } else { this._stopPropagationIfTargetIsMe(event); } - }, - - _onTouchCancelled (event, captureListeners) { - if (!this.enabledInHierarchy) return; + } + + _onTouchCancelled(event, captureListeners) { + if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; // Filte touch cancel event send from self if (!event.simulate) { let touch = event.touch; - if(this.content){ + if (this._content) { this._handleReleaseLogic(touch); } } this._stopPropagationIfTargetIsMe(event); - }, + } - _processDeltaMove (deltaMove) { + _processDeltaMove(deltaMove: Vec3) { this._scrollChildren(deltaMove); this._gatherTouchMove(deltaMove); - }, + } - _handleMoveLogic (touch) { + _handleMoveLogic(touch) { let deltaMove = touch.getDelta(); this._processDeltaMove(deltaMove); - }, + } - _scrollChildren (deltaMove) { + _scrollChildren(deltaMove: Vec3) { deltaMove = this._clampDelta(deltaMove); let realMove = deltaMove; @@ -1041,30 +1048,32 @@ let ScrollView = cc.Class({ realMove = realMove.add(outOfBoundary); } - let scrollEventType = -1; + let scrollEventType = ''; + let pos = new Vec3(); + this._content!.getPosition(pos); if (realMove.y > 0) { //up - let icBottomPos = this.content.y - this.content.anchorY * this.content.height; + let icBottomPos = pos.y - this._content!.anchorY * this._content!.height; if (icBottomPos + realMove.y > this._bottomBoundary) { scrollEventType = 'scroll-to-bottom'; } } else if (realMove.y < 0) { //down - let icTopPos = this.content.y - this.content.anchorY * this.content.height + this.content.height; + let icTopPos = pos.y - this._content!.anchorY * this._content!.height + this._content!.height; if (icTopPos + realMove.y <= this._topBoundary) { scrollEventType = 'scroll-to-top'; } } else if (realMove.x < 0) { //left - let icRightPos = this.content.x - this.content.anchorX * this.content.width + this.content.width; + let icRightPos = pos.x - this._content!.anchorX * this._content!.width + this._content!.width; if (icRightPos + realMove.x <= this._rightBoundary) { scrollEventType = 'scroll-to-right'; } } else if (realMove.x > 0) { //right - let icLeftPos = this.content.x - this.content.anchorX * this.content.width; + let icLeftPos = pos.x - this._content!.anchorX * this._content!.width; if (icLeftPos + realMove.x >= this._leftBoundary) { scrollEventType = 'scroll-to-left'; } @@ -1080,13 +1089,13 @@ let ScrollView = cc.Class({ this._dispatchEvent('scrolling'); } - if (scrollEventType !== -1) { + if (scrollEventType.length > 0) { this._dispatchEvent(scrollEventType); } - }, + } - _handlePressLogic () { + _handlePressLogic() { if (this._autoScrolling) { this._dispatchEvent('scroll-ended'); } @@ -1098,10 +1107,10 @@ let ScrollView = cc.Class({ this._touchMoveTimeDeltas.length = 0; this._onScrollBarTouchBegan(); - }, + } - _clampDelta (delta) { - let contentSize = this.content.getContentSize(); + _clampDelta(delta: Vec3) { + let contentSize = this._content!.getContentSize(); let scrollViewSize = this.node.getContentSize(); if (contentSize.width < scrollViewSize.width) { delta.x = 0; @@ -1111,9 +1120,9 @@ let ScrollView = cc.Class({ } return delta; - }, + } - _gatherTouchMove (delta) { + _gatherTouchMove(delta: Vec3) { delta = this._clampDelta(delta); while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) { @@ -1126,9 +1135,9 @@ let ScrollView = cc.Class({ let timeStamp = getTimeInMilliseconds(); this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000); this._touchMovePreviousTimestamp = timeStamp; - }, + } - _startBounceBackIfNeeded () { + _startBounceBackIfNeeded() { if (!this.elastic) { return false; } @@ -1136,7 +1145,7 @@ let ScrollView = cc.Class({ let bounceBackAmount = this._getHowMuchOutOfBoundary(); bounceBackAmount = this._clampDelta(bounceBackAmount); - if (bounceBackAmount.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (bounceBackAmount.fuzzyEquals(_vec3Zero, EPSILON)) { return false; } @@ -1152,21 +1161,21 @@ let ScrollView = cc.Class({ } return true; - }, + } - _processInertiaScroll () { + _processInertiaScroll() { let bounceBackStarted = this._startBounceBackIfNeeded(); if (!bounceBackStarted && this.inertia) { let touchMoveVelocity = this._calculateTouchMoveVelocity(); - if (!touchMoveVelocity.fuzzyEquals(cc.v2(0, 0), EPSILON) && this.brake < 1) { + if (!touchMoveVelocity.fuzzyEquals(_vec3Zero, EPSILON) && this.brake < 1) { this._startInertiaScroll(touchMoveVelocity); } } this._onScrollBarTouchEnded(); - }, + } - _handleReleaseLogic (touch) { + _handleReleaseLogic(touch) { let delta = touch.getDelta(); this._gatherTouchMove(delta); this._processInertiaScroll(); @@ -1177,14 +1186,14 @@ let ScrollView = cc.Class({ this._dispatchEvent('scroll-ended'); } } - }, + } - _isOutOfBoundary () { + _isOutOfBoundary() { let outOfBoundary = this._getHowMuchOutOfBoundary(); - return !outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON); - }, + return !outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON); + } - _isNecessaryAutoScrollBrake () { + _isNecessaryAutoScrollBrake() { if (this._autoScrollBraking) { return true; } @@ -1202,13 +1211,13 @@ let ScrollView = cc.Class({ } return false; - }, + } - getScrollEndedEventTiming () { + getScrollEndedEventTiming() { return EPSILON; - }, + } - _processAutoScrolling (dt) { + _processAutoScrolling(dt) { let isAutoScrollBrake = this._isNecessaryAutoScrollBrake(); let brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1; this._autoScrollAccumulatedTime += dt * (1 / brakingFactor); @@ -1236,7 +1245,7 @@ let ScrollView = cc.Class({ } else { let moveDelta = newPosition.sub(this.getContentPosition()); let outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta); - if (!outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (!outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { newPosition = newPosition.add(outOfBoundary); reachedEnd = true; } @@ -1254,28 +1263,28 @@ let ScrollView = cc.Class({ this._isBouncing = false; this._dispatchEvent('scroll-ended'); } - }, + } - _startInertiaScroll (touchMoveVelocity) { + _startInertiaScroll(touchMoveVelocity: Vec3) { let inertiaTotalMovement = touchMoveVelocity.mul(MOVEMENT_FACTOR); this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); - }, + } - _calculateAttenuatedFactor (distance) { - if (this.brake <= 0){ + _calculateAttenuatedFactor(distance: number) { + if (this.brake <= 0) { return (1 - this.brake); } //attenuate formula from: http://learnopengl.com/#!Lighting/Light-casters return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008)); - }, + } - _startAttenuatingAutoScroll (deltaMove, initialVelocity) { + _startAttenuatingAutoScroll(deltaMove: Vec3, initialVelocity: Vec3) { let time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag()); let targetDelta = deltaMove.normalize(); - let contentSize = this.content.getContentSize(); + let contentSize = this._content!.getContentSize(); let scrollviewSize = this.node.getContentSize(); let totalMoveWidth = (contentSize.width - scrollviewSize.width); @@ -1284,7 +1293,7 @@ let ScrollView = cc.Class({ let attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth); let attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight); - targetDelta = cc.v2(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake)); + targetDelta = new Vec3(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake)); let originalMoveLength = deltaMove.mag(); let factor = targetDelta.mag() / originalMoveLength; @@ -1305,13 +1314,13 @@ let ScrollView = cc.Class({ } this._startAutoScroll(targetDelta, time, true); - }, + } - _calculateAutoScrollTimeByInitalSpeed (initalSpeed) { + _calculateAutoScrollTimeByInitalSpeed(initalSpeed) { return Math.sqrt(Math.sqrt(initalSpeed / 5)); - }, + } - _startAutoScroll (deltaMove, timeInSecond, attenuated) { + _startAutoScroll(deltaMove, timeInSecond, attenuated) { let adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); this._autoScrolling = true; @@ -1322,41 +1331,41 @@ let ScrollView = cc.Class({ this._autoScrollAccumulatedTime = 0; this._autoScrollBraking = false; this._isScrollEndedWithThresholdEventFired = false; - this._autoScrollBrakingStartPosition = cc.v2(0, 0); + this._autoScrollBrakingStartPosition = new Vec3(0, 0); let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); - if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { this._autoScrollCurrentlyOutOfBoundary = true; } - }, + } - _calculateTouchMoveVelocity () { + _calculateTouchMoveVelocity() { let totalTime = 0; - totalTime = this._touchMoveTimeDeltas.reduce(function(a, b) { + totalTime = this._touchMoveTimeDeltas.reduce(function (a, b) { return a + b; }, totalTime); if (totalTime <= 0 || totalTime >= 0.5) { - return cc.v2(0, 0); + return new Vec3(0, 0); } - let totalMovement = cc.v2(0, 0); - totalMovement = this._touchMoveDisplacements.reduce(function(a, b) { + let totalMovement = new Vec3(0, 0); + totalMovement = this._touchMoveDisplacements.reduce(function (a, b) { return a.add(b); }, totalMovement); - return cc.v2(totalMovement.x * (1 - this.brake) / totalTime, - totalMovement.y * (1 - this.brake) / totalTime); - }, + return new Vec3(totalMovement.x * (1 - this.brake) / totalTime, + totalMovement.y * (1 - this.brake) / totalTime); + } - _flattenVectorByDirection (vector) { + _flattenVectorByDirection(vector: Vec3) { let result = vector; result.x = this.horizontal ? result.x : 0; result.y = this.vertical ? result.y : 0; return result; - }, + } - _moveContent (deltaMove, canStartBounceBack) { + _moveContent(deltaMove: Vec3, canStartBounceBack?: boolean) { let adjustedMove = this._flattenVectorByDirection(deltaMove); let newPosition = this.getContentPosition().add(adjustedMove); @@ -1368,35 +1377,35 @@ let ScrollView = cc.Class({ if (this.elastic && canStartBounceBack) { this._startBounceBackIfNeeded(); } - }, + } - _getContentLeftBoundary () { + _getContentLeftBoundary() { let contentPos = this.getContentPosition(); - return contentPos.x - this.content.getAnchorPoint().x * this.content.getContentSize().width; - }, + return contentPos.x - this._content!.getAnchorPoint().x * this._content!.getContentSize().width; + } - _getContentRightBoundary () { - let contentSize = this.content.getContentSize(); + _getContentRightBoundary() { + let contentSize = this._content!.getContentSize(); return this._getContentLeftBoundary() + contentSize.width; - }, + } - _getContentTopBoundary () { - let contentSize = this.content.getContentSize(); + _getContentTopBoundary() { + let contentSize = this._content!.getContentSize(); return this._getContentBottomBoundary() + contentSize.height; - }, + } - _getContentBottomBoundary () { + _getContentBottomBoundary() { let contentPos = this.getContentPosition(); - return contentPos.y - this.content.getAnchorPoint().y * this.content.getContentSize().height; - }, + return contentPos.y - this._content!.getAnchorPoint().y * this._content!.getContentSize().height; + } - _getHowMuchOutOfBoundary (addition) { - addition = addition || cc.v2(0, 0); - if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON) && !this._outOfBoundaryAmountDirty) { + _getHowMuchOutOfBoundary(addition?: Vec3) { + addition = addition || new Vec3(0, 0); + if (addition.fuzzyEquals(_vec3Zero, EPSILON) && !this._outOfBoundaryAmountDirty) { return this._outOfBoundaryAmount; } - let outOfBoundaryAmount = cc.v2(0, 0); + let outOfBoundaryAmount = new Vec3(0, 0); if (this._getContentLeftBoundary() + addition.x > this._leftBoundary) { outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x); } else if (this._getContentRightBoundary() + addition.x < this._rightBoundary) { @@ -1409,7 +1418,7 @@ let ScrollView = cc.Class({ outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y); } - if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (addition.fuzzyEquals(_vec3Zero, EPSILON)) { this._outOfBoundaryAmount = outOfBoundaryAmount; this._outOfBoundaryAmountDirty = false; } @@ -1417,46 +1426,46 @@ let ScrollView = cc.Class({ outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount); return outOfBoundaryAmount; - }, + } - _updateScrollBar (outOfBoundary) { - if (this.horizontalScrollBar) { - this.horizontalScrollBar._onScroll(outOfBoundary); + _updateScrollBar(outOfBoundary) { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onScroll(outOfBoundary); } if (this.verticalScrollBar) { - this.verticalScrollBar._onScroll(outOfBoundary); + this.verticalScrollBar.onScroll(outOfBoundary); } - }, + } - _onScrollBarTouchBegan () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar._onTouchBegan(); + _onScrollBarTouchBegan() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onTouchBegan(); } if (this.verticalScrollBar) { - this.verticalScrollBar._onTouchBegan(); + this.verticalScrollBar.onTouchBegan(); } - }, + } - _onScrollBarTouchEnded () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar._onTouchEnded(); + _onScrollBarTouchEnded() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onTouchEnded(); } if (this.verticalScrollBar) { - this.verticalScrollBar._onTouchEnded(); + this.verticalScrollBar.onTouchEnded(); } - }, + } - _dispatchEvent (event) { + _dispatchEvent(event) { if (event === 'scroll-ended') { this._scrollEventEmitMask = 0; } else if (event === 'scroll-to-top' - || event === 'scroll-to-bottom' - || event === 'scroll-to-left' - || event === 'scroll-to-right') { + || event === 'scroll-to-bottom' + || event === 'scroll-to-left' + || event === 'scroll-to-right') { let flag = (1 << eventMap[event]); if (this._scrollEventEmitMask & flag) { @@ -1468,94 +1477,96 @@ let ScrollView = cc.Class({ cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]); this.node.emit(event, this); - }, + } + + _adjustContentOutOfBoundary() { + if(!this._content){ + return; + } - _adjustContentOutOfBoundary () { this._outOfBoundaryAmountDirty = true; if (this._isOutOfBoundary()) { - let outOfBoundary = this._getHowMuchOutOfBoundary(cc.v2(0, 0)); + let outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3(0, 0)); let newPosition = this.getContentPosition().add(outOfBoundary); - if (this.content) { - this.content.setPosition(newPosition); + if (this._content) { + this._content.setPosition(newPosition); this._updateScrollBar(0); } } - }, + } - start () { + start() { this._calculateBoundary(); //Because widget component will adjust content position and scrollview position is correct after visit //So this event could make sure the content is on the correct position after loading. - if (this.content) { + if (this._content) { cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); } - }, + } - _hideScrollbar () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.hide(); + _hideScrollbar() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.hide(); } if (this.verticalScrollBar) { this.verticalScrollBar.hide(); } - }, + } - _showScrollbar () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.show(); + _showScrollbar() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.show(); } if (this.verticalScrollBar) { this.verticalScrollBar.show(); } - }, + } - onDisable () { + onDisable() { if (!CC_EDITOR) { this._unregisterEvent(); this.node.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); this.node.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content) { - this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content.parent) { - this.content.parent.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); - this.content.parent.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - this.content.parent.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + if (this._content) { + this._content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this._content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + if (this._content.parent) { + this._content.parent.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); + this._content.parent.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + this._content.parent.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } } this._hideScrollbar(); this.stopAutoScroll(); - }, + } - onEnable () { + onEnable() { if (!CC_EDITOR) { this._registerEvent(); this.node.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); this.node.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content) { - this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content.parent) { - this.content.parent.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); - this.content.parent.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - this.content.parent.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + if (this._content) { + this._content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this._content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + if (this._content.parent) { + this._content.parent.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); + this._content.parent.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + this._content.parent.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } } this._showScrollbar(); - }, + } - update (dt) { + update(dt) { if (this._autoScrolling) { this._processAutoScrolling(dt); } } -}); - -cc.ScrollView = module.exports = ScrollView; +} /** * !#en @@ -1667,12 +1678,12 @@ cc.ScrollView = module.exports = ScrollView; * @param {ScrollView} scrollView - The ScrollView component. */ - /** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event scroll-began - * @param {Event.EventCustom} event - * @param {ScrollView} scrollView - The ScrollView component. - */ +/** +* !#en +* Note: This event is emitted from the node to which the component belongs. +* !#zh +* 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 +* @event scroll-began +* @param {Event.EventCustom} event +* @param {ScrollView} scrollView - The ScrollView component. +*/ diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts new file mode 100644 index 0000000000..6e96eef091 --- /dev/null +++ b/cocos/3d/ui/components/slider-component.ts @@ -0,0 +1,281 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 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/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'; +/** + * !#en The Slider Direction + * !#zh 滑动器方向 + * @enum Slider.Direction + */ +enum Direction { + /** + * !#en The horizontal direction. + * !#zh 水平方向 + * @property {Number} Horizontal + */ + Horizontal = 0, + /** + * !#en The vertical direction. + * !#zh 垂直方向 + * @property {Number} Vertical + */ + Vertical = 1, +} + +Enum(Direction); + +/** + * !#en The Slider Control + * !#zh 滑动器组件 + * @class Slider + * @extends Component + */ +@ccclass('cc.SliderComponent') +@executionOrder(100) +@menu('UI/Slider') +// @executeInEditMode +export class SliderComponent extends Component { + + /** + * !#en The "handle" part of the slider + * !#zh 滑动器滑块按钮部件 + * @property {Button} handle + */ + @property({ + type: SpriteComponent, + }) + get handle () { + return this._handle; + } + + set handle (value: SpriteComponent) { + if (this._handle === value) { + return; + } + + this._handle = value; + if (CC_EDITOR && this._handle) { + this._updateHandlePosition(); + } + } + + /** + * !#en The slider direction + * !#zh 滑动器方向 + * @property {Slider.Direction} direction + */ + @property({ + type: Direction, + }) + get direction () { + return this._direction; + } + + set direction (value: number) { + if (this._direction === value) { + return; + } + + this._direction = value; + } + /** + * !#en The current progress of the slider. The valid value is between 0-1 + * !#zh 当前进度值,该数值的区间是 0-1 之间 + * @property {Number} progress + */ + @property({ + slide: true, + range: [0.1, 1, 0.01], + }) + get progress () { + return this._progress; + } + + set progress (value: number) { + if (this._progress === value) { + return; + } + + this._progress = value; + this._updateHandlePosition(); + } + + /** + * !#en The slider events callback + * !#zh 滑动器组件事件回调函数 + * @property {ComponentEventHandler[]} slideEvents + */ + @property({ + type: ComponentEventHandler, + }) + get slideEvents () { + return this._slideEvents; + } + + set slideEvents (value: ComponentEventHandler[]) { + this._slideEvents = value; + } + + public static Direction = Direction; + @property + public _handle: SpriteComponent | null = null; + @property + public _direction: number = Direction.Horizontal; + @property + public _progress: number = 0.1; + @property + public _slideEvents: ComponentEventHandler[] = []; + + public _offset: Vec2 = new Vec2(); + public _dragging = false; + public _touchHandle = false; + + public __preload () { + this._updateHandlePosition(); + } + + // 注册事件 + public onEnable () { + this._updateHandlePosition(); + + this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this); + this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.on(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); + if (this._handle && this._handle.isValid) { + this._handle.node.on(cc.NodeUI.EventType.TOUCH_START, this._onHandleDragStart, this); + this._handle.node.on(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this); + this._handle.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); + } + } + + public onDisable () { + this.node.off(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this); + this.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this); + this.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.off(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); + if (this._handle && this._handle.isValid) { + this._handle.node.off(cc.NodeUI.EventType.TOUCH_START, this._onHandleDragStart, this); + this._handle.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this); + this._handle.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); + } + } + + public _onHandleDragStart (event: Event) { + if (!event) { + 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()); + + event.stopPropagation(); + } + + public _onTouchBegan (event: Event) { + if (!this._handle) { return; } + this._dragging = true; + if (!this._touchHandle) { + this._handleSliderLogic((event as EventTouch).touch); + } + + event.stopPropagation(); + } + + public _onTouchMoved (event: Event) { + if (!this._dragging) { return; } + this._handleSliderLogic((event as EventTouch).touch); + event.stopPropagation(); + } + + public _onTouchEnded (event: Event) { + this._dragging = false; + this._touchHandle = false; + this._offset = cc.v2(); + event.stopPropagation(); + } + + public _onTouchCancelled (event: Event) { + this._dragging = false; + event.stopPropagation(); + } + + public _handleSliderLogic (touch) { + this._updateProgress(touch); + this._emitSlideEvent(); + } + + public _emitSlideEvent () { + cc.Component.EventHandler.emitEvents(this.slideEvents, this); + this.node.emit('slide', this); + } + + public _updateProgress (touch: EventTouch) { + if (!this._handle) { return; } + const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR((touch as EventTouch).getLocation()); + if (this.direction === Direction.Horizontal) { + 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); + } + } + + public _updateHandlePosition () { + if (!this._handle) { return; } + let handlelocalPos; + if (this._direction === Direction.Horizontal) { + handlelocalPos = cc.v2(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0); + } 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)); + } + } +} + +// cc.Slider = module.exports = Slider; + +/** + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event slide + * @param {Event.EventCustom} event + * @param {Slider} slider - The slider component. + */ diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts new file mode 100644 index 0000000000..b819f2d84b --- /dev/null +++ b/cocos/3d/ui/components/sprite-component.ts @@ -0,0 +1,619 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ +// @ts-check +import atlas from '../../../assets/CCSpriteAtlas'; +import { SpriteFrame } from '../../../assets/CCSpriteFrame'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { clampf } from '../../../core/utils/misc'; +import { Vec2, Enum } from '../../../core/value-types'; +import { MeshBuffer } from '../mesh-buffer'; +import { UIRenderComponent } from './ui-render-component'; +import { Node } from '../../../scene-graph/node'; +import { UI } from '../../../renderer/ui/ui'; +const EventType = Node.EventType; + +/** + * !#en Enum for sprite type. + * !#zh Sprite 类型 + * @enum Sprite.Type + */ +const SpriteType = Enum({ + /** + * !#en The simple type. + * !#zh 普通类型 + * @property {Number} SIMPLE + */ + SIMPLE: 0, + /** + * !#en The sliced type. + * !#zh 切片(九宫格)类型 + * @property {Number} SLICED + */ + SLICED: 1, + // /** + // * !#en The tiled type. + // * !#zh 平铺类型 + // * @property {Number} TILED + // */ + // TILED: 2, + /** + * !#en The filled type. + * !#zh 填充类型 + * @property {Number} FILLED + */ + FILLED: 3, + // /** + // * !#en The mesh type. + // * !#zh 以 Mesh 三角形组成的类型 + // * @property {Number} MESH + // */ + // MESH: 4 +}); + +/** + * !#en Enum for fill type. + * !#zh 填充类型 + * @enum Sprite.FillType + */ +const FillType = cc.Enum({ + /** + * !#en The horizontal fill. + * !#zh 水平方向填充 + * @property {Number} HORIZONTAL + */ + HORIZONTAL: 0, + /** + * !#en The vertical fill. + * !#zh 垂直方向填充 + * @property {Number} VERTICAL + */ + VERTICAL: 1, + // /** + // * !#en The radial fill. + // * !#zh 径向填充 + // * @property {Number} RADIAL + // */ + // RADIAL: 2, +}); + +/** + * !#en Sprite Size can track trimmed size, raw size or none. + * !#zh 精灵尺寸调整模式 + * @enum Sprite.SizeMode + */ +// var SizeMode = cc.Enum({ +// /** +// * !#en Use the customized node size. +// * !#zh 使用节点预设的尺寸 +// * @property {Number} CUSTOM +// */ +// CUSTOM: 0, +// /** +// * !#en Match the trimmed size of the sprite frame automatically. +// * !#zh 自动适配为精灵裁剪后的尺寸 +// * @property {Number} TRIMMED +// */ +// TRIMMED: 1, +// /** +// * !#en Match the raw size of the sprite frame automatically. +// * !#zh 自动适配为精灵原图尺寸 +// * @property {Number} RAW +// */ +// RAW: 2 +// }); + +// var State = cc.Enum({ +// /** +// * !#en The normal state +// * !#zh 正常状态 +// * @property {Number} NORMAL +// */ +// NORMAL: 0, +// /** +// * !#en The gray state, all color will be modified to grayscale value. +// * !#zh 灰色状态,所有颜色会被转换成灰度值 +// * @property {Number} GRAY +// */ +// GRAY: 1 +// }); + +@ccclass('cc.SpriteComponent') +@executionOrder(100) +@menu('UI/Sprite') +@executeInEditMode +export class SpriteComponent extends UIRenderComponent { + + /** + * !#en The sprite frame of the sprite. + * !#zh 精灵的精灵帧 + * @return {SpriteFrame} + */ + @property({ + type: SpriteFrame, + }) + get spriteFrame () { + return this._spriteFrame; + } + + set spriteFrame (value: SpriteFrame | null) { + if (this._spriteFrame === value) { + return; + } + + const lastSprite = this._spriteFrame; + this._spriteFrame = value; + // render & update render data flag will be triggered while applying new sprite frame + this.markForUpdateRenderData(false); + this._applySpriteFrame(lastSprite); + if (CC_EDITOR) { + // @ts-ignore + this.node.emit('spriteframe-changed', this); + } + } + + /** + * !#en The sprite render type. + * !#zh 精灵渲染类型 + * @property type + * @type {Sprite.Type} + * @example + * sprite.type = cc.Sprite.Type.SIMPLE; + */ + @property({ + type: SpriteType, + }) + get type () { + return this._type; + } + set type (value: number) { + if (this._type !== value) { + this._type = value; + this._updateAssembler(); + } + } + + /** + * !#en + * The fill type, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 精灵填充类型,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillType + * @type {Sprite.FillType} + * @example + * sprite.fillType = SpriteComponent.FillType.HORIZONTAL; + */ + @property({ + type: FillType, + }) + get fillType () { + return this._fillType; + } + set fillType (value: number) { + if (value !== this._fillType) { + if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) { + // this.destroyRenderData(/*this._renderData*/); + this._renderData = null; + } else if (this._renderData) { + this.markForUpdateRenderData(true); + } + this._fillType = value; + this._updateAssembler(); + } + } + + /** + * !#en + * The fill Center, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 填充中心点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillCenter + * @type {Vec2} + * @example + * sprite.fillCenter = new cc.v2(0, 0); + */ + @property + get fillCenter () { + return this._fillCenter; + } + set fillCenter (value: Vec2) { + this._fillCenter.x = value.x; + this._fillCenter.y = value.y; + if (this._type === SpriteType.FILLED && this._renderData) { + this.markForUpdateRenderData(true); + } + } + + /** + * !#en + * The fill Start, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 填充起始点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillStart + * @type {Number} + * @example + * // -1 To 1 between the numbers + * sprite.fillStart = 0.5; + */ + @property + get fillStart () { + return this._fillStart; + } + + set fillStart (value: number) { + this._fillStart = clampf(value, -1, 1); + if (this._type === SpriteType.FILLED && this._renderData) { + this.markForUpdateRenderData(true); + } + } + + /** + * !#en + * The fill Range, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 填充范围,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillRange + * @type {Number} + * @example + * // -1 To 1 between the numbers + * sprite.fillRange = 1; + */ + @property + get fillRange () { + return this._fillRange; + } + set fillRange (value: number) { + // ??? -1 ~ 1 + // this._fillRange = cc.misc.clampf(value, -1, 1); + this._fillRange = clampf(value, 0, 1); + if (this._type === SpriteType.FILLED && this._renderData) { + this.markForUpdateRenderData(true); + } + } + /** + * !#en specify the frame is trimmed or not. + * !#zh 是否使用裁剪模式 + * @property trim + * @type {Boolean} + * @example + * sprite.trim = true; + */ + get trim () { + // return this._isTrimmedMode; + return false; + } + + set trim (value: boolean) { + // if (this._isTrimmedMode !== value) { + // this._isTrimmedMode = value; + // if ((this._type === SpriteType.SIMPLE || this._type === SpriteType.MESH) && + // this._renderData) { + // this.markForUpdateRenderData(true); + // } + // } + if (this._spriteFrame) { + this.node.setContentSize(this._spriteFrame.getOriginalSize()); + } + } + + // /** + // * !#en specify the size tracing mode. + // * !#zh 精灵尺寸调整模式 + // * @property sizeMode + // * @type {Sprite.SizeMode} + // * @example + // * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; + // */ + // get sizeMode() { + // return this._sizeMode; + // } + // set sizeMode(value) { + // // this._sizeMode = value; + // // if (value !== SizeMode.CUSTOM) { + // // this._applySpriteSize(); + // // } + // } + + public static FillType = FillType; + public static Type = SpriteType; + @property + public _spriteFrame: SpriteFrame | null = null; + @property + public _type: number = SpriteType.SIMPLE; + @property + public _fillType: number = FillType.HORIZONTAL; + // @property + // _sizeMode = SizeMode.TRIMMED; + @property + public _fillCenter: Vec2 = cc.v2(0, 0); + @property + public _fillStart: number = 0; + @property + public _fillRange: number = 0; + // @property + // _isTrimmedMode = true; + // _state = 0; + // TODO: + @property + public _atlas: atlas | null = null; + public _spriteWidget = null; + // static SizeMode = SizeMode; + // static State = State; + + // /** + // * Change the state of sprite. + // * @method setState + // * @see `SpriteComponent.State` + // * @param state {SpriteComponent.State} NORMAL or GRAY State. + // */ + // getState() { + // return this._state; + // } + + // setState(state) { + // if (this._state === state) return; + // this._state = state; + // this._activateMaterial(); + // } + + // onLoad() {} + + public onEnable () { + super.onEnable(); + if (this._spriteFrame) { + if (!this._spriteFrame.textureLoaded()) { + // this._spriteFrame.once('load', this._onTextureLoaded, this); + this._spriteFrame.ensureLoadTexture(); + } + } + + this._updateAssembler(); + this._activateMaterial(); + + if (!this._spriteFrame) { + this.spriteFrame = cc.builtinResMgr.get('default-spriteframe'); + } + + // this.node.on(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this); + // this.node.on(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this); + } + + public updateAssembler (render: UI) { + if (!this._spriteFrame || !this.material) { + return; + } + super.updateAssembler(render); + } + + public onDestroy () { + super.onDestroy(); + this.destroyRenderData(); + } + + public onDisable () { + // this._super(); + super.onDisable(); + + // this.node.off(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this); + // this.node.off(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this); + } + + public _onNodeSizeDirty () { + if (!this._renderData) { return; } + this.markForUpdateRenderData(true); + } + + public _updateAssembler () { + const assembler = SpriteComponent.Assembler.getAssembler(this); + + if (this._assembler !== assembler) { + this.destroyRenderData(); + this._assembler = assembler; + } + + if (!this._renderData) { + if (this._assembler) { + this._renderData = this._assembler.createData(this); + this._renderData.material = this.material; + this.markForUpdateRenderData(true); + } + } + } + + public _activateMaterial () { + const spriteFrame = this._spriteFrame; + let 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; + if (spriteFrame && spriteFrame.textureLoaded()) { + material!.setProperty('u_texSampler', spriteFrame); + this.markForUpdateRenderData(true); + } + } + // TODO: + // else { + // if (spriteFrame && spriteFrame.textureLoaded()) { + // const matTexture = material && material.getProperty('u_texSampler'); + // if (matTexture !== spriteFrame) { + // material.setProperty('u_texSampler', spriteFrame); + // this.markForUpdateRenderData(true); + // } + // } + // } + + if (this._renderData) { + this._renderData.material = material; + } + } else { + this.markForUpdateRenderData(true); + // this.markForRender(true); + } + } + + public _applyAtlas (spriteFrame: SpriteFrame | null) { + if (!CC_EDITOR) { + return; + } + // Set atlas + if (spriteFrame && spriteFrame.atlasUuid) { + const self = this; + cc.AssetLibrary.loadAsset(spriteFrame.atlasUuid, (err, asset) => { + self._atlas = asset; + }); + } else { + this._atlas = null; + } + } + + public _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; + } + + public markForUpdateRenderData (enable: boolean) { + if (enable /*&& this._canRender()*/) { + // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; + + const renderData = this._renderData; + if (renderData) { + renderData.uvDirty = true; + renderData.vertDirty = true; + } + } + // else if (!enable) { + // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; + // } + } + + // _applySpriteSize() { + // if (this._spriteFrame) { + // if (SizeMode.RAW === this._sizeMode) { + // var size = this._spriteFrame.getOriginalSize(); + // this.node.setContentSize(size); + // } else if (SizeMode.TRIMMED === this._sizeMode) { + // var rect = this._spriteFrame.getRect(); + // this.node.setContentSize(rect.width, rect.height); + // } + + // this._activateMaterial(); + // } + // } + + // _onTextureLoaded() { + // if (!this.isValid) { + // return; + // } + + // this._applySpriteSize(); + // } + + public _applySpriteFrame (oldFrame: SpriteFrame | null) { + // if (oldFrame && oldFrame.off) { + // oldFrame.off('load', this._onTextureLoaded, this); + // } + + const spriteFrame = this._spriteFrame; + // if (!spriteFrame || (this._material && this._material._texture) !== (spriteFrame && spriteFrame._texture)) { + // // disable render flow until texture is loaded + // this.markForRender(false); + // } + + if (spriteFrame) { + if (!oldFrame || spriteFrame !== oldFrame) { + // this.material.setProperty('mainTexture', spriteFrame); + if (spriteFrame.textureLoaded()) { + // this._onTextureLoaded(); + this._activateMaterial(); + } else { + // spriteFrame.once('load', this._onTextureLoaded, this); + spriteFrame.ensureLoadTexture(); + } + } + // else { + // this._applySpriteSize(); + // } + } + + if (CC_EDITOR) { + // Set atlas + this._applyAtlas(spriteFrame); + } + } + + // _resized() { + // if (!CC_EDITOR) { + // return; + // } + + // if (this._spriteFrame) { + // var actualSize = this.node.getContentSize(); + // var expectedW = actualSize.width; + // var expectedH = actualSize.height; + // if (this._sizeMode === SizeMode.RAW) { + // var size = this._spriteFrame.getOriginalSize(); + // expectedW = size.width; + // expectedH = size.height; + // } else if (this._sizeMode === SizeMode.TRIMMED) { + // var rect = this._spriteFrame.getRect(); + // expectedW = rect.width; + // expectedH = rect.height; + + // } + + // if (expectedW !== actualSize.width || expectedH !== actualSize.height) { + // this._sizeMode = SizeMode.CUSTOM; + // } + // } + // } +} + +// if (CC_EDITOR) { +// // override __preload +// Sprite.prototype.__superPreload = cc.Component.prototype.__preload; +// Sprite.prototype.__preload = function () { +// if (this.__superPreload) this.__superPreload(); +// this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); +// }; +// // override onDestroy +// Sprite.prototype.__superOnDestroy = cc.Component.prototype.onDestroy; +// Sprite.prototype.onDestroy = function () { +// if (this.__superOnDestroy) this.__superOnDestroy(); +// this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); +// }; +// } + +// cc.Sprite = module.exports = Sprite; diff --git a/cocos/3d/ui/components/toggle-component.ts b/cocos/3d/ui/components/toggle-component.ts new file mode 100644 index 0000000000..f91afe63f3 --- /dev/null +++ b/cocos/3d/ui/components/toggle-component.ts @@ -0,0 +1,292 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 ComponentEventHandler from '../../../components/CCComponentEventHandler'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ButtonComponent} from './button-component'; +import { SpriteComponent} from './sprite-component'; +import { ToggleGroupComponent} from './toggle-group-component'; + +/** + * !#en The toggle component is a CheckBox, when it used together with a ToggleGroup, it + * could be treated as a RadioButton. + * !#zh Toggle 是一个 CheckBox,当它和 ToggleGroup 一起使用的时候,可以变成 RadioButton。 + * @class Toggle + * @extends Button + */ +@ccclass('cc.ToggleComponent') +@executionOrder(100) +@menu('UI/Toggle') +@executeInEditMode +export class ToggleComponent extends ButtonComponent { + @property + public _isChecked: boolean = true; + @property + public _toggleGroup: ToggleGroupComponent | null = null; + @property + public _checkMark: SpriteComponent | null = null; + @property + public _checkEvents: ComponentEventHandler[] = []; + + /** + * !#en When this value is true, the check mark component will be enabled, otherwise + * the check mark component will be disabled. + * !#zh 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。 + * @property {Boolean} isChecked + */ + @property + get isChecked () { + return this._isChecked; + } + + set isChecked (value) { + if (this._isChecked === value) { + return; + } + + this._isChecked = value; + this._updateCheckMark(); + } + + /** + * !#en The toggle group which the toggle belongs to, when it is null, the toggle is a CheckBox. + * Otherwise, the toggle is a RadioButton. + * !#zh Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox, + * 否则,Toggle 是一个 RadioButton。 + * @property {ToggleGroup} toggleGroup + */ + @property({ + type: ToggleGroupComponent, + }) + get toggleGroup () { + return this._toggleGroup; + } + + set toggleGroup (value) { + if (this._toggleGroup === value) { + return; + } + + if (this._toggleGroup) { + this._toggleGroup.removeToggle(this); + } + this._toggleGroup = value; + if (this._toggleGroup && this._toggleGroup.enabled) { + this._toggleGroup.addToggle(this); + } + } + + /** + * !#en The image used for the checkmark. + * !#zh Toggle 处于选中状态时显示的图片 + * @property {Sprite} checkMark + */ + @property({ + type: SpriteComponent, + }) + get checkMark () { + return this._checkMark; + } + + set checkMark (value: SpriteComponent) { + if (this._checkMark === value) { + return; + } + + this._checkMark = value; + } + + /** + * !#en If Toggle is clicked, it will trigger event's handler + * !#zh Toggle 按钮的点击事件列表。 + * @property {ComponentEventHandler[]} checkEvents + */ + @property({ + type: ComponentEventHandler, + }) + get checkEvents () { + return this._checkEvents; + } + + set checkEvents (value: ComponentEventHandler[]) { + this._checkEvents = value; + } + + set _resizeToTarget (value: boolean) { + if (value) { + this._resizeNodeToTargetNode(); + } + } + + get _toggleContainer () { + const parent = this.node.parent; + // TODO: + // if (cc.Node.isNode(parent)) { + // return parent.getComponent(cc.ToggleContainer); + // } + return null; + } + + public onEnable () { + super.onEnable(); + if (!CC_EDITOR) { + this._registerToggleEvent(); + } + + if (this._toggleGroup && this._toggleGroup.enabled) { + this._toggleGroup.addToggle(this); + } + } + + public onDisable () { + super.onEnable(); + if (!CC_EDITOR) { + this._unregisterToggleEvent(); + } + if (this._toggleGroup && this._toggleGroup.enabled) { + this._toggleGroup.removeToggle(this); + } + } + + public _updateCheckMark () { + if (this._checkMark) { + this._checkMark.node.active = !!this.isChecked; + } + } + + // _updateDisabledState() { + // this._super(); + + // if (this._checkMark) { + // this._checkMark.setState(0); + // } + // if (this.enableAutoGrayEffect) { + // if (this._checkMark && !this.interactable) { + // this._checkMark.setState(1); + // } + // } + // } + + public _registerToggleEvent () { + this.node.on('click', this.toggle, this); + } + + public _unregisterToggleEvent () { + this.node.off('click', this.toggle, this); + } + + public toggle (event) { + const group = this.toggleGroup || this._toggleContainer; + + if (group && group.enabled && this.isChecked) { + if (!group.allowSwitchOff) { + return; + } + } + + this.isChecked = !this.isChecked; + + this._updateCheckMark(); + + if (group && group.enabled) { + group.updateToggles(this); + } + + this._emitToggleEvents(); + } + + public _emitToggleEvents () { + this.node.emit('toggle', this); + if (this._checkEvents) { + ComponentEventHandler.emitEvents(this._checkEvents, this); + } + } + + /** + * !#en Make the toggle button checked. + * !#zh 使 toggle 按钮处于选中状态 + * @method check + */ + public check () { + const group = this.toggleGroup || this._toggleContainer; + + if (group && group.enabled && this.isChecked) { + if (!group.allowSwitchOff) { + return; + } + } + + this.isChecked = true; + + if (group && group.enabled) { + group.updateToggles(this); + } + + this._emitToggleEvents(); + } + + /** + * !#en Make the toggle button unchecked. + * !#zh 使 toggle 按钮处于未选中状态 + * @method uncheck + */ + public uncheck () { + const group = this.toggleGroup || this._toggleContainer; + + if (group && group.enabled && this.isChecked) { + if (!group.allowSwitchOff) { + return; + } + } + + this.isChecked = false; + + this._emitToggleEvents(); + } +} + +// cc.Toggle = module.exports = Toggle; + +// var js = require('../platform/js'); + +// js.get(Toggle.prototype, '_toggleContainer', +// function () { +// var parent = this.node.parent; +// if (cc.Node.isNode(parent)) { +// return parent.getComponent(cc.ToggleContainer); +// } +// return null; +// } +// ); + +/** + * !#en + * Note: This event is emitted from the node to which the component belongs. + * !#zh + * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 + * @event toggle + * @param {Event.EventCustom} event + * @param {Toggle} toggle - The Toggle component. + */ diff --git a/cocos/2d/ui/CCToggleContainer.js b/cocos/3d/ui/components/toggle-container-component.ts similarity index 67% rename from cocos/2d/ui/CCToggleContainer.js rename to cocos/3d/ui/components/toggle-container-component.ts index 3d5801ba21..0df82c396e 100644 --- a/cocos/2d/ui/CCToggleContainer.js +++ b/cocos/3d/ui/components/toggle-container-component.ts @@ -34,38 +34,41 @@ * @class ToggleContainer * @extends Component */ -var ToggleContainer = cc.Class({ - name: 'cc.ToggleContainer', - extends: cc.Component, - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/ToggleContainer', - help: 'i18n:COMPONENT.help_url.toggleContainer', - executeInEditMode: true - }, - properties: { - /** - * !#en If this setting is true, a toggle could be switched off and on when pressed. - * If it is false, it will make sure there is always only one toggle could be switched on - * and the already switched on toggle can't be switched off. - * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 - * @property {Boolean} allowSwitchOff - */ - allowSwitchOff: { - tooltip: CC_DEV && 'i18n:COMPONENT.toggle_group.allowSwitchOff', - default: false - }, - }, +import { Component } from '../../../components/component'; +import { ccclass, executeInEditMode, menu, property } from '../../../core/data/class-decorator'; - updateToggles: function (toggle) { +@ccclass('cc.ToggleContainerComponent') +export class ToggleContainerComponent extends Component { + @property + protected _allowSwitchOff = false; + @property + public toggleItems: Component[] = []; + /** + * !#en If this setting is true, a toggle could be switched off and on when pressed. + * If it is false, it will make sure there is always only one toggle could be switched on + * and the already switched on toggle can't be switched off. + * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 + * @property {Boolean} allowSwitchOff + */ + @property + get allowSwitchOff() { + return this._allowSwitchOff; + } + + set allowSwitchOff(value) { + this._allowSwitchOff = value; + } + + updateToggles(toggle) { this.toggleItems.forEach(function (item) { if (toggle.isChecked && item !== toggle) { item.isChecked = false; } }); - }, + } - _allowOnlyOneToggleChecked: function () { + _allowOnlyOneToggleChecked() { var isChecked = false; this.toggleItems.forEach(function (item) { if (isChecked) { @@ -77,9 +80,9 @@ var ToggleContainer = cc.Class({ }); return isChecked; - }, + } - _makeAtLeastOneToggleChecked: function () { + _makeAtLeastOneToggleChecked() { var isChecked = this._allowOnlyOneToggleChecked(); if (!isChecked && !this.allowSwitchOff) { @@ -88,33 +91,20 @@ var ToggleContainer = cc.Class({ toggleItems[0].check(); } } - }, + } - onEnable: function () { + onEnable() { + this.toggleItems = this.node.getComponentsInChildren(cc.ToggleComponent); this.node.on('child-added', this._allowOnlyOneToggleChecked, this); this.node.on('child-removed', this._makeAtLeastOneToggleChecked, this); - }, + } - onDisable: function () { + onDisable() { this.node.off('child-added', this._allowOnlyOneToggleChecked, this); this.node.off('child-removed', this._makeAtLeastOneToggleChecked, this); - }, + } - start: function () { + start() { this._makeAtLeastOneToggleChecked(); } -}); - -/** - * !#en Read only property, return the toggle items array reference managed by ToggleContainer. - * !#zh 只读属性,返回 ToggleContainer 管理的 toggle 数组引用 - * @property {Toggle[]} toggleItems - */ -var js = require('../platform/js'); -js.get(ToggleContainer.prototype, 'toggleItems', - function () { - return this.node.getComponentsInChildren(cc.Toggle); - } -); - -cc.ToggleContainer = module.exports = ToggleContainer; +} diff --git a/cocos/2d/ui/CCToggleGroup.js b/cocos/3d/ui/components/toggle-group-component.ts similarity index 57% rename from cocos/2d/ui/CCToggleGroup.js rename to cocos/3d/ui/components/toggle-group-component.ts index 035598aa62..e27de57a10 100644 --- a/cocos/2d/ui/CCToggleGroup.js +++ b/cocos/3d/ui/components/toggle-group-component.ts @@ -23,6 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +import { Component} from '../../../components/component'; +import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator'; +import { ToggleComponent} from './toggle-component'; /** * !#en ToggleGroup is not a visiable UI component but a way to modify the behavior of a set of Toggles. @@ -32,74 +35,77 @@ * @class ToggleGroup * @extends Component */ -var ToggleGroup = cc.Class({ - name: 'cc.ToggleGroup', - extends: cc.Component, - ctor: function () { - this._toggleItems = []; - }, - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/ToggleGroup (Legacy)', - help: 'i18n:COMPONENT.help_url.toggleGroup' - }, - properties: { - /** - * !#en If this setting is true, a toggle could be switched off and on when pressed. - * If it is false, it will make sure there is always only one toggle could be switched on - * and the already switched on toggle can't be switched off. - * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 - * @property {Boolean} allowSwitchOff - */ - allowSwitchOff: { - tooltip: CC_DEV && 'i18n:COMPONENT.toggle_group.allowSwitchOff', - default: false - }, +@ccclass('cc.ToggleGroupComponent') +@executionOrder(100) +@menu('UI/ToggleGroup') +@executeInEditMode +export class ToggleGroupComponent extends Component { + @property + _allowSwitchOff: boolean = false; + _toggleItems: ToggleComponent[] = []; - /** - * !#en Read only property, return the toggle items array reference managed by toggleGroup. - * !#zh 只读属性,返回 toggleGroup 管理的 toggle 数组引用 - * @property {Array} toggleItems - */ - toggleItems: { - get: function () { - return this._toggleItems; - } - } - }, + /** + * !#en If this setting is true, a toggle could be switched off and on when pressed. + * If it is false, it will make sure there is always only one toggle could be switched on + * and the already switched on toggle can't be switched off. + * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 + * @property {Boolean} allowSwitchOff + */ + @property + get allowSwitchOff() { + return this._allowSwitchOff; + } - updateToggles: function (toggle) { - if(!this.enabledInHierarchy) return; + set allowSwitchOff(value: boolean) { + this._allowSwitchOff = value; + } - this._toggleItems.forEach(function (item){ - if(toggle.isChecked) { + /** + * !#en Read only property, return the toggle items array reference managed by toggleGroup. + * !#zh 只读属性,返回 toggleGroup 管理的 toggle 数组引用 + * @property {Array} toggleItems + */ + get toggleItems() { + return this._toggleItems; + } + + start() { + this._makeAtLeastOneToggleChecked(); + } + + updateToggles(toggle: ToggleComponent) { + if (!this.enabledInHierarchy) return; + + this._toggleItems.forEach(function (item) { + if (toggle.isChecked) { if (item !== toggle && item.isChecked && item.enabled) { item.isChecked = false; } } }); - }, + } - addToggle: function (toggle) { + addToggle(toggle: ToggleComponent) { var index = this._toggleItems.indexOf(toggle); if (index === -1) { this._toggleItems.push(toggle); } this._allowOnlyOneToggleChecked(); - }, + } - removeToggle: function (toggle) { + removeToggle(toggle: ToggleComponent) { var index = this._toggleItems.indexOf(toggle); - if(index > -1) { + if (index > -1) { this._toggleItems.splice(index, 1); } this._makeAtLeastOneToggleChecked(); - }, + } - _allowOnlyOneToggleChecked: function () { + _allowOnlyOneToggleChecked() { var isChecked = false; this._toggleItems.forEach(function (item) { - if(isChecked && item.enabled) { + if (isChecked && item.enabled) { item.isChecked = false; } @@ -109,31 +115,15 @@ var ToggleGroup = cc.Class({ }); return isChecked; - }, + } - _makeAtLeastOneToggleChecked: function () { + _makeAtLeastOneToggleChecked() { var isChecked = this._allowOnlyOneToggleChecked(); - if(!isChecked && !this.allowSwitchOff) { - if(this._toggleItems.length > 0) { + if (!isChecked && !this._allowSwitchOff) { + if (this._toggleItems.length > 0) { this._toggleItems[0].isChecked = true; } } - }, - - start: function () { - this._makeAtLeastOneToggleChecked(); } -}); - -var js = require('../platform/js'); -var showed = false; -js.get(cc, 'ToggleGroup', function () { - if (!showed) { - cc.logID(1405, 'cc.ToggleGroup', 'cc.ToggleContainer'); - showed = true; - } - return ToggleGroup; -}); - -module.exports = ToggleGroup; +} diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts new file mode 100644 index 0000000000..87b5b57160 --- /dev/null +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -0,0 +1,304 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { RenderableComponent } from '../../../3d/framework/renderable-component'; +// import gfx from '../../renderer/gfx/index'; +import { + ccclass, + executeInEditMode, + executionOrder, + property, + requireComponent, +} from '../../../core/data/class-decorator'; +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 { IAssembler } from '../assembler/assembler'; +import { MeshBuffer } from '../mesh-buffer'; +import { CanvasComponent } from './canvas-component'; +import { UITransformComponent } from './ui-transfrom-component'; + +/** + * !#en + * Base class for components which supports rendering features. + * !#zh + * 所有支持渲染的组件的基类 + * + * @class UIRenderComponent + * @extends Component + */ +@ccclass('cc.UIRenderComponent') +@executionOrder(100) +@requireComponent(UITransformComponent) +export class UIRenderComponent extends RenderableComponent { + + /** + * !#en specify the source Blend Factor, this will generate a custom material object + * please pay attention to the memory cost. + * !#zh 指定原图的混合模式,这会克隆一个新的材质对象,注意这带来的 + * @property srcBlendFactor + * sprite.srcBlendFactor = macro.BlendFactor.ONE; + */ + @property({ + type: macro.BlendFactor, + }) + get srcBlendFactor () { + return this._srcBlendFactor; + } + set srcBlendFactor (value) { + if (this._srcBlendFactor === value) { return; } + this._srcBlendFactor = value; + this._updateBlendFunc(true); + } + + /** + * !#en specify the destination Blend Factor. + * !#zh 指定目标的混合模式 + * @property dstBlendFactor + * @type {macro.BlendFactor} + * @example + * sprite.dstBlendFactor = cc.macro.BlendFactor.ONE; + */ + @property({ + type: macro.BlendFactor, + }) + get dstBlendFactor () { + return this._dstBlendFactor; + } + + set dstBlendFactor (value) { + if (this._dstBlendFactor === value) { return; } + this._dstBlendFactor = value; + this._updateBlendFunc(true); + } + + /** + * !#en render order, render order according to width, and arrange once under the same level node. + * !#zh 渲染先后顺序,按照广度渲染排列,同级节点下进行一次排列 + */ + @property + get priority() { + return this._priority; + } + + set priority(value) { + this._priority = value; + } + + /** + * !#en render color + * !#zh 渲染颜色 + * @property color + */ + get color() { + return this._color; + } + + set color(value) { + if (this._color === value) { + return; + } + + this._color = value; + } + + get visibility () { + return this._visibility; + } + + get renderData () { + return this._renderData; + } + + public static assembler = 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 _color: Color = Color.WHITE; + @property + protected _priority: number = 0; + protected _renderData: RenderData | null = null; + // _allocedDatas = []; + // _vertexFormat = null; + // _toPostHandle = false; + + constructor () { + super(); + // this._assembler = this.constructor._assembler; + // this._postAssembler = this.constructor._postAssembler; + } + + public onEnable () { + let parent = this.node; + while (parent) { + if (parent) { + const canvasComp = parent.getComponent(CanvasComponent); + if (canvasComp) { + this._visibility = canvasComp.visibility; + break; + } + } + + // @ts-ignore + parent = parent.parent; + } + // if (this.node._renderComponent) { + // this.node._renderComponent.enabled = false; + // } + // this.node._renderComponent = this; + // this.node._renderFlag |= RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR; + } + + public onDisable () { + this._visibility = -1; + // this.node._renderComponent = null; + // this.disableRender(); + } + + public onDestroy () { + // for (let i = 0, l = this._allocedDatas.length; i < l; i++) { + // RenderData.free(this._allocedDatas[i]); + // } + // this._allocedDatas.length = 0; + this.destroyRenderData(); + this.material = null; + this._renderData = null; + } + + // _canRender() { + // return this._enabled; + // } + + // markForUpdateRenderData(enable) { + // // if (enable && this._canRender()) { + // // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; + // // } + // // else if (!enable) { + // // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; + // // } + // } + + // markForRender(enable) { + // // if (enable && this._canRender()) { + // // this.node._renderFlag |= RenderFlow.FLAG_RENDER; + // // } + // // else if (!enable) { + // // this.node._renderFlag &= ~RenderFlow.FLAG_RENDER; + // // } + // } + + // markForCustomIARender(enable) { + // // if (enable && this._canRender()) { + // // this.node._renderFlag |= RenderFlow.FLAG_CUSTOM_IA_RENDER; + // // } + // // else if (!enable) { + // // this.node._renderFlag &= ~RenderFlow.FLAG_CUSTOM_IA_RENDER; + // // } + // } + + // disableRender() { + // // this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_CUSTOM_IA_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR); + // } + + public requestRenderData () { + const data = RenderData.add(); + // this._allocedDatas.push(data); + this._renderData = data.data; + this._renderDataPoolID = data.pooID; + return this._renderData; + } + + public destroyRenderData () { + // let index = this._allocedDatas.indexOf(data); + // if (index !== -1) { + // this._allocedDatas.splice(index, 1); + // RenderData.free(data); + // } + if (this._renderDataPoolID === -1) { + return; + } + + RenderData.remove(this._renderDataPoolID); + this._renderDataPoolID = -1; + this._renderData = null; + } + + public _updateColor () { + const material = this.material; + if (material) { + material.setProperty('color', this._color); + // material.updateHash(); + } + } + + // TODO: + public _updateBlendFunc (updateHash) { + // if (!this.material) { + // return; + // } + + // var pass = this.material._mainTech.passes[0]; + // pass.setBlend( + // gfx.BLEND_FUNC_ADD, + // this._srcBlendFactor, this._dstBlendFactor, + // gfx.BLEND_FUNC_ADD, + // this._srcBlendFactor, this._dstBlendFactor + // ); + + // if (updateHash) { + // this.material.updateHash(); + // } + } + + 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); + } + } +} + +// RenderComponent._assembler = null; +// RenderComponent._postAssembler = null; diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts new file mode 100644 index 0000000000..bc113e7d4f --- /dev/null +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -0,0 +1,325 @@ +import { Component} from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator'; +import Event from '../../../core/event/event'; +import { Enum, Mat4 } from '../../../core/value-types'; +import Size from '../../../core/value-types/size'; +import Vec2 from '../../../core/value-types/vec2'; +import * as math from '../../../core/vmath/index'; + +const _vec2a = cc.v2(); +const _vec2b = cc.v2(); +const _mat4_temp = cc.mat4(); +const _worldMatrix = cc.mat4(); + +const EventType = Enum({ + /** + * !#en The event type for size change events. + * Performance note, this event will be triggered every time corresponding properties being changed, + * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. + * !#zh 当节点尺寸改变时触发的事件。 + * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 + * @property {String} SIZE_CHANGED + * @static + */ + SIZE_CHANGED: 'size-changed', + /** + * !#en The event type for anchor point change events. + * Performance note, this event will be triggered every time corresponding properties being changed, + * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. + * !#zh 当节点锚点改变时触发的事件。 + * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 + * @property {String} ANCHOR_CHANGED + * @static + */ + ANCHOR_CHANGED: 'anchor-changed', +}); + +@ccclass('cc.UITransformComponent') +@executionOrder(100) +@executeInEditMode +export class UITransformComponent extends Component { + + @property + get contentSize () { + return this._contentSize; + } + + set contentSize (value) { + if (this._contentSize === value) { + return; + } + + this._contentSize = value; + this.node.emit(EventType.SIZE_CHANGED); + } + + get width () { + return this._contentSize.width; + } + + set width (value) { + if (this._contentSize.width === value) { + return; + } + + this._contentSize.width = value; + this.node.emit(EventType.SIZE_CHANGED); + } + + get height () { + return this._contentSize.height; + } + + set height (value) { + if (this._contentSize.height === value) { + return; + } + + this._contentSize.height = value; + this.node.emit(EventType.SIZE_CHANGED); + } + + @property + get anchorPoint () { + return this._anchorPoint; + } + + set anchorPoint (value) { + if (this._anchorPoint === value) { + return; + } + + this._anchorPoint = value; + this.node.emit(EventType.ANCHOR_CHANGED); + } + + get anchorX () { + return this._anchorPoint.x; + } + + set anchorX (value) { + if (this._anchorPoint.x === value) { + return; + } + + this._anchorPoint.x = value; + this.node.emit(EventType.ANCHOR_CHANGED); + } + + get anchorY () { + return this._anchorPoint.y; + } + + set anchorY (value) { + if (this._anchorPoint.y === value) { + return; + } + + this._anchorPoint.y = value; + this.node.emit(EventType.ANCHOR_CHANGED); + } + + public static EventType = EventType; + @property + public _contentSize = new cc.Size(100, 100); + @property + public _anchorPoint = cc.v2(0.5, 0.5); + + public __preload () { + this.node.uiTransfromComp = this; + } + + public onDestroy () { + this.node.uiTransfromComp = null; + } + + /** + * !#en + * Sets the untransformed size of the node.
+ * The contentSize remains the same no matter the node is scaled or rotated.
+ * All nodes has a size. Layer and Scene has the same size of the screen. + * !#zh 设置节点原始大小,不受该节点是否被缩放或者旋转的影响。 + * @method setContentSize + * @param {Size|Number} size - The untransformed size of the node or The untransformed size's width of the node. + * @param {Number} [height] - The untransformed size's height of the node. + * @example + * node.setContentSize(cc.size(100, 100)); + * node.setContentSize(100, 100); + */ + public setContentSize (size: Size|number, height?: number) { + const locContentSize = this._contentSize; + // var 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.height = height; + } + // if (CC_EDITOR) { + // this.emit(EventType.SIZE_CHANGED, clone); + // } + // else { + this.node.emit(EventType.SIZE_CHANGED); + // } + } + + /** + * !#en + * Sets the anchor point in percent.
+ * anchor point is the point around which all transformations and positioning manipulations take place.
+ * It's like a pin in the node where it is "attached" to its parent.
+ * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
+ * But you can use values higher than (1,1) and lower than (0,0) too.
+ * The default anchor point is (0.5,0.5), so it starts at the center of the node. + * !#zh + * 设置锚点的百分比。
+ * 锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。
+ * 锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。
+ * 但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。
+ * 默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。
+ * 注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。 + * @method setAnchorPoint + * @param {Vec2|Number} point - The anchor point of node or The x axis anchor of node. + * @param {Number} [y] - The y axis anchor of node. + * @example + * node.setAnchorPoint(cc.v2(1, 1)); + * node.setAnchorPoint(1, 1); + */ + public setAnchorPoint (point: Vec2 | number, y?: number) { + const locAnchorPoint = this._anchorPoint; + if (y === undefined) { + point = point as Vec2; + if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y)) { + return; + } + locAnchorPoint.x = point.x; + locAnchorPoint.y = point.y; + } else { + if ((point === locAnchorPoint.x) && (y === locAnchorPoint.y)) { + return; + } + locAnchorPoint.x = point; + locAnchorPoint.y = y; + } + // this.setLocalDirty(LocalDirtyFlag.POSITION); + // if (this._eventMask & ANCHOR_ON) { + this.node.emit(EventType.ANCHOR_CHANGED); + // } + } + + public isHit (point: Vec2, listener: Event|null = null) { + const w = this._contentSize.width; + const h = this._contentSize.height; + const cameraPt = _vec2a; + const testPt = _vec2b; + + const renderComp = this.node.getComponent(cc.RenderComponent); + if (!renderComp) { + return false; + } + const canvas = cc.CanvasComponent.findView(renderComp); + if (!canvas) { + return; + } + + canvas.node.getWorldRT(_mat4_temp); + + const m12 = _mat4_temp.m12; + const m13 = _mat4_temp.m13; + + const center = cc.visibleRect.center; + // let size = cc.view.getFrameSize(); + // let center = cc.v2(size.width / 2, size.height / 2); + // let center = cc.v2(cc.game._renderer._device._gl.canvas.width / 2, cc.game._renderer._device._gl.canvas.height / 2); + _mat4_temp.m12 = center.x - (_mat4_temp.m00 * m12 + _mat4_temp.m04 * m13); + _mat4_temp.m13 = center.y - (_mat4_temp.m01 * m12 + _mat4_temp.m05 * m13); + + // if (out !== _mat4_temp) { + // mat4.copy(out, _mat4_temp); + // } + math.mat4.invert(_mat4_temp, _mat4_temp); + math.vec2.transformMat4(cameraPt, point, _mat4_temp); + // let camera = cc.Camera.findCamera(this); + // if (camera) { + // camera.getCameraToWorldPoint(point, cameraPt); + // } + // else { + // cameraPt.set(point); + // } + + this.node.getWorldMatrix(_worldMatrix); + math.mat4.invert(_mat4_temp, _worldMatrix); + math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); + testPt.x += this._anchorPoint.x * w; + testPt.y += this._anchorPoint.y * h; + + if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { + if (listener && listener.mask) { + const mask = listener.mask; + const parent = this; + // find mask parent, should hit test it + if (parent === mask.node) { + const comp = parent.getComponent(cc.Mask); + return (comp && comp.enabledInHierarchy) ? comp.node.uiTransfromComp!.isHit(cameraPt) : true; + } else { + listener.mask = null; + return true; + } + } else { + return true; + } + } else { + return false; + } + } + + /** + * !#en + * Converts a Point to node (local) space coordinates in which the anchor point is the origin position. + * !#zh + * 将一个点转换到节点 (局部) 空间坐标系,这个坐标系以锚点为原点。 + * @method convertToNodeSpaceAR + * @param {Vec2} worldPoint + * @return {Vec2} + * @example + * var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100)); + */ + public convertToNodeSpaceAR (worldPoint) { + const matrix = new Mat4(); + this.node.getWorldMatrix(matrix); + math.mat4.invert(_mat4_temp, matrix); + const out = new cc.Vec2(); + return math.vec2.transformMat4(out, worldPoint, _mat4_temp); + } + + /** + * !#en + * Converts a Point in node coordinates to world space coordinates. + * !#zh + * 将节点坐标系下的一个点转换到世界空间坐标系。 + * @method convertToWorldSpaceAR + * @param {Vec2} nodePoint + * @return {Vec2} + * @example + * var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100)); + */ + public convertToWorldSpaceAR (nodePoint) { + this.node.getWorldMatrix(_worldMatrix); + const out = new cc.Vec2(); + return math.vec2.transformMat4(out, nodePoint, _worldMatrix); + } +} diff --git a/cocos/2d/ui/CCViewGroup.js b/cocos/3d/ui/components/view-group-component.ts similarity index 94% rename from cocos/2d/ui/CCViewGroup.js rename to cocos/3d/ui/components/view-group-component.ts index 04b7b2f79f..9317c26127 100644 --- a/cocos/2d/ui/CCViewGroup.js +++ b/cocos/3d/ui/components/view-group-component.ts @@ -39,11 +39,9 @@ * @class ViewGroup * @extends Component */ -var ViewGroup = cc.Class({ - name: 'cc.ViewGroup', - extends: require('./CCComponent') -}); +import { Component } from "../../../components/component"; +export class ViewGroupComponent extends Component{ -cc.ViewGroup = module.exports = ViewGroup; +} diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts new file mode 100644 index 0000000000..24c9160a1d --- /dev/null +++ b/cocos/3d/ui/components/widget-component.ts @@ -0,0 +1,645 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { widgetManager } from '../../../2d/base-ui/widget-manager'; +import { Component} from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { Node } from '../../../scene-graph/index'; +/** + * !#en Enum for Widget's alignment mode, indicating when the widget should refresh. + * !#zh Widget 的对齐模式,表示 Widget 应该何时刷新。 + * @enum Widget.AlignMode + */ +/** + * !#en + * Only align once when the Widget is enabled for the first time. + * This will allow the script or animation to continue controlling the current node. + * It will only be aligned once before the end of frame when onEnable is called, + * then immediately disables the Widget. + * !#zh + * 仅在 Widget 第一次激活时对齐一次,便于脚本或动画继续控制当前节点。 + * 开启后会在 onEnable 时所在的那一帧结束前对齐一次,然后立刻禁用该 Widget。 + * @property {Number} ONCE + */ +/** + * !#en Align first from the beginning as ONCE, and then realign it every time the window is resized. + * !#zh 一开始会像 ONCE 一样对齐一次,之后每当窗口大小改变时还会重新对齐。 + * @property {Number} ON_WINDOW_RESIZE + */ +/** + * !#en Keep aligning all the way. + * !#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; + +/** + * !#en + * Stores and manipulate the anchoring based on its parent. + * Widget are used for GUI but can also be used for other things. + * Widget will adjust current node's position and size automatically, but the results after adjustment can not be obtained until the next frame unless you call {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}} manually. + * !#zh + * Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。 + * Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到,除非你先手动调用 {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}}。 + * + * @class Widget + * @extends Component + */ +@ccclass('cc.WidgetComponent') +@executionOrder(100) +@menu('UI/Widget') +@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. + * !#zh 指定一个对齐目标,只能是当前节点的其中一个父节点,默认为空,为空时表示当前父节点。 + * @property {Node} target + * @default null + */ + @property({ + type: Node, + }) + get target () { + return this._target; + } + + set target (value) { + this._target = value; + 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); + } + } + + // ENABLE ALIGN ? + + /** + * !#en Whether to align the top. + * !#zh 是否对齐上边。 + * @property isAlignTop + * @type {Boolean} + * @default false + */ + @property + get isAlignTop () { + return (this._alignFlags & TOP) > 0; + } + set isAlignTop (value) { + this._setAlign(TOP, value); + } + + /** + * !#en Whether to align the bottom. + * !#zh 是否对齐下边。 + * @property isAlignBottom + * @type {Boolean} + * @default false + */ + @property + get isAlignBottom () { + return (this._alignFlags & BOT) > 0; + } + set isAlignBottom (value) { + this._setAlign(BOT, value); + } + + /** + * !#en Whether to align the left. + * !#zh 是否对齐左边 + * @property isAlignLeft + * @type {Boolean} + * @default false + */ + @property + get isAlignLeft () { + return (this._alignFlags & LEFT) > 0; + } + set isAlignLeft (value) { + this._setAlign(LEFT, value); + } + + /** + * !#en Whether to align the right. + * !#zh 是否对齐右边。 + * @property isAlignRight + * @type {Boolean} + * @default false + */ + @property + get isAlignRight () { + return (this._alignFlags & RIGHT) > 0; + } + set isAlignRight (value) { + this._setAlign(RIGHT, value); + } + + /** + * !#en + * Vertically aligns the midpoint, This will open the other vertical alignment options cancel. + * !#zh + * 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。 + * @property isAlignVerticalCenter + * @type {Boolean} + * @default false + */ + @property + get isAlignVerticalCenter () { + return (this._alignFlags & MID) > 0; + } + set isAlignVerticalCenter (value) { + if (value) { + this.isAlignTop = false; + this.isAlignBottom = false; + this._alignFlags |= MID; + } else { + this._alignFlags &= ~MID; + } + } + + /** + * !#en + * Horizontal aligns the midpoint. This will open the other horizontal alignment options canceled. + * !#zh + * 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。 + * @property isAlignHorizontalCenter + * @type {Boolean} + * @default false + */ + @property + get isAlignHorizontalCenter () { + return (this._alignFlags & CENTER) > 0; + } + set isAlignHorizontalCenter (value) { + if (value) { + this.isAlignLeft = false; + this.isAlignRight = false; + this._alignFlags |= CENTER; + } else { + this._alignFlags &= ~CENTER; + } + } + + /** + * !#en + * Whether the stretched horizontally, when enable the left and right alignment will be stretched horizontally, + * the width setting is invalid (read only). + * !#zh + * 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸,此时节点的宽度只读。 + * @property isStretchWidth + * @type {Boolean} + * @default false + * @readOnly + */ + @property({ + visible: false, + }) + get isStretchWidth () { + return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT; + } + + /** + * !#en + * Whether the stretched vertically, when enable the left and right alignment will be stretched vertically, + * then height setting is invalid (read only) + * !#zh + * 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度只读。 + * @property isStretchHeight + * @type {Boolean} + * @default false + * @readOnly + */ + @property({ + visible: false, + }) + get isStretchHeight () { + return (this._alignFlags & TOP_BOT) === TOP_BOT; + } + + // ALIGN MARGINS + + /** + * !#en + * The margins between the top of this node and the top of parent node, + * the value can be negative, Only available in 'isAlignTop' open. + * !#zh + * 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。 + * @property top + * @type {Number} + * @default 0 + */ + @property + get top () { + return this._top; + } + set top (value) { + this._top = value; + } + + /** + * !#en + * The margins between the bottom of this node and the bottom of parent node, + * the value can be negative, Only available in 'isAlignBottom' open. + * !#zh + * 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。 + * @property bottom + * @type {Number} + * @default 0 + */ + @property + get bottom () { + return this._bottom; + } + set bottom (value) { + this._bottom = value; + } + + /** + * !#en + * The margins between the left of this node and the left of parent node, + * the value can be negative, Only available in 'isAlignLeft' open. + * !#zh + * 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。 + * @property left + * @type {Number} + * @default 0 + */ + @property + get left () { + return this._left; + } + set left (value) { + this._left = value; + } + + /** + * !#en + * The margins between the right of this node and the right of parent node, + * the value can be negative, Only available in 'isAlignRight' open. + * !#zh + * 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。 + * @property right + * @type {Number} + * @default 0 + */ + @property + get right () { + return this._right; + } + set right (value) { + this._right = value; + } + + /** + * !#en + * Horizontal aligns the midpoint offset value, + * the value can be negative, Only available in 'isAlignHorizontalCenter' open. + * !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。 + * @property horizontalCenter + * @type {Number} + * @default 0 + */ + @property + get horizontalCenter () { + return this._horizontalCenter; + } + set horizontalCenter (value) { + this._horizontalCenter = value; + } + + /** + * !#en + * Vertical aligns the midpoint offset value, + * the value can be negative, Only available in 'isAlignVerticalCenter' open. + * !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。 + * @property verticalCenter + * @type {Number} + * @default 0 + */ + @property + get verticalCenter () { + return this._verticalCenter; + } + set verticalCenter (value) { + this._verticalCenter = value; + } + + /** + * !#en + * If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. + * !#zh + * 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 + * @property isAbsoluteTop + * @type {Boolean} + * @default true + */ + @property + get isAbsoluteTop () { + return this._isAbsTop; + } + set isAbsoluteTop (value) { + this._isAbsTop = value; + } + + /** + * !#en + * If true, bottom is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. + * !#zh + * 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 + * @property isAbsoluteBottom + * @type {Boolean} + * @default true + */ + @property + get isAbsoluteBottom () { + return this._isAbsBottom; + } + set isAbsoluteBottom (value) { + this._isAbsBottom = value; + } + + /** + * !#en + * If true, left is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. + * !#zh + * 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 + * @property isAbsoluteLeft + * @type {Boolean} + * @default true + */ + @property + get isAbsoluteLeft () { + return this._isAbsLeft; + } + set isAbsoluteLeft (value) { + this._isAbsLeft = value; + } + + /** + * !#en + * If true, right is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. + * !#zh + * 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 + * @property isAbsoluteRight + * @type {Boolean} + * @default true + */ + @property + get isAbsoluteRight () { + return this._isAbsRight; + } + set isAbsoluteRight (value) { + this._isAbsRight = value; + } + + /** + * !#en Specifies the alignment mode of the Widget, which determines when the widget should refresh. + * !#zh 指定 Widget 的对齐模式,用于决定 Widget 应该何时刷新。 + * @property {Widget.AlignMode} alignMode + * @example + * widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE; + */ + @property({ + type: AlignMode, + }) + get alignMode () { + return this._alignMode; + } + + set alignMode (value) { + this._alignMode = value; + } + + /** + * !#en If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin. + * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 + * @property isAbsoluteHorizontalCenter + * @type {Boolean} + * @default true + */ + @property + get isAbsoluteHorizontalCenter () { + return this._isAbsHorizontalCenter; + } + + set isAbsoluteHorizontalCenter (value) { + this._isAbsHorizontalCenter = value; + } + + /** + * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin. + * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 + * @property isAbsoluteVerticalCenter + * @type {Boolean} + * @default true + */ + @property + get isAbsoluteVerticalCenter () { + return this._isAbsVerticalCenter; + } + set isAbsoluteVerticalCenter (value) { + this._isAbsVerticalCenter = value; + } + + public static AlignMode = AlignMode; + /** + * !#zh: 对齐开关,由 AlignFlags 组成 + * + * @property _alignFlags + * @type {Number} + * @default 0 + * @private + */ + private _alignFlags = 0; + private _wasAlignOnce = false; + @property + private _target: Node | null = null; + @property + private _left = 0; + @property + private _right = 0; + @property + private _top = 0; + @property + private _bottom = 0; + @property + private _horizontalCenter = 0; + @property + private _verticalCenter = 0; + @property + private _isAbsLeft = true; + @property + private _isAbsRight = true; + @property + private _isAbsTop = true; + @property + private _isAbsBottom = true; + @property + private _isAbsHorizontalCenter = true; + @property + private _isAbsVerticalCenter = true; + // original size before align + @property + private _originalWidth = 0; + @property + private _originalHeight = 0; + @property + private _alignMode = AlignMode.ON_WINDOW_RESIZE; + + /** + * !#en + * Immediately perform the widget alignment. You need to manually call this method only if + * you need to get the latest results after the alignment before the end of current frame. + * !#zh + * 立刻执行 widget 对齐操作。这个接口一般不需要手工调用。 + * 只有当你需要在当前帧结束前获得 widget 对齐后的最新结果时才需要手动调用这个方法。 + * + * @method updateAlignment + * + * @example + * widget.top = 10; // change top margin + * cc.log(widget.node.y); // not yet changed + * widget.updateAlignment(); + * cc.log(widget.node.y); // changed + */ + public updateAlignment () { + widgetManager.updateAlignment(this.node); + } + + protected onLoad () { + // TODO: + // if (this._wasAlignOnce) { + // // migrate for old version + // this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; + // this._wasAlignOnce = false; + // } + if(this._alignMode === AlignMode.ONCE){ + this._wasAlignOnce = true; + } + } + + protected onEnable () { + widgetManager.add(this); + } + + protected onDisable () { + widgetManager.remove(this); + } + + private _setAlign (flag, isAlign) { + const current = (this._alignFlags & flag) > 0; + if (isAlign === current) { + return; + } + const isHorizontal = (flag & LEFT_RIGHT) > 0; + if (isAlign) { + this._alignFlags |= flag; + + if (isHorizontal) { + this.isAlignHorizontalCenter = false; + if (this.isStretchWidth) { + // become stretch + this._originalWidth = this.node.width; + // test check conflict + if (CC_EDITOR && !cc.engine.isPlaying) { + // _Scene.DetectConflict.checkConflict_Widget(this); + } + } + } else { + this.isAlignVerticalCenter = false; + if (this.isStretchHeight) { + // become stretch + this._originalHeight = this.node.height; + // test check conflict + if (CC_EDITOR && !cc.engine.isPlaying) { + // _Scene.DetectConflict.checkConflict_Widget(this); + } + } + } + + 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); + } + } else { + if (isHorizontal) { + if (this.isStretchWidth) { + // will cancel stretch + this.node.width = this._originalWidth; + } + } else { + if (this.isStretchHeight) { + // will cancel stretch + this.node.height = this._originalHeight; + } + } + + this._alignFlags &= ~flag; + } + } +} + +/** + * !#en + * When turned on, it will only be aligned once at the end of the onEnable frame, + * then immediately disables the current component. + * This will allow the script or animation to continue controlling the current node. + * Note: It will still be aligned at the frame when onEnable is called. + * !#zh + * 开启后仅会在 onEnable 的当帧结束时对齐一次,然后立刻禁用当前组件。 + * 这样便于脚本或动画继续控制当前节点。 + * 注意:onEnable 时所在的那一帧仍然会进行对齐。 + * @property {Boolean} isAlignOnce + * @default false + * @deprecated + */ +// Object.defineProperty(Widget.prototype, 'isAlignOnce', { +// get() { +// if (CC_DEBUG) { +// cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode === cc.Widget.AlignMode.ONCE` instead please.'); +// } +// return this.alignMode === AlignMode.ONCE; +// } +// set(value) { +// if (CC_DEBUG) { +// cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode = cc.Widget.AlignMode.*` instead please.'); +// } +// this.alignMode = value ? AlignMode.ONCE : AlignMode.ALWAYS; +// } +// }); + +// cc.Widget = module.exports = Widget; diff --git a/cocos/3d/ui/index.ts b/cocos/3d/ui/index.ts new file mode 100644 index 0000000000..9ff479d8fc --- /dev/null +++ b/cocos/3d/ui/index.ts @@ -0,0 +1,37 @@ + +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'; + +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; + diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/3d/ui/mesh-buffer.ts new file mode 100644 index 0000000000..35e439bfc0 --- /dev/null +++ b/cocos/3d/ui/mesh-buffer.ts @@ -0,0 +1,246 @@ +// import gfx from '../gfx/index'; +// import VertexFormat from '../gfx/vertex-format'; +// import { UI } from './ui'; +// import { GFXDevice } from '../../gfx/device'; +// import { GFXBuffer } from '../../gfx/buffer'; +import { GFXFormat, GFXPrimitiveMode } from '../../gfx/define'; +import { IGFXInputAttribute } from '../../gfx/input-assembler'; +// import UISystem from '../UISystem'; + +export interface IMeshBufferInitData { + vertexCount: number; + indiceCount: number; + attributes: IGFXInputAttribute[]; +} + +export class MeshBuffer { + public byteStart: number = 0; + public byteOffset: number = 0; + public indiceStart: number = 0; + public indiceOffset: number = 0; + public vertexStart: number = 0; + public vertexOffset: number = 0; + // public _vb: GFXBuffer | null = null; + // public _ib: GFXBuffer | null = null; + public vData: Float32Array | null = null; + public iData: Uint16Array | null = null; + // public uintVData: Uint32Array | null = null; + public primitiveMode: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + + private _vertexBytes: number = 0; + private _vertexFormat: IGFXInputAttribute[] = []; + // private _renderer: UI|null = null; + + private _initVDataCount: number = 0; // actually 256 * 4 * (vertexFormat._bytes / 4) + private _initIDataCount: number = 0; + private _dirty: boolean = false; + + constructor (/*device: GFXDevice*/) { + + // const device = cc.game._renderContext; + // this._vertexFormat = vertexFormat; + + // TODO: calculate + // this._vertexBytes = this.calculateBytes(vertexFormat)/*this._vertexFormat._bytes*/; + // this._vb = new gfx.VertexBuffer( + // device, + // vertexFormat, + // gfx.USAGE_DYNAMIC, + // new ArrayBuffer(0), + // 0, + // ); + // this._vb = device.createBuffer({ + // usage: GFXBufferUsageBit.VERTEX, + // memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + // size: 0, + // stride: 0, + // }); + // this._ib = new gfx.IndexBuffer( + // device, + // gfx.INDEX_FMT_UINT16, + // gfx.USAGE_STATIC, + // new ArrayBuffer(0), + // 0, + // ); + + // this._ib = device.createBuffer({ + // usage: GFXBufferUsageBit.INDEX, + // memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + // size: 0, + // stride: 2, + // }); + // this._renderer = renderer; + // this._initVDataCount = 256 * this._vertexBytes; + // this._reallocBuffer(); + } + + public initialize (data: IMeshBufferInitData) { + this._vertexFormat = data.attributes; + this._vertexBytes = this.calculateBytes(this._vertexFormat); + this._initVDataCount = data.vertexCount * this._vertexBytes; + this._initIDataCount = data.indiceCount; + this.primitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + this.byteOffset = 0; + this.byteStart = 0; + this.indiceStart = 0; + this.indiceOffset = 0; + this.vertexStart = 0; + this.vertexOffset = 0; + this._reallocBuffer(); + } + + public uploadData () { + if (this.byteOffset === 0 || !this._dirty) { + return; + } + + // update vertext data + // const vertexsData = new Float32Array(this.vData!.buffer, 0, this.byteOffset >> 2); + // const indicesData = new Uint16Array(this.iData!.buffer, 0, this.indiceOffset); + + // const vb = this._vb; + // vb.update(0, vertexsData); + + // const ib = this._ib; + // ib.update(0, indicesData); + + this._dirty = false; + } + + public requestStatic (vertexCount, indiceCount) { + const byteOffset = this.byteOffset + vertexCount * this._vertexBytes; + const indiceOffset = this.indiceOffset + indiceCount; + + let byteLength = this.vData!.byteLength; + let indiceLength = this.iData!.length; + if (byteOffset > byteLength || indiceOffset > indiceLength) { + while (byteLength < byteOffset || indiceLength < indiceOffset) { + this._initVDataCount *= 2; + this._initIDataCount *= 2; + + byteLength = this._initVDataCount * 4; + indiceLength = this._initIDataCount; + } + + this._reallocBuffer(); + } + + this.vertexOffset += vertexCount; + this.indiceOffset += indiceCount; + + this.byteOffset = byteOffset; + + this._dirty = true; + } + + public request (vertexCount, indiceCount) { + // There used to be two buffer, quad and mesh, now together. + // if (this._renderer!.buffer !== this) { + // this._renderer!.flush(); + // this._renderer!.buffer = this; + // } + + this.requestStatic(vertexCount, indiceCount); + } + + public _reallocBuffer () { + this._reallocVData(true); + this._reallocIData(true); + } + + public _reallocVData (copyOldData) { + // let oldVData; + // if (this.vData) { + // if (this._initVDataCount * 4 > this.vData.byteLength){ + // oldVData = new Uint8Array(this.vData.buffer); + // } + // } + + if (this.vData && this.vData.byteLength === this._initVDataCount) { + return; + } + + this.vData = new Float32Array(this._initVDataCount); + // this.uintVData = new Uint32Array(this.vData.buffer); + // const newData = new Uint8Array(this.vData.buffer); + + // if (oldVData && copyOldData) { + // for (let i = 0, l = oldVData.length; i < l; i++) { + // newData[i] = oldVData[i]; + // } + // } + + // this._vb._bytes = this.vData.byteLength; + } + + public _reallocIData (copyOldData) { + // const oldIData = this.iData; + + if (this.iData && this.iData.byteLength === this._initIDataCount) { + return; + } + + this.iData = new Uint16Array(this._initIDataCount); + + // if (oldIData && copyOldData) { + // const iData = this.iData; + // for (let i = 0, l = oldIData.length; i < l; i++) { + // iData[i] = oldIData[i]; + // } + // } + + // this._ib._bytes = this.iData.byteLength; + } + + public reset () { + this.byteStart = 0; + this.byteOffset = 0; + this.indiceStart = 0; + this.indiceOffset = 0; + this.vertexStart = 0; + this.vertexOffset = 0; + this._dirty = false; + } + + public destroy () { + // this._ib.destroy(); + // this._vb.destroy(); + } + + private calculateBytes (vertexFormat: IGFXInputAttribute[]) { + let bytes = 0; + let num = 0; + for (const attr of vertexFormat) { + let name = GFXFormat[attr.format].toString(); + if (name.startsWith('RGBA')) { + num = 4; + } else if (name.startsWith('RGB')) { + num = 3; + } else if (name.startsWith('RG')) { + num = 2; + } else { + num = 1; + } + + name = name.substring(num); + switch (name) { + case '8I': + case '8UI': + bytes += num * 1; + break; + case '16I': + case '16UI': + bytes += num * 2; + break; + case '32I': + case '32UI': + case '32F': + bytes += num * 4; + break; + } + } + + return bytes; + } +} +cc.MeshBuffer = MeshBuffer; diff --git a/cocos/animation/CCAnimation.js b/cocos/animation/CCAnimation.js index 587ed549d5..6314d5d338 100644 --- a/cocos/animation/CCAnimation.js +++ b/cocos/animation/CCAnimation.js @@ -62,7 +62,7 @@ var EventType = cc.Enum({ /** * !#en Emit when pause animation * !#zh 暂停播放时触发 - * @property {String} PAUSE + * @property {String} PAUSE * @static */ PAUSE: 'pause', @@ -91,7 +91,7 @@ var EventType = cc.Enum({ /** * !#en The animation component is used to play back animations. - * + * * Animation provide several events to register: * - play : Emit when begin playing animation * - stop : Emit when stop playing animation @@ -101,7 +101,7 @@ var EventType = cc.Enum({ * - finished : Emit when finish playing animation * * !#zh Animation 组件用于播放动画。 - * + * * Animation 提供了一系列可注册的事件: * - play : 开始播放时 * - stop : 停止播放时 @@ -109,14 +109,14 @@ var EventType = cc.Enum({ * - resume : 恢复播放时 * - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时 * - finished : 动画播放完成时 - * + * * @class Animation * @extends Component * @uses EventTarget */ var Animation = cc.Class({ name: 'cc.Animation', - extends: require('./CCComponent'), + extends: require('./component'), mixins: [EventTarget], editor: CC_EDITOR && { @@ -305,7 +305,7 @@ var Animation = cc.Class({ if (state) { this.enabled = true; - + var animator = this._animator; if (animator.isPlaying && state.isPlaying) { if (state.isPaused) { @@ -488,7 +488,7 @@ var Animation = cc.Class({ }, /** - * !#en + * !#en * Remove clip from the animation list. This will remove the clip and any animation states based on it. * If there are animation states depand on the clip are playing or clip is defaultClip, it will not delete the clip. * But if force is true, then will always remove the clip and any animation states based on it. If clip is defaultClip, defaultClip will be reset to null @@ -521,7 +521,7 @@ var Animation = cc.Class({ else { if (!CC_TEST) cc.warnID(3902); return; - } + } } if (state && state.isPlaying) { @@ -537,7 +537,7 @@ var Animation = cc.Class({ }); if (state) { - delete this._nameToState[state.name]; + delete this._nameToState[state.name]; } }, @@ -565,7 +565,7 @@ var Animation = cc.Class({ /** - * !#en + * !#en * Register animation event callback. * The event arguments will provide the AnimationState which emit the event. * When play an animation, will auto register the event callback to the AnimationState, and unregister the event callback from the AnimationState when animation stopped. @@ -577,7 +577,7 @@ var Animation = cc.Class({ * @param {String} type - A string representing the event type to listen for. * @param {Function} callback - The callback that will be invoked when the event is dispatched. * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {cc.AnimationState} state + * @param {cc.AnimationState} state * @param {Object} [target] - The target (this object) to invoke the callback, can be null * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. @@ -592,7 +592,7 @@ var Animation = cc.Class({ * onPlay: function (type, state) { * // callback * } - * + * * // register event to all animation * animation.on('play', this.onPlay, this); */ @@ -658,7 +658,7 @@ var Animation = cc.Class({ _createStates: function() { this._nameToState = js.createMap(true); - + // create animation states var state = null; var defaultClipState = false; diff --git a/cocos/assets/CCAssetLibrary.js b/cocos/assets/CCAssetLibrary.js index bfdf1d27a2..fb6020b08a 100644 --- a/cocos/assets/CCAssetLibrary.js +++ b/cocos/assets/CCAssetLibrary.js @@ -25,7 +25,7 @@ ****************************************************************************/ import {createMap, isChildClassOf, _getClassById} from '../core/utils/js'; -import Asset from './CCAsset'; +import { Asset } from './asset'; import {callInNextTick} from '../core/utils/misc'; import decodeUuid from '../core/utils/decode-uuid'; import Loader from '../load-pipeline/CCLoader'; @@ -348,11 +348,11 @@ let AssetLibrary = { _uuidToRawAsset[uuid] = new RawAssetEntry(mountPoint + '/' + url, type); // init resources var isSubAsset = info[2] === 1; - + if (!assetTables[mountPoint]) { assetTables[mountPoint] = new AssetTable(); - } - + } + assetTables[mountPoint].add(url, uuid, type, !isSubAsset); } } diff --git a/cocos/assets/CCFont.js b/cocos/assets/CCFont.js index 3c0cb6e939..37dcfe23e6 100644 --- a/cocos/assets/CCFont.js +++ b/cocos/assets/CCFont.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass} from '../core/data/class-decorator'; /** diff --git a/cocos/assets/CCGLTFAsset.js b/cocos/assets/CCGLTFAsset.js index 4e8c114118..b44718a902 100644 --- a/cocos/assets/CCGLTFAsset.js +++ b/cocos/assets/CCGLTFAsset.js @@ -26,7 +26,7 @@ import { _decorator } from "../core/data/index"; const { ccclass, property } = _decorator; import BufferAsset from "./CCBufferAsset"; -import Asset from "./CCAsset"; +import { Asset } from "./asset"; /** * @typedef {import("../../../types/glTF/glTF").GlTf} GlTf @@ -37,7 +37,7 @@ import Asset from "./CCAsset"; * Class for GLTF file. * * !#zh - * GLTF 资源类。
+ * GLTF 资溝类。
* * @class GLTFAsset * @extends Asset @@ -80,4 +80,4 @@ export default class GLTFAsset extends Asset { } } -cc.GLTFAsset = GLTFAsset; \ No newline at end of file +cc.GLTFAsset = GLTFAsset; diff --git a/cocos/assets/CCJsonAsset.js b/cocos/assets/CCJsonAsset.js index 9ace3831ed..07185e57a9 100644 --- a/cocos/assets/CCJsonAsset.js +++ b/cocos/assets/CCJsonAsset.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** diff --git a/cocos/assets/CCPrefab.js b/cocos/assets/CCPrefab.js index 08083bfca1..c53d4c4b79 100644 --- a/cocos/assets/CCPrefab.js +++ b/cocos/assets/CCPrefab.js @@ -27,7 +27,7 @@ import {compile} from '../core/data/instantiate-jit'; import Enum from '../core/value-types/enum'; import {obsolete} from '../core/utils/js'; -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -203,4 +203,4 @@ export default class Prefab extends Asset { } cc.Prefab = Prefab; -obsolete(cc, 'cc._Prefab', 'Prefab'); \ No newline at end of file +obsolete(cc, 'cc._Prefab', 'Prefab'); diff --git a/cocos/assets/CCSceneAsset.js b/cocos/assets/CCSceneAsset.js index 1058ad9092..dd948ec349 100644 --- a/cocos/assets/CCSceneAsset.js +++ b/cocos/assets/CCSceneAsset.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -60,4 +60,4 @@ export default class SceneAsset extends Asset { //} } -cc.SceneAsset = SceneAsset; \ No newline at end of file +cc.SceneAsset = SceneAsset; diff --git a/cocos/assets/CCScripts.js b/cocos/assets/CCScripts.js index aca55d426f..9a1bf850db 100644 --- a/cocos/assets/CCScripts.js +++ b/cocos/assets/CCScripts.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass} from '../core/data/class-decorator'; /** @@ -36,7 +36,7 @@ import {ccclass} from '../core/data/class-decorator'; * @private */ @ccclass('cc.Script') -class Script extends Asset { +export class Script extends Asset { } cc._Script = Script; @@ -62,4 +62,4 @@ cc._JavaScript = JavaScript; @ccclass('cc.TypeScript') export class TypeScript extends Script { } -cc._TypeScript = TypeScript; \ No newline at end of file +cc._TypeScript = TypeScript; diff --git a/cocos/assets/CCSpriteAtlas.js b/cocos/assets/CCSpriteAtlas.js index 85667e295f..e8ed5d5220 100644 --- a/cocos/assets/CCSpriteAtlas.js +++ b/cocos/assets/CCSpriteAtlas.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -64,7 +64,7 @@ export default class SpriteAtlas extends Asset { let sf = this._spriteFrames[key]; if (!sf) { return null; - } + } if (!sf.name) { sf.name = key; } @@ -88,4 +88,4 @@ export default class SpriteAtlas extends Asset { } } -cc.SpriteAtlas = SpriteAtlas; \ No newline at end of file +cc.SpriteAtlas = SpriteAtlas; diff --git a/cocos/assets/CCSpriteFrame.js b/cocos/assets/CCSpriteFrame.ts similarity index 51% rename from cocos/assets/CCSpriteFrame.js rename to cocos/assets/CCSpriteFrame.ts index 6d28070663..2000d6a05c 100644 --- a/cocos/assets/CCSpriteFrame.js +++ b/cocos/assets/CCSpriteFrame.ts @@ -25,19 +25,37 @@ THE SOFTWARE. ****************************************************************************/ +import { ccclass, property } from '../core/data/class-decorator'; import EventTarget from '../core/event/event-target'; +import { addon } from '../core/utils/js'; +import Rect, { rect } from '../core/value-types/rect'; +import Size, { size } from '../core/value-types/size'; +import Vec2, { v2 } from '../core/value-types/vec2'; +import { Asset } from './asset'; +import { Texture2D } from './texture-2d'; import textureUtil from './texture-util'; -import {addon} from '../core/utils/js'; -import Asset from './CCAsset'; -import {ccclass, property} from '../core/data/class-decorator'; - const INSET_LEFT = 0; const INSET_TOP = 1; const INSET_RIGHT = 2; const INSET_BOTTOM = 3; -let temp_uvs = [{u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}]; +export interface IUV { + u: number; + v: number; +} + +interface IVertices { + x: any; + y: any; + triangles: any; + nu: number[]; + u: number[]; + nv: number[]; + v: number[]; +} + +const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }]; /** * !#en @@ -65,22 +83,22 @@ let temp_uvs = [{u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}]; * }); */ @ccclass('cc.SpriteFrame') -export default class SpriteFrame extends Asset { +export class SpriteFrame extends Texture2D { // Use this property to set texture when loading dependency - @property - set _textureSetter (texture) { - if (texture) { - if (CC_EDITOR && !(texture instanceof cc.Texture2D)) { - // just building - this._texture = texture; - return; - } - if (this._texture !== texture) { - this._refreshTexture(texture); - } - this._textureFilename = texture.url; - } - } + // @property + // set _textureSetter(texture) { + // if (texture) { + // if (CC_EDITOR && !(texture instanceof cc.Texture2D)) { + // // just building + // this._texture = texture; + // return; + // } + // if (this._texture !== texture) { + // this._refreshTexture(texture); + // } + // this._textureFilename = texture.url; + // } + // } // _textureFilename: { // get () { @@ -104,9 +122,9 @@ export default class SpriteFrame extends Asset { } set insetTop (value) { this._capInsets[INSET_TOP] = value; - if (this._texture) { - this._calculateSlicedUV(); - } + // if (this._texture) { + this._calculateSlicedUV(); + // } } /** @@ -121,9 +139,9 @@ export default class SpriteFrame extends Asset { } set insetBottom (value) { this._capInsets[INSET_BOTTOM] = value; - if (this._texture) { - this._calculateSlicedUV(); - } + // if (this._texture) { + this._calculateSlicedUV(); + // } } /** @@ -138,9 +156,9 @@ export default class SpriteFrame extends Asset { } set insetLeft (value) { this._capInsets[INSET_LEFT] = value; - if (this._texture) { - this._calculateSlicedUV(); - } + // if (this._texture) { + this._calculateSlicedUV(); + // } } /** @@ -155,11 +173,39 @@ export default class SpriteFrame extends Asset { } set insetRight (value) { this._capInsets[INSET_RIGHT] = value; - if (this._texture) { - this._calculateSlicedUV(); - } + // if (this._texture) { + this._calculateSlicedUV(); + // } } + get atlasUuid () { + return this._atlasUuid; + } + + public vertices: IVertices | null = null; + + public uv: number[] = []; + + public uvSliced: IUV[] = []; + + // the location of the sprite on rendering texture + private _rect = new Rect(); + + // for trimming + private _offset = new Vec2(); + + // for trimming + private _originalSize = new Size(); + + private _rotated = false; + + private _capInsets = [0, 0, 0, 0]; + + // store original info before packed to dynamic atlas + private _original = null; + + private _atlasUuid?: string; + /** * !#en * Constructor of SpriteFrame class. @@ -177,121 +223,86 @@ export default class SpriteFrame extends Asset { // Init EventTarget data EventTarget.call(this); - let filename = arguments[0]; - let rect = arguments[1]; - let rotated = arguments[2]; - let offset = arguments[3]; - let originalSize = arguments[4]; + // let filename = arguments[0]; + const rect = arguments[0]; + const rotated = arguments[1]; + const offset = arguments[2]; + const originalSize = arguments[3]; - // the location of the sprite on rendering texture - this._rect = null; + // this._texture = null; + // this._textureFilename = ''; - // for trimming - this._offset = null; - - // for trimming - this._originalSize = null; - - this._rotated = false; - - this.vertices = null; - - this._capInsets = [0, 0, 0, 0]; - - this.uv = []; - this.uvSliced = []; - - this._texture = null; - this._textureFilename = ''; - - // store original info before packed to dynamic atlas - this._original = null; + this._capInsets[INSET_BOTTOM] = 0; + this._capInsets[INSET_LEFT] = 0; + this._capInsets[INSET_RIGHT] = 0; + this._capInsets[INSET_TOP] = 0; if (CC_EDITOR) { // Atlas asset uuid this._atlasUuid = ''; } - - if (filename !== undefined) { - this.setTexture(filename, rect, rotated, offset, originalSize); - } else { - //todo log Error - } + // if (filename !== undefined) { + // this.setTexture(filename, rect, rotated, offset, originalSize); + // } else { + // //todo log Error + // } } /** * !#en Returns whether the texture have been loaded * !#zh 返回是否已加载纹理 - * @method textureLoaded - * @returns {boolean} */ - textureLoaded () { - return this._texture && this._texture.loaded; + public textureLoaded () { + return this.loaded; } /** * !#en Returns whether the sprite frame is rotated in the texture. * !#zh 获取 SpriteFrame 是否旋转 - * @method isRotated - * @return {Boolean} */ - isRotated () { + public isRotated () { return this._rotated; } /** * !#en Set whether the sprite frame is rotated in the texture. * !#zh 设置 SpriteFrame 是否旋转 - * @method setRotated - * @param {Boolean} bRotated + * @param value */ - setRotated (bRotated) { - this._rotated = bRotated; + public setRotated (rotated: boolean) { + this._rotated = rotated; } /** * !#en Returns the rect of the sprite frame in the texture. * !#zh 获取 SpriteFrame 的纹理矩形区域 - * @method getRect - * @return {Rect} */ - getRect () { - return cc.rect(this._rect); + public getRect () { + return rect(this._rect); } /** * !#en Sets the rect of the sprite frame in the texture. * !#zh 设置 SpriteFrame 的纹理矩形区域 - * @method setRect - * @param {Rect} rect */ - setRect (rect) { + public setRect (rect: Rect) { this._rect = rect; } /** * !#en Returns the original size of the trimmed image. * !#zh 获取修剪前的原始大小 - * @method getOriginalSize - * @return {Size} */ - getOriginalSize () { - return cc.size(this._originalSize); + public getOriginalSize () { + return size(this._originalSize); } /** * !#en Sets the original size of the trimmed image. * !#zh 设置修剪前的原始大小 - * @method setOriginalSize - * @param {Size} size */ - setOriginalSize (size) { - if (!this._originalSize) { - this._originalSize = cc.size(size); - } else { - this._originalSize.width = size.width; - this._originalSize.height = size.height; - } + public setOriginalSize (size: Size) { + this._originalSize.set(size); } /** @@ -300,32 +311,35 @@ export default class SpriteFrame extends Asset { * @method getTexture * @return {Texture2D} */ - getTexture () { - return this._texture; - } + // getTexture() { + // return this._texture; + // } - _textureLoadedCallback () { - let self = this; - let texture = this._texture; - if (!texture) { - // clearTexture called while loading texture... - return; - } - let w = texture.width, h = texture.height; + public _textureLoadedCallback () { + const self = this; + // let texture = this._texture; + // if (!texture) { + // // clearTexture called while loading texture... + // return; + // } + // let w = texture.width, h = texture.height; + let w = self.width; + let h = self.height; if (self._rotated && cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { // TODO: rotate texture for canvas // self._texture = _ccsg.Sprite.CanvasRenderCmd._createRotatedTexture(texture, self.getRect()); self._rotated = false; - w = self._texture.width; - h = self._texture.height; + // w = self._texture.width; + // h = self._texture.height; + w = self.width; + h = self.height; self.setRect(cc.rect(0, 0, w, h)); } if (self._rect) { - self._checkRect(self._texture); - } - else { + self._checkRect(/*self._texture*/); + } else { self.setRect(cc.rect(0, 0, w, h)); } @@ -340,7 +354,8 @@ export default class SpriteFrame extends Asset { self._calculateUV(); // dispatch 'load' event of cc.SpriteFrame - self.emit("load"); + // @ts-ignore + self.emit('load'); } /* @@ -349,33 +364,31 @@ export default class SpriteFrame extends Asset { * @method _refreshTexture * @param {Texture2D} texture */ - _refreshTexture (texture) { - this._texture = texture; - if (texture.loaded) { - this._textureLoadedCallback(); - } - else { - texture.once('load', this._textureLoadedCallback, this); - } - } + // _refreshTexture(/*texture*/) { + // // this._texture = texture; + // if (/*texture.loaded*/this.loaded) { + // this._textureLoadedCallback(); + // } + // else { + // // texture.once('load', this._textureLoadedCallback, this); + // this.once('load', this._textureLoadedCallback, this); + // } + // } /** * !#en Returns the offset of the frame in the texture. * !#zh 获取偏移量 - * @method getOffset - * @return {Vec2} */ - getOffset () { - return cc.v2(this._offset); + public getOffset () { + return v2(this._offset); } /** * !#en Sets the offset of the frame in the texture. * !#zh 设置偏移量 - * @method setOffset - * @param {Vec2} offsets + * @param offsets */ - setOffset (offsets) { + public setOffset (offsets: Vec2) { this._offset = cc.v2(offsets); } @@ -385,64 +398,71 @@ export default class SpriteFrame extends Asset { * @method clone * @return {SpriteFrame} */ - clone () { - return new SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize); - } + // TODO + // clone() { + // let cloneSprite = new SpriteFrame(/*this._texture || this._textureFilename,*/ this._rect, this._rotated, this._offset, this._originalSize); + // cloneSprite.setWrapMode(this._wrapS, this._wrapT); + // cloneSprite.setFilters(this._minFilter, this._magFilter); + // cloneSprite.setPremultiplyAlpha(this._premultiplyAlpha); + // cloneSprite.setAnisotropy(this._anisotropy); + // cloneSprite._mipmaps = this._mipmaps; + // return cloneSprite; + // } - /** - * !#en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.
- * !#zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame。 - * @method setTexture - * @param {String|Texture2D} textureOrTextureFile - * @param {Rect} [rect=null] - * @param {Boolean} [rotated=false] - * @param {Vec2} [offset=cc.v2(0,0)] - * @param {Size} [originalSize=rect.size] - * @return {Boolean} - */ - setTexture (textureOrTextureFile, rect, rotated, offset, originalSize) { - if (rect) { - this.setRect(rect); - } - else { - this._rect = null; - } + // /** + // * !#en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.
+ // * !#zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame。 + // * @method setTexture + // * @param {String|Texture2D} textureOrTextureFile + // * @param {Rect} [rect=null] + // * @param {Boolean} [rotated=false] + // * @param {Vec2} [offset=cc.v2(0,0)] + // * @param {Size} [originalSize=rect.size] + // * @return {Boolean} + // */ + // setTexture(textureOrTextureFile, rect, rotated, offset, originalSize) { + // if (rect) { + // this.setRect(rect); + // } + // else { + // this._rect = null; + // } - if (offset) { - this.setOffset(offset); - } - else { - this._offset = null; - } + // if (offset) { + // this.setOffset(offset); + // } + // else { + // this._offset = null; + // } - if (originalSize) { - this.setOriginalSize(originalSize); - } - else { - this._originalSize = null; - } + // if (originalSize) { + // this.setOriginalSize(originalSize); + // } + // else { + // this._originalSize = null; + // } - this._rotated = rotated || false; + // this._rotated = rotated || false; - // loading texture - let texture = textureOrTextureFile; - if (typeof texture === 'string' && texture) { - this._textureFilename = texture; - this._loadTexture(); - } - if (texture instanceof cc.Texture2D && this._texture !== texture) { - this._refreshTexture(texture); - } + // // loading texture + // let texture = textureOrTextureFile; + // if (typeof texture === 'string' && texture) { + // this._textureFilename = texture; + // this._loadTexture(); + // } + // if (texture instanceof cc.Texture2D && this._texture !== texture) { + // this._refreshTexture(texture); + // } - return true; - } + // return true; + // } - _loadTexture () { - if (this._textureFilename) { - let texture = textureUtil.loadImage(this._textureFilename); - this._refreshTexture(texture); - } - } + // _loadTexture() { + // if (this._textureFilename) { + // let texture = textureUtil.loadImage(this._textureFilename); + // this._refreshTexture(texture); + // } + // } /** * !#en If a loading scene (or prefab) is marked as `asyncLoadAssets`, all the textures of the SpriteFrame which @@ -462,68 +482,77 @@ export default class SpriteFrame extends Asset { * spriteFrame.ensureLoadTexture(); * } */ - ensureLoadTexture () { - if (this._texture) { - if (!this._texture.loaded) { - // load exists texture - this._refreshTexture(this._texture); - textureUtil.postLoadTexture(this._texture); - } - } - else if (this._textureFilename) { - // load new texture - this._loadTexture(); + public ensureLoadTexture () { + // if (this._texture) { + // if (!this._texture.loaded) { + if (!this.loaded) { + // load exists texture + // this._refreshTexture(/*this._texture*/); + textureUtil.postLoadTexture(/*this._texture*/this); } + // } + // else if (this._textureFilename) { + // // load new texture + // this._loadTexture(); + // } } - /** - * !#en - * If you do not need to use the SpriteFrame temporarily, you can call this method so that its texture could be garbage collected. Then when you need to render the SpriteFrame, you should call `ensureLoadTexture` manually to reload texture. - * !#zh - * 当你暂时不再使用这个 SpriteFrame 时,可以调用这个方法来保证引用的贴图对象能被 GC。然后当你要渲染 SpriteFrame 时,你需要手动调用 `ensureLoadTexture` 来重新加载贴图。 - * - * @method clearTexture - * @example - * spriteFrame.clearTexture(); - * // when you need the SpriteFrame again... - * spriteFrame.once('load', onSpriteFrameLoaded); - * spriteFrame.ensureLoadTexture(); - */ - clearTexture () { - this._texture = null; // TODO - release texture - } + // /** + // * !#en + // * If you do not need to use the SpriteFrame temporarily, you can call this method so that its texture could be garbage collected. Then when you need to render the SpriteFrame, you should call `ensureLoadTexture` manually to reload texture. + // * !#zh + // * 当你暂时不再使用这个 SpriteFrame 时,可以调用这个方法来保证引用的贴图对象能被 GC。然后当你要渲染 SpriteFrame 时,你需要手动调用 `ensureLoadTexture` 来重新加载贴图。 + // * + // * @method clearTexture + // * @example + // * spriteFrame.clearTexture(); + // * // when you need the SpriteFrame again... + // * spriteFrame.once('load', onSpriteFrameLoaded); + // * spriteFrame.ensureLoadTexture(); + // */ + // clearTexture() { + // this._texture = null; // TODO - release texture + // } - _checkRect (texture) { - let rect = this._rect; - let maxX = rect.x, maxY = rect.y; + public _checkRect (/*texture*/) { + const rect = this._rect; + let maxX = rect.x; + let maxY = rect.y; if (this._rotated) { maxX += rect.height; maxY += rect.width; - } - else { + } else { maxX += rect.width; maxY += rect.height; } - if (maxX > texture.width) { - cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width); + // if (maxX > texture.width) { + // cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width); + // } + // if (maxY > texture.height) { + // cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height); + // } + if (maxX > this._originalSize.width) { + cc.errorID(3300, /*this.url*/ + '/' + this.name, maxX, this._originalSize.width); } - if (maxY > texture.height) { - cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height); + if (maxY > this._originalSize.height) { + cc.errorID(3400, /*this.url +*/ '/' + this.name, maxY, this._originalSize.height); } } - _calculateSlicedUV () { - let rect = this._rect; - let atlasWidth = this._texture.width; - let atlasHeight = this._texture.height; - let leftWidth = this._capInsets[INSET_LEFT]; - let rightWidth = this._capInsets[INSET_RIGHT]; - let centerWidth = rect.width - leftWidth - rightWidth; - let topHeight = this._capInsets[INSET_TOP]; - let bottomHeight = this._capInsets[INSET_BOTTOM]; - let centerHeight = rect.height - topHeight - bottomHeight; + public _calculateSlicedUV () { + const rect = this._rect; + // let atlasWidth = this._texture.width; + // let atlasHeight = this._texture.height; + const atlasWidth = this._originalSize.width; + const atlasHeight = this._originalSize.height; + const leftWidth = this._capInsets[INSET_LEFT]; + const rightWidth = this._capInsets[INSET_RIGHT]; + const centerWidth = rect.width - leftWidth - rightWidth; + const topHeight = this._capInsets[INSET_TOP]; + const bottomHeight = this._capInsets[INSET_BOTTOM]; + const centerHeight = rect.height - topHeight - bottomHeight; - let uvSliced = this.uvSliced; + const uvSliced = this.uvSliced; uvSliced.length = 0; if (this._rotated) { temp_uvs[0].u = (rect.x) / atlasWidth; @@ -536,17 +565,16 @@ export default class SpriteFrame extends Asset { temp_uvs[0].v = (rect.y + rect.width) / atlasHeight; for (let row = 0; row < 4; ++row) { - let rowD = temp_uvs[row]; + const rowD = temp_uvs[row]; for (let col = 0; col < 4; ++col) { - let colD = temp_uvs[3 - col]; + const colD = temp_uvs[3 - col]; uvSliced.push({ u: rowD.u, - v: colD.v + v: colD.v, }); } } - } - else { + } else { temp_uvs[0].u = (rect.x) / atlasWidth; temp_uvs[1].u = (rect.x + leftWidth) / atlasWidth; temp_uvs[2].u = (rect.x + leftWidth + centerWidth) / atlasWidth; @@ -557,30 +585,32 @@ export default class SpriteFrame extends Asset { temp_uvs[0].v = (rect.y + rect.height) / atlasHeight; for (let row = 0; row < 4; ++row) { - let rowD = temp_uvs[row]; + const rowD = temp_uvs[row]; for (let col = 0; col < 4; ++col) { - let colD = temp_uvs[col]; + const colD = temp_uvs[col]; uvSliced.push({ u: colD.u, - v: rowD.v + v: rowD.v, }); } } } } - _calculateUV () { - let rect = this._rect, - texture = this._texture, - uv = this.uv, - texw = texture.width, - texh = texture.height; + public _calculateUV () { + const rect = this._rect; + // texture = this._texture, + const uv = this.uv; + // texw = texture.width, + // texh = texture.height; + const texw = this._originalSize.width; + const texh = this._originalSize.height; if (this._rotated) { - let l = texw === 0 ? 0 : rect.x / texw; - let r = texw === 0 ? 0 : (rect.x + rect.height) / texw; - let b = texh === 0 ? 0 : (rect.y + rect.width) / texh; - let t = texh === 0 ? 0 : rect.y / texh; + const l = texw === 0 ? 0 : rect.x / texw; + const r = texw === 0 ? 0 : (rect.x + rect.height) / texw; + const b = texh === 0 ? 0 : (rect.y + rect.width) / texh; + const t = texh === 0 ? 0 : rect.y / texh; uv[0] = l; uv[1] = t; uv[2] = l; @@ -589,12 +619,11 @@ export default class SpriteFrame extends Asset { uv[5] = t; uv[6] = r; uv[7] = b; - } - else { - let l = texw === 0 ? 0 : rect.x / texw; - let r = texw === 0 ? 0 : (rect.x + rect.width) / texw; - let b = texh === 0 ? 0 : (rect.y + rect.height) / texh; - let t = texh === 0 ? 0 : rect.y / texh; + } else { + const l = texw === 0 ? 0 : rect.x / texw; + const r = texw === 0 ? 0 : (rect.x + rect.width) / texw; + const b = texh === 0 ? 0 : (rect.y + rect.height) / texh; + const t = texh === 0 ? 0 : rect.y / texh; uv[0] = l; uv[1] = b; uv[2] = r; @@ -605,13 +634,13 @@ export default class SpriteFrame extends Asset { uv[7] = t; } - let vertices = this.vertices; + const vertices = this.vertices; if (vertices) { vertices.nu.length = 0; vertices.nv.length = 0; for (let i = 0; i < vertices.u.length; i++) { - vertices.nu[i] = vertices.u[i]/texw; - vertices.nv[i] = vertices.v[i]/texh; + vertices.nu[i] = vertices.u[i] / texw; + vertices.nv[i] = vertices.v[i] / texh; } } @@ -620,22 +649,26 @@ export default class SpriteFrame extends Asset { // SERIALIZATION - _serialize (exporting) { - let rect = this._rect; - let offset = this._offset; - let size = this._originalSize; - let uuid; - let texture = this._texture; - if (texture) { - uuid = texture._uuid; - } - if (!uuid) { - let url = this._textureFilename; - if (url) { - uuid = Editor.Utils.UuidCache.urlToUuid(url); - } - } + // @ts-ignore + // TODO: + public _serialize (exporting) { + const rect = this._rect; + const offset = this._offset; + const size = this._originalSize; + let uuid = this._uuid; + // let texture = this._texture; + // if (texture) { + // uuid = texture._uuid; + // } + // if (!uuid) { + // let url = this._textureFilename; + // if (url) { + // uuid = Editor.Utils.UuidCache.urlToUuid(url); + // } + // } if (uuid && exporting) { + // @ts-ignore + // TODO: uuid = Editor.Utils.UuidUtils.compressUuid(uuid, true); } @@ -646,11 +679,12 @@ export default class SpriteFrame extends Asset { x: this.vertices.x, y: this.vertices.y, u: this.vertices.u, - v: this.vertices.v + v: this.vertices.v, }; } return { + base: super._serialize(), name: this._name, texture: uuid || undefined, atlas: exporting ? undefined : this._atlasUuid, // strip from json if exporting @@ -659,17 +693,18 @@ export default class SpriteFrame extends Asset { originalSize: size ? [size.width, size.height] : undefined, rotated: this._rotated ? 1 : undefined, capInsets: this._capInsets, - vertices: vertices + vertices, }; } - _deserialize (data, handle) { - let rect = data.rect; + public _deserialize (data, handle) { + super._deserialize(data.base, handle); + const rect = data.rect; if (rect) { - this.setRect(new cc.Rect(rect[0], rect[1], rect[2], rect[3])); + this.setRect(new Rect(rect[0], rect[1], rect[2], rect[3])); } if (data.offset) { - this.setOffset(new cc.Vec2(data.offset[0], data.offset[1])); + this.setOffset(new Vec2(data.offset[0], data.offset[1])); } if (data.originalSize) { this.setOriginalSize(new cc.Size(data.originalSize[0], data.originalSize[1])); @@ -677,7 +712,7 @@ export default class SpriteFrame extends Asset { this._rotated = data.rotated === 1; this._name = data.name; - let capInsets = data.capInsets; + const capInsets = data.capInsets; if (capInsets) { this._capInsets[INSET_LEFT] = capInsets[INSET_LEFT]; this._capInsets[INSET_TOP] = capInsets[INSET_TOP]; @@ -697,19 +732,36 @@ export default class SpriteFrame extends Asset { } // load texture via _textureSetter - let textureUuid = data.texture; - if (textureUuid) { - handle.result.push(this, '_textureSetter', textureUuid); - } + // let textureUuid = data.texture; + // if (textureUuid) { + // handle.result.push(this, '_textureSetter', textureUuid); + // } } + + public onLoaded () { + this.loaded = true; + if (super.onLoaded) { + super.onLoaded(); + } + + this._textureLoadedCallback(); + } + + public copyWithZone (...args: any[]) { + // return this.clone(...args); + } + + public copy (...args: any[]) { + // return this.clone(...args); + } + + // public initWithTexture (...args: any[]) { + // return this.setTexture(...args); + // } } -let proto = SpriteFrame.prototype; - -proto.copyWithZone = proto.clone; -proto.copy = proto.clone; -proto.initWithTexture = proto.setTexture; +const proto = SpriteFrame.prototype; addon(proto, EventTarget.prototype); -cc.SpriteFrame = SpriteFrame; \ No newline at end of file +cc.SpriteFrame = SpriteFrame; diff --git a/cocos/assets/CCTextAsset.js b/cocos/assets/CCTextAsset.js index 904afcdad4..5d99e80bcb 100644 --- a/cocos/assets/CCTextAsset.js +++ b/cocos/assets/CCTextAsset.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -54,4 +54,4 @@ export default class TextAsset extends Asset { } } -cc.TextAsset = TextAsset; \ No newline at end of file +cc.TextAsset = TextAsset; diff --git a/cocos/assets/asset.d.ts b/cocos/assets/asset.d.ts new file mode 100644 index 0000000000..9055813b31 --- /dev/null +++ b/cocos/assets/asset.d.ts @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { RawAsset } from "./raw-asset"; + +export class Asset extends RawAsset { + protected _native: string; + protected loaded: boolean; + + public _nativeAsset: any; + public nativeUrl: string; + + static preventDeferredLoadDependents: boolean; + static preventPreloadNativeObject: boolean; + static deserialize(data: string): object; + + public createNode: (err: string, node: object) => void | null; + public toString(): string; + public serialize(): string; + protected _setRawAsset(filename: string, inLibrary: boolean): void; +} diff --git a/cocos/assets/CCAsset.js b/cocos/assets/asset.js similarity index 98% rename from cocos/assets/CCAsset.js rename to cocos/assets/asset.js index cc051ced5e..050dcdfabc 100644 --- a/cocos/assets/CCAsset.js +++ b/cocos/assets/asset.js @@ -25,7 +25,7 @@ ****************************************************************************/ import { ccclass, property } from '../core/data/class-decorator'; -import RawAsset from './CCRawAsset'; +import { RawAsset } from './raw-asset'; /** * !#en @@ -49,7 +49,7 @@ import RawAsset from './CCRawAsset'; * @extends RawAsset */ @ccclass('cc.Asset') -export default class Asset extends RawAsset { +export class Asset extends RawAsset { constructor () { super(); /** @@ -221,4 +221,4 @@ export default class Asset extends RawAsset { */ Asset.prototype.createNode = null; -cc.Asset = Asset; \ No newline at end of file +cc.Asset = Asset; diff --git a/cocos/assets/image-asset.js b/cocos/assets/image-asset.js deleted file mode 100644 index 9644ebed06..0000000000 --- a/cocos/assets/image-asset.js +++ /dev/null @@ -1,243 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ -//@ts-check -import {ccclass, property} from "../core/data/class-decorator"; -import EventTarget from '../core/event/event-target'; -import {addon} from '../core/utils/js'; - -/** - * @typedef {{ _data: ArrayBufferView, _compressed: boolean, width: number, height: number, format: number}} RawImageData - */ - -const CHAR_CODE_0 = 48; // '0' - -/** - * Class ImageAsset. - */ -@ccclass('cc.ImageAsset') -export default class ImageAsset extends cc.Asset { - - static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc']; - - /** - * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} nativeAsset - */ - constructor(nativeAsset = undefined) { - super(); - EventTarget.call(this); - - /** - * !#en - * The url of the texture, this could be empty if the texture wasn't created via a file. - * !#zh - * 图像文件的 url,当图像不是由文件创建时值可能为空 - * @property url - * @type {String} - * @readonly - */ - // TODO - use nativeUrl directly - this.url = ""; - - /** - * @type {HTMLCanvasElement | HTMLImageElement | RawImageData} - */ - this._nativeData = { - _data: null, - width: 0, - height: 0, - format: 0, - _compressed: false - }; - - if (CC_EDITOR) { - this._exportedExts = null; - } - - if (nativeAsset !== undefined) { - this._nativeAsset = nativeAsset; - } - } - - /** - * @type {HTMLCanvasElement | HTMLImageElement | RawImageData} - */ - @property({ - override: true - }) - get _nativeAsset () { - // maybe returned to pool in webgl - return this._nativeData; - } - - /** - * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} value - */ - set _nativeAsset (value) { - this.reset(value); - } - - /** - * @type {HTMLCanvasElement | HTMLImageElement | ArrayBufferView} - */ - get data() { - return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data; - } - - /** - * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} data - */ - reset(data) { - if (!(data instanceof HTMLElement)) { - this._nativeData = Object.create(data); - this._onDataComplete(); - } else { - this._nativeData = data; - if (CC_WECHATGAME || CC_QQPLAY || data.complete || data instanceof HTMLCanvasElement) { - this._onDataComplete(); - } else { - this.loaded = false; - data.addEventListener('load', () => { - this._onDataComplete(); - }); - data.addEventListener('error', (err) => { - cc.warnID(3119, err.message); - }); - } - } - } - - get width() { - return this._nativeData.width; - } - - get height() { - return this._nativeData.height; - } - - get format() { - if (this._nativeData instanceof HTMLElement) { - return undefined; - } - return this._nativeData.format; - } - - // destroy() { - // if (cc.macro.CLEANUP_IMAGE_CACHE) { - // if (this._data instanceof HTMLImageElement) { - // this._data.src = ""; - // cc.loader.removeItem(this._data.id); - // } - // } - // } - - // SERIALIZATION - - _serialize () { - let extId = ""; - let exportedExts = this._exportedExts; - if (!exportedExts && this._native) { - exportedExts = [this._native]; - } - if (exportedExts) { - let exts = []; - for (let i = 0; i < exportedExts.length; i++) { - let extId = ""; - let ext = exportedExts[i]; - if (ext) { - // ext@format - let extFormat = ext.split('@'); - extId = ImageAsset.extnames.indexOf(extFormat[0]); - if (extId < 0) { - extId = ext; - } - if (extFormat[1]) { - extId += '@' + extFormat[1]; - } - } - exts.push(extId); - } - extId = exts.join('_'); - } - return "" + extId; - } - - _deserialize (data, handle) { - let fields = data.split(','); - // decode extname - var extIdStr = fields[0]; - if (extIdStr) { - let extIds = extIdStr.split('_'); - - let extId = 999; - let ext = ''; - let format = this._format; - let SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS; - for (let i = 0; i < extIds.length; i++) { - let extFormat = extIds[i].split('@'); - let tmpExt = extFormat[0]; - tmpExt = tmpExt.charCodeAt(0) - CHAR_CODE_0; - tmpExt = ImageAsset.extnames[tmpExt] || extFormat; - - let index = SupportTextureFormats.indexOf(tmpExt); - if (index !== -1 && index < extId) { - extId = index; - ext = tmpExt; - format = extFormat[1] ? parseInt(extFormat[1]) : this._format; - } - } - - if (ext) { - this._setRawAsset(ext); - this._format = format; - } - - // preset uuid to get correct nativeUrl - let loadingItem = handle.customEnv; - let uuid = loadingItem && loadingItem.uuid; - if (uuid) { - this._uuid = uuid; - var url = this.nativeUrl; - this.url = url; - } - } - } - - _onDataComplete() { - this.loaded = true; - this.emit("load"); - } -} - -/** - * !#zh - * 当该资源加载成功后触发该事件 - * !#en - * This event is emitted when the asset is loaded - * - * @event load - */ -addon(ImageAsset.prototype, EventTarget.prototype); - -cc.ImageAsset = ImageAsset; \ No newline at end of file diff --git a/cocos/assets/image-asset.ts b/cocos/assets/image-asset.ts new file mode 100644 index 0000000000..708fc1c0ed --- /dev/null +++ b/cocos/assets/image-asset.ts @@ -0,0 +1,231 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ +// @ts-check +import {ccclass, property} from '../core/data/class-decorator'; +import EventTarget from '../core/event/event-target'; +import {addon} from '../core/utils/js'; +import { Asset } from './asset'; + +export interface IMemoryImageSource { + _data: ArrayBufferView | null; + _compressed: boolean; + width: number; + height: number; + format: number; +} + +export type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource; + +/** + * Class ImageAsset. + */ +@ccclass('cc.ImageAsset') +export class ImageAsset extends Asset { + + @property({override: true}) + get _nativeAsset () { + // Maybe returned to pool in webgl. + return this._nativeData; + } + + set _nativeAsset (value: ImageSource) { + this.reset(value); + } + + get data () { + return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data; + } + + get width () { + return this._nativeData.width; + } + + get height () { + return this._nativeData.height; + } + + get format () { + if (this._nativeData instanceof HTMLElement) { + return undefined; + } + return this._nativeData.format; + } + + /** + * !#en + * The url of the texture, this could be empty if the texture wasn't created via a file. + * !#zh + * 图像文件的 url,当图像不是由文件创建时值可能为空 + */ + // TODO - use nativeUrl directly + get url () { + return this._url; + } + + private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc']; + + private _nativeData: ImageSource; + + private _url: string; + + private _exportedExts: string[] | null | undefined = undefined; + + private _format: string = ''; + + /** + * @param nativeAsset + */ + constructor (nativeAsset?: ImageSource) { + super(); + // @ts-ignore + EventTarget.call(this); + + this._url = ''; + + this._nativeData = { + _data: null, + width: 0, + height: 0, + format: 0, + _compressed: false, + }; + + if (CC_EDITOR) { + this._exportedExts = null; + } + + if (nativeAsset !== undefined) { + this._nativeAsset = nativeAsset; + } + } + + public reset (data: ImageSource) { + if (!(data instanceof HTMLElement)) { + this._nativeData = Object.create(data); + this._onDataComplete(); + } else { + this._nativeData = data; + if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) { + this._onDataComplete(); + } else { + this.loaded = false; + data.addEventListener('load', () => { + this._onDataComplete(); + }); + data.addEventListener('error', (err) => { + cc.warnID(3119, err.message); + }); + } + } + } + + // destroy() { + // if (cc.macro.CLEANUP_IMAGE_CACHE) { + // if (this._data instanceof HTMLImageElement) { + // this._data.src = ""; + // cc.loader.removeItem(this._data.id); + // } + // } + // } + + // SERIALIZATION + + public _serialize () { + let targetExtensions = this._exportedExts; + if (!targetExtensions && this._native) { + targetExtensions = [this._native]; + } + + if (!targetExtensions) { + return ''; + } + + const extensionIndices: string[] = []; + for (const targetExtension of targetExtensions) { + const extensionFormat = targetExtension.split('@'); + const i = ImageAsset.extnames.indexOf(extensionFormat[0]); + let exportedExtensionID = i < 0 ? targetExtension : `${i}`; + if (extensionFormat[1]) { + exportedExtensionID += '@' + extensionFormat[1]; + } + extensionIndices.push(exportedExtensionID); + } + return extensionIndices.join('_'); + } + + public _deserialize (data: string, handle: any) { + const extensionIDs = data.split('_'); + + let preferedExtensionIndex = Number.MAX_VALUE; + let format = this._format; + let ext = ''; + const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS as string[]; + for (const extensionID of extensionIDs) { + const extFormat = extensionID.split('@'); + + const i = parseInt(extFormat[0], undefined); + const tmpExt = ImageAsset.extnames[i] || extFormat.join(); + + const index = SupportTextureFormats.indexOf(tmpExt); + if (index !== -1 && index < preferedExtensionIndex) { + preferedExtensionIndex = index; + ext = tmpExt; + format = extFormat[1] ? extFormat[1] : this._format; + } + } + + if (ext) { + // @ts-ignore + this._setRawAsset(ext); + this._format = format; + } + + // preset uuid to get correct nativeUrl + const loadingItem = handle.customEnv; + const uuid = loadingItem && loadingItem.uuid; + if (uuid) { + this._uuid = uuid; + this._url = this.nativeUrl; + } + } + + public _onDataComplete () { + this.loaded = true; + // @ts-ignore + this.emit('load'); + } +} + +/** + * !#zh + * 当该资源加载成功后触发该事件 + * !#en + * This event is emitted when the asset is loaded + * + * @event load + */ +addon(ImageAsset.prototype, EventTarget.prototype); + +cc.ImageAsset = ImageAsset; diff --git a/cocos/assets/index.js b/cocos/assets/index.js index b39587bccc..fd95924b0c 100644 --- a/cocos/assets/index.js +++ b/cocos/assets/index.js @@ -24,18 +24,18 @@ THE SOFTWARE. ****************************************************************************/ -export {default as RawAsset} from './CCRawAsset'; -export {default as Asset} from './CCAsset'; +export { RawAsset } from './raw-asset'; +export { Asset } from './asset'; export {default as Prefab} from './CCPrefab'; export * from './CCScripts'; export {default as SceneAsset} from './CCSceneAsset'; -export {default as SpriteFrame} from './CCSpriteFrame'; +export { SpriteFrame } from './CCSpriteFrame'; export {default as SpriteAtlas} from './CCSpriteAtlas'; export {default as TextAsset} from './CCTextAsset'; export {default as JsonAsset} from './CCJsonAsset'; export {default as GLTFAsset} from './CCGLTFAsset'; export {default as BufferAsset} from './CCBufferAsset'; export {default as AssetLibrary} from './CCAssetLibrary'; -export {default as ImageAsset} from './image-asset'; -export {default as Texture2D} from './texture-2d'; -export {default as RenderTexture} from './render-texture'; +export { ImageAsset } from './image-asset'; +export { Texture2D } from './texture-2d'; +export { RenderTexture } from './render-texture'; diff --git a/cocos/3d/assets/utils/buffer-range.js b/cocos/assets/raw-asset.d.ts similarity index 70% rename from cocos/3d/assets/utils/buffer-range.js rename to cocos/assets/raw-asset.d.ts index bbd720b2df..a7d7b2e319 100644 --- a/cocos/3d/assets/utils/buffer-range.js +++ b/cocos/assets/raw-asset.d.ts @@ -1,4 +1,5 @@ /**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -23,33 +24,10 @@ THE SOFTWARE. ****************************************************************************/ -// @ts-check -import { _decorator } from "../../../core/data"; -const { ccclass, property } = _decorator; +import { CCObject } from '../core/data/object'; -/** - * The class BufferRange denotes a range of the buffer. - */ -@ccclass("cc.BufferRange") -export default class BufferRange { - /** - * The offset of the range. - * @type {Number} - */ - @property(Number) - _offset = 0; - - /** - * The length of the range, in bytes. - * @type {Number} - */ - @property(Number) - _length = 0; - - constructor(offset, length) { - this._offset = offset; - this._length = length; - } +export class RawAsset extends CCObject { + _uuid: string; + public constructor(); + static isRawAssetType(ctor: Function): boolean; } - -cc.BufferRange = BufferRange; \ No newline at end of file diff --git a/cocos/assets/CCRawAsset.js b/cocos/assets/raw-asset.js similarity index 91% rename from cocos/assets/CCRawAsset.js rename to cocos/assets/raw-asset.js index d433c0c493..52b902900a 100644 --- a/cocos/assets/CCRawAsset.js +++ b/cocos/assets/raw-asset.js @@ -24,9 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -import {isChildClassOf} from '../core/utils/js'; -import CCObject from '../core/data/object'; -import {ccclass} from '../core/data/class-decorator'; +import { isChildClassOf } from '../core/utils/js'; +import { CCObject } from '../core/data/object'; +import { ccclass } from '../core/data/class-decorator'; /** * !#en @@ -38,7 +38,7 @@ import {ccclass} from '../core/data/class-decorator'; * @extends Object */ @ccclass('cc.RawAsset') -export default class RawAsset extends CCObject { +export class RawAsset extends CCObject { constructor () { super(); /** diff --git a/cocos/assets/render-texture.js b/cocos/assets/render-texture.js deleted file mode 100644 index 5b3302620f..0000000000 --- a/cocos/assets/render-texture.js +++ /dev/null @@ -1,135 +0,0 @@ -import gfx from '../renderer/gfx'; -import Texture2D from './texture-2d'; -import { ccclass } from '../core/data/class-decorator'; - -/** - * Render textures are textures that can be rendered to. - * @class RenderTexture - * @extends Texture2D - */ -@ccclass('cc.RenderTexture') -export default class RenderTexture extends Texture2D { - - constructor () { - super(); - this._framebuffer = null; - } - - /** - * !#en - * Init the render texture with size. - * !#zh - * 初始化 render texture - * @param {Number} [width] - * @param {Number} [height] - * @param {Number} [depthStencilFormat] - * @method initWithSize - */ - initWithSize (width, height, depthStencilFormat) { - this.width = Math.floor(width || cc.visibleRect.width); - this.height = Math.floor(height || cc.visibleRect.height); - this._resetUnderlyingMipmaps(); - - let opts = { - colors: [ this._texture ], - }; - if (depthStencilFormat) { - if (this.depthStencilBuffer) this.depthStencilBuffer.destroy(); - let depthStencilBuffer = new gfx.RenderBuffer(cc.game._renderContext, depthStencilFormat, this.width, this.height); - if (depthStencilFormat === gfx.RB_FMT_D24S8) { - opts.depthStencil = depthStencilBuffer; - } - else if (depthStencilFormat === gfx.RB_FMT_S8) { - opts.stencil = depthStencilBuffer; - } - else if (depthStencilFormat === gfx.RB_FMT_D16) { - opts.depth = depthStencilBuffer; - } - this.depthStencilBuffer = depthStencilBuffer; - this.depthStencilFormat = depthStencilFormat; - } - - if (this._framebuffer) this._framebuffer.destroy(); - this._framebuffer = new gfx.FrameBuffer(cc.game._renderContext, this.width, this.height, opts); - - this.loaded = true; - this.emit("load"); - } - - updateSize(width, height) { - this.width = Math.floor(width || cc.visibleRect.width); - this.height = Math.floor(height || cc.visibleRect.height); - this._resetUnderlyingMipmaps(); - - let rbo = this.depthStencilBuffer; - if (rbo) rbo.update(this.width, this.height); - this._framebuffer._width = width; - this._framebuffer._height = height; - } - - /** - * !#en Draw a texture to the specified position - * !#zh 将指定的图片渲染到指定的位置上 - * @param {Texture2D} texture - * @param {Number} x - * @param {Number} y - */ - drawTextureAt (texture, x, y) { - if (!texture._image) return; - - this._texture.updateSubImage({ - x, y, - image: texture._image, - width: texture.width, - height: texture.height, - level: 0, - flipY: false, - premultiplyAlpha: texture._premultiplyAlpha - }) - } - - /** - * !#en - * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array. - * It will return a new (width * height * 4) length Uint8Array by default。 - * You can specify a data to store the pixels to reuse the data, - * you and can specify other params to specify the texture region to read. - * !#zh - * 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。 - * 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。 - * 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。 - * @method readPixels - * @param {Uint8Array} [data] - * @param {Number} [x] - * @param {Number} [y] - * @param {Number} [w] - * @param {Number} [h] - * @return {Uint8Array} - */ - readPixels (data, x, y, w, h) { - if (!this._framebuffer || !this._texture) return data; - - x = x || 0; - y = y || 0; - let width = w || this.width; - let height = h || this.height; - data = data || new Uint8Array(width * height * 4); - - let gl = cc.game._renderContext._gl; - let oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); - gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer._glID); - gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); - gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO); - - return data; - } - - destroy () { - super.destroy(); - if (this._framebuffer) { - this._framebuffer.destroy(); - } - } -} - -cc.RenderTexture = RenderTexture; diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts new file mode 100644 index 0000000000..d535942467 --- /dev/null +++ b/cocos/assets/render-texture.ts @@ -0,0 +1,215 @@ +import { ccclass } from '../core/data/class-decorator'; +import { IRect2D, normalizeRect2D } from '../core/vmath/rect'; +import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; +import { GFXFramebuffer } from '../gfx/framebuffer'; +import { GFXTexture } from '../gfx/texture'; +import { GFXTextureView } from '../gfx/texture-view'; +import { RenderPassStage } from '../pipeline/define'; +import { ImageAsset } from './image-asset'; +import { Texture2D } from './texture-2d'; + +type DSFormat = 'D24S8' | 'S8' | 'D16'; +const _formatMap = { + D24S8: GFXFormat.D24S8, + S8: GFXFormat.R8UI, + D16: GFXFormat.D16, +}; + +/** + * Render textures are textures that can be rendered to. + * @class RenderTexture + * @extends Texture2D + */ +@ccclass('cc.RenderTexture') +export class RenderTexture extends Texture2D { + private _framebuffer: GFXFramebuffer | null = null; + + private _depthStencilTexture: GFXTexture | null = null; + + private _depthStencilTextureView: GFXTextureView | null = null; + + constructor () { + super(); + } + + /** + * !#en + * Init the render texture with size. + * !#zh + * 初始化 render texture + * @param [width] + * @param [height] + * @param [string] + * @method initWithSize + */ + public initWithSize (width?: number, height?: number, format?: DSFormat) { + this.destroy(); + + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + const w = Math.floor(width || cc.visibleRect.width); + const h = Math.floor(height || cc.visibleRect.height); + const image = new ImageAsset({ + width: w, + height: h, + format: GFXFormat.RGBA8UI, + _data: new Uint8Array(w * h * 4), + _compressed: false, + }); + + this.image = image; + + if (!this._texture) { + return; + } + + const colorView = gfxDevice.createTextureView({ + texture: this._texture, + type: GFXTextureViewType.TV2D, + format: this._getGfxFormat(), + }); + + if (!colorView) { + return; + } + + if (format !== undefined) { + this._depthStencilTexture = gfxDevice.createTexture({ + type: GFXTextureType.TEX2D, + usage: GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT, + format: _formatMap[format], + width: w, + height: h, + }); + if (!this._depthStencilTexture) { + return; + } + this._depthStencilTextureView = gfxDevice.createTextureView({ + texture: this._depthStencilTexture, + type: GFXTextureViewType.TV2D, + format: _formatMap[format], + }); + } + + if (this._depthStencilTextureView === null) { + return; + } + + this._framebuffer = gfxDevice.createFramebuffer({ + renderPass: cc.director.root.pipeline.getRenderPass(RenderPassStage.DEFAULT), + colorViews: [ colorView ], + depthStencilView: this._depthStencilTextureView === null ? undefined : this._depthStencilTextureView, + isOffscreen: true, + }); + + this.loaded = true; + // @ts-ignore + this.emit('load'); + } + + public destroy () { + if (this._framebuffer) { + this._framebuffer.destroy(); + this._framebuffer = null; + } + if (this._depthStencilTextureView) { + this._depthStencilTextureView.destroy(); + this._depthStencilTextureView = null; + } + if (this._depthStencilTexture) { + this._depthStencilTexture.destroy(); + this._depthStencilTexture = null; + } + return super.destroy(); + } + + // TODO: + // public updateSize (width, height) { + // this.width = Math.floor(width || cc.visibleRect.width); + // this.height = Math.floor(height || cc.visibleRect.height); + // this._resetUnderlyingMipmaps(); + + // const rbo = this.depthStencilBuffer; + // if (rbo) { rbo.update(this.width, this.height); } + // this._framebuffer._width = width; + // this._framebuffer._height = height; + // } + + /** + * !#en Draw a texture to the specified position + * !#zh 将指定的图片渲染到指定的位置上 + * @param texture + * @param x + * @param y + */ + public drawTextureAt (texture: Texture2D, x: number, y: number) { + if (!this._texture) { + return; + } + + const image = texture.image; + + if (!image) { + return; + } + + this._assignImage(image, 0); + } + + /** + * !#en + * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array. + * It will return a new (width * height * 4) length Uint8Array by default。 + * You can specify a data to store the pixels to reuse the data, + * you and can specify other params to specify the texture region to read. + * !#zh + * 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。 + * 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。 + * 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。 + * @param [data] + * @param [rect] + */ + public readPixels (data?: Uint8Array, rect: IRect2D = {}) { + if (!this._framebuffer || !this._texture) { + return undefined; + } + + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + const normalizedRect = normalizeRect2D(rect, this.width, this.height); + + data = data || new Uint8Array(normalizedRect.width * normalizedRect.height * 4); + + gfxDevice.copyFramebufferToBuffer(this._framebuffer, data.buffer, [{ + buffOffset: 0, + buffStride: 0, + buffTexHeight: 0, + texOffset: { + x: normalizedRect.x, + y: normalizedRect.y, + z: 0, + }, + texExtent: { + width: normalizedRect.width, + height: normalizedRect.height, + depth: 1, + }, + texSubres: { + baseMipLevel: 0, + levelCount: 1, + baseArrayLayer: 0, + layerCount: 1, + }, + }]); + + return data; + } +} + +cc.RenderTexture = RenderTexture; diff --git a/cocos/assets/texture-2d.js b/cocos/assets/texture-2d.js deleted file mode 100644 index 544984835b..0000000000 --- a/cocos/assets/texture-2d.js +++ /dev/null @@ -1,327 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ -// @ts-check -import GFXTexture2D from '../renderer/gfx/texture-2d'; -import {ccclass, property} from '../core/data/class-decorator'; -import TextureBase from './texture-base'; -import ImageAsset from './image-asset'; - -/** - * @typedef {import("./texture-base").ImageSource} ImageSource - * @typedef {import("./texture-base").TextureUpdateOpts} TextureUpdateOpts - */ - -/** - *

- * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
- * The created cc.Texture2D object will always have power-of-two dimensions.
- * Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
- * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
- * Be aware that the content of the generated textures will be upside-down!

- - * @class Texture2D - * @extends TextureBase - */ -@ccclass('cc.Texture2D') -export default class Texture2D extends TextureBase { - @property({ - override: true - }) - _flipY = true; - - /** - * @type {ImageAsset[]} - */ - @property([ImageAsset]) - _mipmaps = []; - - constructor () { - super(); - - /** - * @type {GFXTexture2D} - */ - this._texture = null; - } - - /** - * Gets the mipmap images. - * Note that the result do not contains the auto generated mipmaps. - * @return {ImageAsset[]} - */ - get mipmaps() { - return this._mipmaps; - } - - /** - * Sets the mipmaps images. - * @param {ImageAsset[]} value - */ - set mipmaps(value) { - this._setMipmaps(value); - } - - /** - * Gets the mipmap image at level 0. - * @return {ImageAsset} - */ - get image() { - return this._mipmaps.length === 0 ? null : this._mipmaps[0]; - } - - /** - * Sets the mipmap images as a single mipmap image. - * @param {ImageAsset} value - */ - set image(value) { - this.mipmaps = [value]; - } - - /** - * Gets the underlying texture object. - */ - getImpl () { - return this._texture; - } - - /** - * Returns the string representation of this texture. - */ - toString () { - return this._mipmaps.length !== 0 ? this._mipmaps[0].url : ""; - } - - /** - * Update texture options, not available in Canvas render mode. - * image, format, premultiplyAlpha can not be updated in native. - * @method update - * @param {TextureUpdateOpts} options - */ - update (options) { - if (!options) { - return; - } - - super.update(options); - - if (options.image) { - options.images = [options.image]; - } - - if (options.images !== undefined && options.images.length !== 0) { - this._setMipmaps(options.images.map(image => { - const mipmap = new ImageAsset(); - mipmap.reset(image instanceof HTMLElement ? image : { - _data: image, - width: this.width, - height: this.height, - format: this._format, - _compressed: false - }); - return mipmap; - })); - } - - if (this._texture) { - this._texture.update(options); - } - } - - /** - * - * @param {ImageSource} source - */ - updateImage(source) { - this.updateMipmaps([source]); - } - - /** - * Updates mipmaps at specified range of levels. - * @param {ImageSource[]} sources The image sources. - * @param {number} firstLevel The first level from which the sources update. - * @description - * If the range specified by [firstLevel, firstLevel + sources.length) exceeds - * the actually range of mipmaps this texture contains, only overlaped mipmaps are updated. - */ - updateMipmaps(sources, firstLevel = 0) { - if (firstLevel >= sources.length) { - return; - } - - const nUpdate = Math.min(sources.length, this._mipmaps.length - firstLevel); - for (let i = 0; i < nUpdate; ++i) { - const level = firstLevel + i; - const mipmap = this._mipmaps[level]; - const source = sources[i]; - mipmap.reset(source instanceof HTMLElement ? source : { - _data: source, - width: mipmap.width, - height: mipmap.height, - format: mipmap._format, - _compressed: false - }); - this._texture.updateImage({ - width: this.width, - height: this.height, - level: level, - image: sources[i], - flipY: false, - premultiplyAlpha: false - }); - } - } - - /** - * !#en - * HTMLElement Object getter, available only on web. - * !#zh 获取当前贴图对应的 HTML Image 或 Canvas 对象,只在 Web 平台下有效。 - * @method getHtmlElementObj - * @return {HTMLImageElement|HTMLCanvasElement} - * @deprecated Use this.image.data instead. - */ - getHtmlElementObj () { - return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data: null; - } - - /** - * !#en - * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
- * After destroy, this object is not usable any more. - * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. - * !#zh - * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
- * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @method destroy - * @return {Boolean} inherit from the CCObject - */ - destroy () { - this.releaseTexture(); - // TODO cc.textureUtil ? - // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url - return super.destroy(); - } - - /** - * !#en - * Description of cc.Texture2D. - * !#zh cc.Texture2D 描述。 - * @method description - * @returns {String} - */ - description () { - return ""; - } - - /** - * !#en - * Release texture, please use destroy instead. - * !#zh 释放纹理,请使用 destroy 替代。 - * @method releaseTexture - * @deprecated since v2.0, use destroy instead. - */ - releaseTexture () { - this._setMipmaps([]); - this._texture && this._texture.destroy(); - } - - /** - * Sets the _mipmaps to specified value, and updates the width and height accordingly. - * If available, synchronize the mipmap data to underlying texture. - * @param {ImageAsset[]} mipmaps - */ - _setMipmaps(mipmaps) { - this._mipmaps = mipmaps; - if (mipmaps.length === 0) { - super.update({ - width: 0, - height: 0 - }); - } else { - const level0 = this._mipmaps[0]; - super.update({ - width: level0.width, - height: level0.height, - format: level0._format - }); - } - - let counter = 0; - const inc = () => { - ++counter; - if (counter === mipmaps.length) { - this._resetUnderlyingMipmaps(mipmaps.map(mipmap => mipmap.data)); - } - }; - mipmaps.forEach(mipmap => { - if (mipmap.loaded) { - inc(); - } else { - mipmap.addEventListener("load", () => { - inc(); - }); - } - }); - } - - /** - * Resets sources and amount of the underlying texture's the mipmaps. - * @param {ImageSource[]} mipmapSources - */ - _resetUnderlyingMipmaps(mipmapSources = [null]) { - const opts = this._getOpts(); - opts.images = mipmapSources; - if (!this._texture) { - this._texture = new GFXTexture2D(cc.game._renderContext, opts); - } else { - this._texture.update(opts); - } - } - - _serialize() { - return { - base: super._serialize(), - mipmaps: this._mipmaps.map(mipmap => mipmap._uuid) - }; - } - - _deserialize (data, handle) { - super._deserialize(data.base); - - this._mipmaps = new Array(data.mipmaps.length); - for (let i = 0; i < data.mipmaps.length; ++i) { - // Prevent resource load failed - this._mipmaps[i] = new ImageAsset(); - const mipmapUUID = data.mipmaps[i]; - handle.result.push(this._mipmaps, `${i}`, mipmapUUID); - } - } - - onLoaded() { - this.mipmaps = this._mipmaps; - } -} - -cc.Texture2D = Texture2D; diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts new file mode 100644 index 0000000000..d5a5afd186 --- /dev/null +++ b/cocos/assets/texture-2d.ts @@ -0,0 +1,194 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ +// @ts-check +import { ccclass, property } from '../core/data/class-decorator'; +import { ImageAsset, ImageSource } from './image-asset'; +import { TextureBase } from './texture-base'; + +/** + * Represents a 2-dimension texture. + */ +@ccclass('cc.Texture2D') +export class Texture2D extends TextureBase { + /** + * Gets the mipmap images. + * Note that the result do not contains the auto generated mipmaps. + */ + get mipmaps () { + return this._mipmaps; + } + + /** + * Sets the mipmaps images. + */ + set mipmaps (value) { + this._mipmaps = value; + this.create( + value.length === 0 ? 0 : value[0].width, + value.length === 0 ? 0 : value[0].height, + undefined, + this._mipmaps.length); + this._mipmaps.forEach((mipmap, level) => { + this._assignImage(mipmap, level); + }); + } + + /** + * Gets the mipmap image at level 0. + */ + get image () { + return this._mipmaps.length === 0 ? null : this._mipmaps[0]; + } + + /** + * Sets the mipmap images as a single mipmap image. + */ + set image (value) { + this.mipmaps = value ? [value] : []; + } + + @property([ImageAsset]) + public _mipmaps: ImageAsset[] = []; + + constructor () { + super(true); + } + + /** + * Returns the string representation of this texture. + */ + public toString () { + return this._mipmaps.length !== 0 ? this._mipmaps[0].url : ''; + } + + /** + * Updates mipmaps at level 0. + */ + public updateImage () { + this.updateMipmaps(0); + } + + /** + * Updates mipmaps at specified range of levels. + * @param firstLevel The first level from which the sources update. + * @description + * If the range specified by [firstLevel, firstLevel + sources.length) exceeds + * the actually range of mipmaps this texture contains, only overlaped mipmaps are updated. + * Use this method if your mipmap data are modified. + */ + public updateMipmaps (firstLevel: number = 0, count?: number) { + if (firstLevel >= this._mipmaps.length) { + return; + } + + const nUpdate = Math.min( + count === undefined ? this._mipmaps.length : count, + this._mipmaps.length - firstLevel); + + for (let i = 0; i < nUpdate; ++i) { + const level = firstLevel + i; + this._assignImage(this._mipmaps[level], level); + } + } + + public directUpdate (source: HTMLImageElement | HTMLCanvasElement | ArrayBuffer, level: number = 0) { + this._uploadData(source, level); + } + + /** + * !#en + * HTMLElement Object getter, available only on web. + * !#zh 获取当前贴图对应的 HTML Image 或 Canvas 对象,只在 Web 平台下有效。 + * @method getHtmlElementObj + * @return {HTMLImageElement|HTMLCanvasElement} + * @deprecated Use this.image.data instead. + */ + public getHtmlElementObj () { + return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data : null; + } + + /** + * !#en + * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
+ * After destroy, this object is not usable any more. + * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. + * !#zh + * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
+ * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + */ + public destroy () { + this._mipmaps = []; + return super.destroy(); + } + + /** + * !#en + * Description of cc.Texture2D. + * !#zh cc.Texture2D 描述。 + */ + public description () { + const url = this._mipmaps[0] ? this._mipmaps[0].url : ''; + return ``; + } + + /** + * !#en + * Release texture, please use destroy instead. + * !#zh 释放纹理,请使用 destroy 替代。 + * @deprecated Since v2.0, use destroy instead. + */ + public releaseTexture () { + this.mipmaps = []; + } + + public _serialize () { + return { + base: super._serialize(), + mipmaps: this._mipmaps.map((mipmap) => mipmap._uuid), + }; + } + + public _deserialize (serializedData: any, handle: any) { + const data = serializedData as ITexture2DSerializeData; + super._deserialize(data.base, handle); + + this._mipmaps = new Array(data.mipmaps.length); + for (let i = 0; i < data.mipmaps.length; ++i) { + // Prevent resource load failed + this._mipmaps[i] = new ImageAsset(); + const mipmapUUID = data.mipmaps[i]; + handle.result.push(this._mipmaps, `${i}`, mipmapUUID); + } + } +} + +/* tslint:disable:no-string-literal */ +cc['Texture2D'] = Texture2D; + +interface ITexture2DSerializeData { + base: string; + mipmaps: string[]; +} diff --git a/cocos/assets/texture-base.js b/cocos/assets/texture-base.js deleted file mode 100644 index 28fc526f3e..0000000000 --- a/cocos/assets/texture-base.js +++ /dev/null @@ -1,602 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ -// @ts-check -import EventTarget from '../core/event/event-target'; -import IDGenerator from '../core/utils/id-generator'; -import Enum from '../core/value-types/enum'; -import {addon} from '../core/utils/js'; -import {enums} from '../renderer/gfx/enums'; -import Asset from './CCAsset'; -import {ccclass, property} from '../core/data/class-decorator'; - -/** - * @typedef {import("../renderer/gfx/texture-2d").HTMLImageSource} HTMLImageSource - * @typedef {import("../renderer/gfx/texture-2d").ImageSource} ImageSource - * @typedef {import("../renderer/gfx/texture-2d").TextureUpdateOpts} TextureUpdateOpts - * - * @exports HTMLImageSource - * @exports ImageSource - * @exports TextureUpdateOpts - */ - -let _images = []; - -const CHAR_CODE_1 = 49; // '1' - -const GL_NEAREST = 9728; // gl.NEAREST -const GL_LINEAR = 9729; // gl.LINEAR -const GL_REPEAT = 10497; // gl.REPEAT -const GL_CLAMP_TO_EDGE = 33071; // gl.CLAMP_TO_EDGE -const GL_MIRRORED_REPEAT = 33648; // gl.MIRRORED_REPEAT - -var idGenerator = new IDGenerator('Tex'); - -/** - * The texture pixel format, default value is RGBA8888, - * you should note that textures loaded by normal image files (png, jpg) can only support RGBA8888 format, - * other formats are supported by compressed file types or raw data. - * @enum {number} - */ -const PixelFormat = Enum({ - /** - * 16-bit texture without Alpha channel - * @property RGB565 - * @readonly - * @type {Number} - */ - RGB565: enums.TEXTURE_FMT_R5_G6_B5, - /** - * 16-bit textures: RGB5A1 - * @property RGB5A1 - * @readonly - * @type {Number} - */ - RGB5A1: enums.TEXTURE_FMT_R5_G5_B5_A1, - /** - * 16-bit textures: RGBA4444 - * @property RGBA4444 - * @readonly - * @type {Number} - */ - RGBA4444: enums.TEXTURE_FMT_R4_G4_B4_A4, - /** - * 24-bit texture: RGB888 - * @property RGB888 - * @readonly - * @type {Number} - */ - RGB888: enums.TEXTURE_FMT_RGB8, - /** - * 32-bit texture: RGBA8888 - * @property RGBA8888 - * @readonly - * @type {Number} - */ - RGBA8888: enums.TEXTURE_FMT_RGBA8, - /** - * 32-bit float texture: RGBA32F - * @property RGBA32F - * @readonly - * @type {Number} - */ - RGBA32F: enums.TEXTURE_FMT_RGBA32F, - /** - * 8-bit textures used as masks - * @property A8 - * @readonly - * @type {Number} - */ - A8: enums.TEXTURE_FMT_A8, - /** - * 8-bit intensity texture - * @property I8 - * @readonly - * @type {Number} - */ - I8: enums.TEXTURE_FMT_L8, - /** - * 16-bit textures used as masks - * @property AI88 - * @readonly - * @type {Number} - */ - AI8: enums.TEXTURE_FMT_L8_A8, - - /** - * rgb 2 bpp pvrtc - * @property RGB_PVRTC_2BPPV1 - * @readonly - * @type {Number} - */ - RGB_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_2BPPV1, - /** - * rgba 2 bpp pvrtc - * @property RGBA_PVRTC_2BPPV1 - * @readonly - * @type {Number} - */ - RGBA_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_2BPPV1, - /** - * rgb 4 bpp pvrtc - * @property RGB_PVRTC_4BPPV1 - * @readonly - * @type {Number} - */ - RGB_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_4BPPV1, - /** - * rgba 4 bpp pvrtc - * @property RGBA_PVRTC_4BPPV1 - * @readonly - * @type {Number} - */ - RGBA_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1, -}); - -/** - * The texture wrap mode - * @enum {number} - */ -export const WrapMode = Enum({ - /** - * The constant variable equals gl.REPEAT for texture - * @property REPEAT - * @type {Number} - * @readonly - */ - REPEAT: GL_REPEAT, - /** - * The constant variable equals gl.CLAMP_TO_EDGE for texture - * @property CLAMP_TO_EDGE - * @type {Number} - * @readonly - */ - CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE, - /** - * The constant variable equals gl.MIRRORED_REPEAT for texture - * @property MIRRORED_REPEAT - * @type {Number} - * @readonly - */ - MIRRORED_REPEAT: GL_MIRRORED_REPEAT -}); - -/** - * The texture filter mode - * @enum {number} - */ -export const Filter = Enum({ - /** - * The constant variable equals gl.LINEAR for texture - * @property LINEAR - * @type {Number} - * @readonly - */ - LINEAR: GL_LINEAR, - /** - * The constant variable equals gl.NEAREST for texture - * @property NEAREST - * @type {Number} - * @readonly - */ - NEAREST: GL_NEAREST -}); - -const FilterIndex = { - 9728: 0, // GL_NEAREST - 9729: 1, // GL_LINEAR -}; - -/** - * @type TextureUpdateOpts - */ -let _sharedOpts = { - width: undefined, - height: undefined, - minFilter: undefined, - magFilter: undefined, - mipFilter: undefined, - wrapS: undefined, - wrapT: undefined, - format: undefined, - mipmap: undefined, - images: undefined, - image: undefined, - flipY: undefined, - premultiplyAlpha: undefined, - anisotropy: undefined -}; -function _getSharedOptions () { - for (var key in _sharedOpts) { - _sharedOpts[key] = undefined; - } - _images.length = 0; - _sharedOpts.images = _images; - _sharedOpts.flipY = false; - return _sharedOpts; -} - -@ccclass('cc.TextureBase') -export default class TextureBase extends Asset { - @property - _genMipmap = false; - - @property - _format = PixelFormat.RGBA8888; - - @property - _premultiplyAlpha = false; - - @property - _flipY = false; - - @property - _minFilter = Filter.LINEAR; - - @property - _magFilter = Filter.LINEAR; - - @property - _mipFilter = Filter.LINEAR; - - @property - _wrapS = WrapMode.CLAMP_TO_EDGE; - - @property - _wrapT = WrapMode.CLAMP_TO_EDGE; - - @property - _anisotropy = 1; - - static PixelFormat = PixelFormat; - - static WrapMode = WrapMode; - - static Filter = Filter; - - /** - * - * @param {TextureBase} texture - */ - static _isCompressed (texture) { - return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1; - } - - constructor () { - super(); - EventTarget.call(this); - - // Id for generate hash in material - this._id = idGenerator.getNewId(); - - /** - * !#en - * Whether the texture is loaded or not - * !#zh - * 贴图是否已经成功加载 - * @property loaded - * @type {Boolean} - */ - this.loaded = false; - /** - * !#en - * Texture width, in pixels. - * For 2D texture, the width of texture is equal to its very first mipmap's width; - * For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width. - * !#zh - * 贴图像素宽度 - * @property width - * @type {Number} - */ - this.width = 0; - /** - * !#en - * Texture height, in pixels. - * For 2D texture, the height of texture is equal to its very first mipmap's height; - * For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height. - * !#zh - * 贴图像素高度 - * @property height - * @type {Number} - */ - this.height = 0; - } - - getId () { - return this._id; - } - - /** - * Update texture sampler options. - * @method update - * @param {TextureUpdateOpts} options - */ - update (options) { - if (!options) { - return; - } - - if (options.width !== undefined) { - this.width = options.width; - } - if (options.height !== undefined) { - this.height = options.height; - } - if (options.minFilter !== undefined) { - this._minFilter = options.minFilter; - options.minFilter = FilterIndex[options.minFilter]; - } - if (options.magFilter !== undefined) { - this._magFilter = options.magFilter; - options.magFilter = FilterIndex[options.magFilter]; - } - if (options.mipFilter !== undefined) { - this._mipFilter = options.mipFilter; - options.mipFilter = FilterIndex[options.mipFilter]; - } - if (options.wrapS !== undefined) { - this._wrapS = options.wrapS; - } - if (options.wrapT !== undefined) { - this._wrapT = options.wrapT; - } - if (options.format !== undefined) { - this._format = options.format; - } - if (options.flipY !== undefined) { - this._flipY = options.flipY; - } - if (options.premultiplyAlpha !== undefined) { - this._premultiplyAlpha = options.premultiplyAlpha; - } - if (options.anisotropy !== undefined) { - this._anisotropy = options.anisotropy; - } - if (options.mipmap !== undefined) { - this._genMipmap = options.mipmap; - } - } - - _getOpts() { - let opts = _getSharedOptions(); - opts.width = this.width; - opts.height = this.height; - opts.mipmap = this._genMipmap; - opts.format = this._format; - opts.premultiplyAlpha = this._premultiplyAlpha; - opts.anisotropy = this._anisotropy; - opts.flipY = this._flipY; - opts.minFilter = FilterIndex[this._minFilter]; - opts.magFilter = FilterIndex[this._magFilter]; - opts.mipFilter = FilterIndex[this._mipFilter]; - opts.wrapS = this._wrapS; - opts.wrapT = this._wrapT; - return opts; - } - - /** - * !#en - * Pixel format of the texture. - * !#zh 获取纹理的像素格式。 - * @method getPixelFormat - * @return {Number} - */ - getPixelFormat () { - //support only in WebGl rendering mode - return this._format; - } - - /** - * !#en - * Whether or not the texture has their Alpha premultiplied. - * !#zh 检查纹理在上传 GPU 时预乘选项是否开启。 - * @method hasPremultipliedAlpha - * @return {Boolean} - */ - hasPremultipliedAlpha () { - return this._premultiplyAlpha || false; - } - - /** - * !#en Anisotropy of the texture. - * !#zh 获取纹理的各向异性。 - * @method getAnisotropy - * @return {Number} - */ - getAnisotropy() { - return this._anisotropy; - } - - /** - * !#en - * Whether or not to generate mipmap. - * !#zh 检查纹理在上传 GPU 时是否生成 mipmap。 - * @method hasMipmap - * @return {Boolean} - */ - genMipmap () { - return this._genMipmap || false; - } - - /** - * !#en Sets the wrap s and wrap t options.
- * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. - * !#zh 设置纹理包装模式。 - * 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。 - * @method setTexParameters - * @param {WrapMode} wrapS - * @param {WrapMode} wrapT - */ - setWrapMode (wrapS, wrapT) { - if (this._wrapS !== wrapS || this._wrapT !== wrapT) { - var opts = _getSharedOptions(); - opts.wrapS = wrapS; - opts.wrapT = wrapT; - this.update(opts); - } - } - - /** - * !#en Sets the minFilter and magFilter options - * !#zh 设置纹理贴图缩小和放大过滤器算法选项。 - * @method setFilters - * @param {Filter} minFilter - * @param {Filter} magFilter - */ - setFilters (minFilter, magFilter) { - if (this._minFilter !== minFilter || this._magFilter !== magFilter) { - var opts = _getSharedOptions(); - opts.minFilter = minFilter; - opts.magFilter = magFilter; - this.update(opts); - } - } - - /** - * !#en Sets the mipFilter options - * !#zh 设置纹理Mipmap过滤算法选项。 - * @method setMipFilter - * @param {Filter} mipFilter - */ - setMipFilter (mipFilter) { - if (this._mipFilter !== mipFilter) { - var opts = _getSharedOptions(); - opts.mipFilter = mipFilter; - this.update(opts); - } - } - - /** - * !#en - * Sets the flipY options - * !#zh 设置贴图的纵向翻转选项。 - * @method setFlipY - * @param {Boolean} flipY - */ - setFlipY (flipY) { - if (this._flipY !== flipY) { - var opts = _getSharedOptions(); - opts.flipY = flipY; - this.update(opts); - } - } - - /** - * !#en - * Sets the premultiply alpha options - * !#zh 设置贴图的预乘选项。 - * @method setPremultiplyAlpha - * @param {Boolean} premultiply - */ - setPremultiplyAlpha (premultiply) { - if (this._premultiplyAlpha !== premultiply) { - var opts = _getSharedOptions(); - opts.premultiplyAlpha = premultiply; - this.update(opts); - } - } - - /** - * !#en Sets the anisotropy of the texture - * !#zh 设置贴图的各向异性。 - * @method setAnisotropy - * @param {number} anisotropy - */ - setAnisotropy(anisotropy) { - if (this._anisotropy != anisotropy) { - var opts = _getSharedOptions(); - opts.anisotropy = anisotropy; - this.update(opts); - } - } - - /** - * !#en - * Sets whether generate mipmaps for the texture - * !#zh 是否为纹理设置生成 mipmaps。 - * @method setGenerateMipmap - * @param {Boolean} mipmap - */ - setGenMipmap (mipmap) { - if (this._genMipmap !== mipmap) { - var opts = _getSharedOptions(); - opts.mipmap = mipmap; - this.update(opts); - } - } - - // SERIALIZATION - - /** - * @return {any} - */ - _serialize () { - return this._minFilter + "," + this._magFilter + "," + - this._wrapS + "," + this._wrapT + "," + - (this._premultiplyAlpha ? 1 : 0) + "," + - this._mipFilter + "," + this._anisotropy + "," + - (this._flipY ? 1 : 0) + "," + - (this._genMipmap ? 1 : 0); - } - - /** - * - * @param {string} data - */ - _deserialize (data) { - let fields = data.split(','); - fields.unshift(""); - if (fields.length >= 6) { - // decode filters - this._minFilter = parseInt(fields[1]); - this._magFilter = parseInt(fields[2]); - // decode wraps - this._wrapS = parseInt(fields[3]); - this._wrapT = parseInt(fields[4]); - // decode premultiply alpha - this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1; - } - if (fields.length >= 8) { - this._mipFilter = parseInt(fields[6]); - this._anisotropy = parseInt(fields[7]); - } - if (fields.length >= 10) { - this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1; - this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1; - } - } -} - -/** - * !#zh - * 当该资源加载成功后触发该事件 - * !#en - * This event is emitted when the asset is loaded - * - * @event load - */ - -addon(TextureBase.prototype, EventTarget.prototype); -cc.TextureBase = TextureBase; diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts new file mode 100644 index 0000000000..5f8812de9e --- /dev/null +++ b/cocos/assets/texture-base.ts @@ -0,0 +1,644 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ +// @ts-check +import {ccclass, property} from '../core/data/class-decorator'; +import EventTarget from '../core/event/event-target'; +import IDGenerator from '../core/utils/id-generator'; +import {addon} from '../core/utils/js'; +import { ccenum } from '../core/value-types/enum'; +import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat, + GFXTextureFlagBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; +import { GFXDevice } from '../gfx/device'; +import { GFXSampler } from '../gfx/sampler'; +import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; +import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view'; +import { Asset } from './asset'; +import { ImageAsset, ImageSource } from './image-asset'; + +const CHAR_CODE_1 = 49; // '1' + +const idGenerator = new IDGenerator('Tex'); + +/** + * The texture pixel format, default value is RGBA8888, + * you should note that textures loaded by normal image files (png, jpg) can only support RGBA8888 format, + * other formats are supported by compressed file types or raw data. + * @enum {number} + */ +export enum PixelFormat { + /** + * 16-bit texture without Alpha channel + */ + RGB565 = GFXFormat.R5G6B5, + /** + * 16-bit textures: RGB5A1 + */ + RGB5A1 = GFXFormat.RGB5A1, + /** + * 16-bit textures: RGBA4444 + */ + RGBA4444 = GFXFormat.RGBA4, + /** + * 24-bit texture: RGB888 + */ + RGB888 = GFXFormat.RGB8, + /** + * 32-bit texture: RGBA8888 + */ + RGBA8888 = GFXFormat.RGBA8, + /** + * 32-bit float texture: RGBA32F + */ + RGBA32F = GFXFormat.RGBA32F, + /** + * 8-bit textures used as masks + */ + A8 = GFXFormat.A8, + /** + * 8-bit intensity texture + */ + I8 = GFXFormat.L8, + /** + * 16-bit textures used as masks + */ + AI8 = GFXFormat.LA8, + /** + * rgb 2 bpp pvrtc + */ + RGB_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGB2, + /** + * rgba 2 bpp pvrtc + */ + RGBA_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGBA2, + /** + * rgb 4 bpp pvrtc + */ + RGB_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGB4, + /** + * rgba 4 bpp pvrtc + */ + RGBA_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGBA4, +} +ccenum(PixelFormat); + +function toGfxFormat (pixelFormat: PixelFormat) { + return pixelFormat as unknown as GFXFormat; +} + +/** + * The texture wrap mode. + * @enum {number} + */ +export enum WrapMode { + /** + * Specifies that the repeat warp mode will be used. + */ + REPEAT = GFXAddress.WRAP, + /** + * Specifies that the clamp to edge warp mode will be used. + */ + CLAMP_TO_EDGE = GFXAddress.CLAMP, + /** + * Specifies that the mirrored repeat warp mode will be used. + */ + MIRRORED_REPEAT = GFXAddress.MIRROR, + /** + * Specifies that the clamp to border wrap mode will be used. + */ + CLAMP_TO_BORDER = GFXAddress.BORDER, +} +ccenum(WrapMode); + +function toGfxAddressMode (wrapMode: WrapMode) { + return wrapMode as unknown as GFXAddress; +} + +/** + * The texture filter mode + * @enum {number} + */ +export enum Filter { + /** + * Specifies linear filtering. + */ + LINEAR = GFXFilter.LINEAR, + /** + * Specifies nearest filtering. + */ + NEAREST = GFXFilter.POINT, +} +ccenum(Filter); + +function toGfxFilterMode (filter: Filter) { + return filter as unknown as GFXFilter; +} + +@ccclass('cc.TextureBase') +export class TextureBase extends Asset { + + /** + * !#en + * Texture width, in pixels. + * For 2D texture, the width of texture is equal to its very first mipmap's width; + * For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width. + * !#zh + * 贴图像素宽度 + */ + public get width (): number { + return this._texture ? this._texture.width : 0; + } + + /** + * !#en + * Texture height, in pixels. + * For 2D texture, the height of texture is equal to its very first mipmap's height; + * For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height. + * !#zh + * 贴图像素高度 + */ + public get height (): number { + return this._texture ? this._texture.height : 0; + } + + public static PixelFormat = PixelFormat; + + public static WrapMode = WrapMode; + + public static Filter = Filter; + + /** + * + * @param texture + */ + public static _isCompressed (texture: TextureBase) { + return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1; + } + + protected _texture: GFXTexture | null = null; + + protected _textureView: GFXTextureView | null = null; + + private _potientialWidth: number = 0; + + private _potientialHeight: number = 0; + + private _mipmapLevel: number = 1; + + @property + private _genMipmap = false; + + @property + private _format: PixelFormat = PixelFormat.RGBA8888; + + @property + private _premultiplyAlpha = false; + + @property + private _flipY = false; + + @property + private _minFilter = Filter.LINEAR; + + @property + private _magFilter = Filter.LINEAR; + + @property + private _mipFilter = Filter.LINEAR; + + @property + private _wrapS: WrapMode = WrapMode.CLAMP_TO_EDGE; + + @property + private _wrapT: WrapMode = WrapMode.CLAMP_TO_EDGE; + + @property + private _anisotropy = 1; + + private _sampler: GFXSampler | null = null; + + private _id: string; + + protected constructor (flipY: boolean = false) { + super(); + // @ts-ignore + EventTarget.call(this); + + this._flipY = flipY; + + // Id for generate hash in material + this._id = idGenerator.getNewId(); + + /** + * !#en + * Whether the texture is loaded or not + * !#zh + * 贴图是否已经成功加载 + * @property loaded + * @type {Boolean} + */ + // @ts-ignore + this.loaded = false; + } + + public create (width: number, height: number, format = PixelFormat.RGBA8888, mipmapLevel = 1) { + this._potientialWidth = width; + this._potientialHeight = height; + this._format = format; + this._mipmapLevel = mipmapLevel; + this._updateSampler(); + this._recreateTexture(); + } + + /** + * Gets the underlying texture object. + * @deprecated Use getGfxTexture() instead. + */ + public getImpl () { + return this._texture; + } + + public getId () { + return this._id; + } + + /** + * !#en + * Pixel format of the texture. + * !#zh 获取纹理的像素格式。 + * @return + */ + public getPixelFormat () { + // support only in WebGl rendering mode + return this._format; + } + + /** + * !#en + * Whether or not the texture has their Alpha premultiplied. + * !#zh 检查纹理在上传 GPU 时预乘选项是否开启。 + * @return + */ + public hasPremultipliedAlpha () { + return this._premultiplyAlpha || false; + } + + /** + * !#en Anisotropy of the texture. + * !#zh 获取纹理的各向异性。 + * @return + */ + public getAnisotropy () { + return this._anisotropy; + } + + /** + * !#en + * Whether or not to generate mipmap. + * !#zh 检查纹理在上传 GPU 时是否生成 mipmap。 + * @return + */ + public genMipmap () { + return this._genMipmap || false; + } + + /** + * !#en Sets the wrap s and wrap t options.
+ * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. + * !#zh 设置纹理包装模式。 + * 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。 + * @param wrapS + * @param wrapT + */ + public setWrapMode (wrapS: WrapMode, wrapT: WrapMode) { + if (this._wrapS !== wrapS || this._wrapT !== wrapT) { + this._wrapS = wrapS; + this._wrapT = wrapT; + this._updateSampler(); + } + } + + /** + * !#en Sets the minFilter and magFilter options + * !#zh 设置纹理贴图缩小和放大过滤器算法选项。 + * @param minFilter + * @param magFilter + */ + public setFilters (minFilter: Filter, magFilter: Filter) { + if (this._minFilter !== minFilter || this._magFilter !== magFilter) { + this._minFilter = minFilter; + this._magFilter = magFilter; + this._updateSampler(); + } + } + + /** + * !#en Sets the mipFilter options + * !#zh 设置纹理Mipmap过滤算法选项。 + * @param mipFilter + */ + public setMipFilter (mipFilter: Filter) { + if (this._mipFilter !== mipFilter) { + this._mipFilter = mipFilter; + this._updateSampler(); + } + } + + /** + * !#en + * Sets the flipY options + * !#zh 设置贴图的纵向翻转选项。 + * @param flipY + */ + public setFlipY (flipY: boolean) { + if (this._flipY !== flipY) { + this._flipY = flipY; + this._updateSampler(); + } + } + + /** + * !#en + * Sets the premultiply alpha options + * !#zh 设置贴图的预乘选项。 + * @param premultiply + */ + public setPremultiplyAlpha (premultiply: boolean) { + if (this._premultiplyAlpha !== premultiply) { + this._premultiplyAlpha = premultiply; + this._updateSampler(); + } + } + + /** + * !#en Sets the anisotropy of the texture + * !#zh 设置贴图的各向异性。 + * @param anisotropy + */ + public setAnisotropy (anisotropy: number) { + if (this._anisotropy !== anisotropy) { + this._anisotropy = anisotropy; + this._updateSampler(); + } + } + + /** + * !#en + * Sets whether generate mipmaps for the texture + * !#zh 是否为纹理设置生成 mipmaps。 + * @param mipmap + */ + public setGenMipmap (mipmap: boolean) { + if (this._genMipmap !== mipmap) { + this._genMipmap = mipmap; + this._updateSampler(); + } + } + + public destroy () { + this._destroyTexture(); + + if (this._sampler) { + this._sampler.destroy(); + } + + return true; + } + + public getGFXTexture () { + return this._texture; + } + + public getGFXTextureView () { + return this._textureView; + } + + public getGFXSampler () { + return this._sampler; + } + + // SERIALIZATION + + /** + * @return + */ + public _serialize (): any { + return this._minFilter + ',' + this._magFilter + ',' + + this._wrapS + ',' + this._wrapT + ',' + + (this._premultiplyAlpha ? 1 : 0) + ',' + + this._mipFilter + ',' + this._anisotropy + ',' + + (this._flipY ? 1 : 0) + ',' + + (this._genMipmap ? 1 : 0); + } + + /** + * + * @param data + */ + public _deserialize (serializedData: any, handle: any) { + const data = serializedData as string; + const fields = data.split(','); + fields.unshift(''); + if (fields.length >= 6) { + // decode filters + this._minFilter = parseInt(fields[1], undefined); + this._magFilter = parseInt(fields[2], undefined); + // decode wraps + this._wrapS = parseInt(fields[3], undefined); + this._wrapT = parseInt(fields[4], undefined); + // decode premultiply alpha + this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1; + } + if (fields.length >= 8) { + this._mipFilter = parseInt(fields[6], undefined); + this._anisotropy = parseInt(fields[7], undefined); + } + if (fields.length >= 10) { + this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1; + this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1; + } + } + + public onLoaded () { + this._updateSampler(); + this._recreateTexture(); + } + + protected _getGlobalDevice (): GFXDevice | null { + // @ts-ignore + return cc.director.root.device; + } + + protected _getGfxFormat () { + return toGfxFormat(this._format); + } + + protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) { + const upload = () => { + if (!image.data) { + return; + } + let source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer; + if (image.data instanceof HTMLElement) { + source = image.data; + } else { + source = image.data.buffer; + } + this._uploadData(source, level, arrayIndex); + }; + // @ts-ignore + if (image.loaded) { + upload(); + } else { + // @ts-ignore + image.addEventListener('load', () => { + upload(); + }); + } + } + + protected _uploadData ( + source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer, level: number, arrayIndex?: number) { + if (!this._texture) { + return; + } + + if (level >= this._texture.mipLevel) { + return; + } + + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + const region: GFXBufferTextureCopy = { + buffOffset: 0, + buffStride: 0, + buffTexHeight: 0, + texOffset: { + x: 0, + y: 0, + z: 0, + }, + texExtent: { + width: this._texture.width, + height: this._texture.height, + depth: 1, + }, + texSubres: { + baseMipLevel: level, + levelCount: 1, + baseArrayLayer: arrayIndex || 0, + layerCount: 1, + }, + }; + + if (source instanceof HTMLElement) { + gfxDevice.copyImageSourceToTexture(source, this._texture, [region]); + } else { + gfxDevice.copyBufferToTexture(source, this._texture, [region]); + } + } + + protected _getTextureCreateInfo (): IGFXTextureInfo { + return { + type: GFXTextureType.TEX2D, + usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, + format: toGfxFormat(this._format), + width: this._potientialWidth, + height: this._potientialHeight, + mipLevel: this._mipmapLevel, + flags: this._genMipmap ? GFXTextureFlagBit.GEN_MIPMAP : GFXTextureFlagBit.NONE, + }; + } + + protected _getTextureViewCreateInfo (): IGFXTextureViewInfo { + return { + texture: this._texture!, + type: GFXTextureViewType.TV2D, + format: this._getGfxFormat(), + }; + } + + protected _recreateTexture () { + this._destroyTexture(); + + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + this._texture = gfxDevice.createTexture(this._getTextureCreateInfo()); + + this._textureView = gfxDevice.createTextureView(this._getTextureViewCreateInfo()); + } + + private _destroyTexture () { + if (this._textureView) { + this._textureView.destroy(); + this._textureView = null; + } + + if (this._texture) { + this._texture.destroy(); + this._texture = null; + } + } + + private _updateSampler () { + if (this._sampler) { + this._sampler.destroy(); + } + + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + this._sampler = gfxDevice.createSampler({ + name: `Sampler of ${this.name}`, + minFilter: toGfxFilterMode(this._minFilter), + magFilter: toGfxFilterMode(this._magFilter), + addressU: toGfxAddressMode(this._wrapS), + addressV: toGfxAddressMode(this._wrapT), + maxAnisotropy: this._anisotropy, + }); + } +} + +/* tslint:disable:no-string-literal */ +cc['TextureBase'] = TextureBase; + +/** + * !#zh + * 当该资源加载成功后触发该事件 + * !#en + * This event is emitted when the asset is loaded + * + * @event load + */ + +addon(TextureBase.prototype, EventTarget.prototype); diff --git a/cocos/assets/texture-util.js b/cocos/assets/texture-util.js index 35d75a2fe3..0278ade825 100644 --- a/cocos/assets/texture-util.js +++ b/cocos/assets/texture-util.js @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ -import ImageAsset from './image-asset'; -import Texture2D from './texture-2d'; +import { ImageAsset } from './image-asset'; +import { Texture2D } from './texture-2d'; /** * cc.textureUtil is a singleton object, it can load cc.Texture2D asynchronously diff --git a/cocos/audio/CCAudioSource.js b/cocos/audio/CCAudioSource.js index ff525592d9..fd49ab31bd 100644 --- a/cocos/audio/CCAudioSource.js +++ b/cocos/audio/CCAudioSource.js @@ -24,9 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -const misc = require('../utils/misc'); -const Component = require('./CCComponent'); -const AudioClip = require('../assets/CCAudioClip'); +import * as misc from '../core/utils/misc'; +import { Component } from './component'; +import AudioClip from '../assets/CCAudioClip'; /** * !#en Audio Source. diff --git a/cocos/camera/CCCamera.js b/cocos/camera/CCCamera.js index 6c8c05e592..bafb0e903f 100644 --- a/cocos/camera/CCCamera.js +++ b/cocos/camera/CCCamera.js @@ -24,14 +24,14 @@ THE SOFTWARE. ****************************************************************************/ -import game from '../core/CCGame'; +import game from '../core/game'; import AffineTrans from '../core/value-types/affine-transform'; import mat4 from '../core/vmath/mat4'; import vec2 from '../core/vmath/vec2'; import vec3 from '../core/vmath/vec3'; -import Component from '../components/CCComponent'; +import { Component } from '../components/component'; // TODO fix import from renderer -import {default as Renderer_Camera} from '../renderer/scene/camera'; +import { Camera as Renderer_Camera} from '../renderer/scene/camera'; import {default as Renderer_View} from '../renderer/core/view'; import {ccclass, property, executeInEditMode, menu, inspector} from '../core/data/class-decorator'; diff --git a/cocos/components/WXSubContextView.js b/cocos/components/WXSubContextView.js index 183c617e2a..cf1fc17dd2 100644 --- a/cocos/components/WXSubContextView.js +++ b/cocos/components/WXSubContextView.js @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ -const Component = require('./CCComponent'); -const ImageAsset = require('../assets/image-asset'); +import { Component } from './component'; +const { ImageAsset } = require('../assets/image-asset'); let WXSubContextView; @@ -37,7 +37,7 @@ if (!CC_EDITOR && !CC_WECHATGAME) { else { /** * !#en WXSubContextView is a view component which controls open data context viewport in Wechat game platform.
- * The component's node size decide the viewport of the sub context content in main context, + * The component's node size decide the viewport of the sub context content in main context, * the entire sub context texture will be scaled to the node's bounding box area.
* This component provides multiple important features:
* 1. Sub context could use its own resolution size and policy.
@@ -45,7 +45,7 @@ else { * 3. Resolution of sub context content could be increased.
* 4. User touch input is transformed to the correct viewport.
* 5. Texture update is handled by this component. User don't need to worry.
- * One important thing to be noted, whenever the node's bounding box change, + * One important thing to be noted, whenever the node's bounding box change, * you need to manually reset the viewport of sub context using updateSubContextViewport. * !#zh WXSubContextView 可以用来控制微信小游戏平台开放数据域在主域中的视窗的位置。
* 这个组件的节点尺寸决定了开放数据域内容在主域中的尺寸,整个开放数据域会被缩放到节点的包围盒范围内。
@@ -134,4 +134,4 @@ else { } -cc.WXSubContextView = module.exports = WXSubContextView; \ No newline at end of file +cc.WXSubContextView = module.exports = WXSubContextView; diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts new file mode 100644 index 0000000000..c8cbc9b011 --- /dev/null +++ b/cocos/components/component.d.ts @@ -0,0 +1,56 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 { CCObject } from '../core/data/object'; +import { getClassName, value } from '../core/utils/js'; +import IDGenerator from '../core/utils/id-generator'; +import { ccclass, property } from '../core/data/class-decorator'; +import { Node } from '../scene-graph'; +import { RenderScene } from '../renderer/scene/render-scene'; + +export class Component extends CCObject { + node: Node; + uuid: string; + enabled: boolean; + enabledInHierarchy: boolean; + + public constructor(); + + protected _getRenderScene (): RenderScene; + public addComponent (typeOrClassName: string | (new () => T)): T; + public getComponent (typeOrClassName: string | (new () => T)): T; + public getComponents (typeOrClassName: string | (new () => T)): T[]; + public getComponentInChildren (typeOrClassName: string | (new () => T)): T; + public getComponentsInChildren (typeOrClassName: string | (new () => T)): T[]; + public schedule (callback: Function, interval: number, repeat: number, delay: number): void; + public scheduleOnce (callback: Function, delay: number): void; + public unschedule (callback: Function): void; + public unscheduleAllCallbacks (): void; + + // friend to class BaseNode + public _id: string; + public _enabled: boolean; +} diff --git a/cocos/components/CCComponent.js b/cocos/components/component.js similarity index 98% rename from cocos/components/CCComponent.js rename to cocos/components/component.js index ad5e99f5c0..867c106ea6 100644 --- a/cocos/components/CCComponent.js +++ b/cocos/components/component.js @@ -24,10 +24,11 @@ THE SOFTWARE. ****************************************************************************/ -import CCObject from '../core/data/object'; +import { CCObject } from '../core/data/object'; import {getClassName, value} from '../core/utils/js'; import IDGenerator from '../core/utils/id-generator'; import {ccclass, property} from '../core/data/class-decorator'; +import {Script} from '../assets'; let idGenerator = new IDGenerator('Comp'); const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; @@ -102,10 +103,10 @@ class Component extends CCObject { @property({ displayName: 'Script', - type: cc._Script, + type: Script, tooltip: CC_DEV && 'i18n:INSPECTOR.component.script' }) - get __scriptAsset () {} + get __scriptAsset () { return null; } //set __scriptAsset (value) { // if (this.__scriptUuid !== value) { // if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) { @@ -177,7 +178,7 @@ class Component extends CCObject { visible: false }) get enabledInHierarchy () { - return (this._objFlags & IsOnEnableCalled) > 0; + return this._enabled && this.node._activeInHierarchy; } /** @@ -195,6 +196,10 @@ class Component extends CCObject { static system = null; + _getRenderScene() { + return this.node._scene._renderScene; + } + constructor () { super(); if (CC_EDITOR) { @@ -718,4 +723,4 @@ value(Component, '_registerEditorProps', function (cls, props) { Component.prototype.__scriptUuid = ''; cc.Component = Component; -export default Component; \ No newline at end of file +export { Component }; diff --git a/cocos/components/index.js b/cocos/components/index.js index 8f1c1b533c..0e9980ec24 100644 --- a/cocos/components/index.js +++ b/cocos/components/index.js @@ -24,7 +24,6 @@ THE SOFTWARE. ****************************************************************************/ -export {default as Component} from './CCComponent'; +export {Component} from './component'; export {default as EventHandler} from './CCComponentEventHandler'; export {default as MissingScript} from './missing-script'; -export {default as Canvas} from './CCCanvas'; \ No newline at end of file diff --git a/cocos/components/missing-script.js b/cocos/components/missing-script.js index 6dae7bc849..4ee8d0ceab 100644 --- a/cocos/components/missing-script.js +++ b/cocos/components/missing-script.js @@ -26,7 +26,7 @@ import {_getClassById} from '../core/utils/js'; import {BUILTIN_CLASSID_RE} from '../core/utils/misc'; -import Component from './CCComponent'; +import { Component } from './component'; import {ccclass, property, inspector} from '../core/data/class-decorator'; /* @@ -48,7 +48,7 @@ class MissingClass { @ccclass('cc.MissingScript') @inspector('packages://inspector/inspectors/comps/missing-script.js') export default class MissingScript extends Component { - + //_scriptUuid: { // get: function () { // var id = this._$erialized.__type__; diff --git a/cocos/core/data/class.js b/cocos/core/data/class.js index 503a106fa0..cfac3fc81d 100644 --- a/cocos/core/data/class.js +++ b/cocos/core/data/class.js @@ -144,7 +144,7 @@ function defineProp (cls, className, propName, val, es6) { appendProp(cls, propName); // apply attributes - var attrs = parseAttributes(cls, val, className, propName, false); + var attrs = parseAttributes(cls, val, className, propName, false); if (attrs) { var onAfterProp = tmpArray; for (var i = 0; i < attrs.length; i++) { @@ -1240,4 +1240,4 @@ CCClass.escapeForJS = escapeForJS; CCClass.IDENTIFIER_RE = IDENTIFIER_RE; CCClass.getNewValueTypeCode = CC_SUPPORT_JIT && getNewValueTypeCodeJit; -cc.Class = CCClass; \ No newline at end of file +cc.Class = CCClass; diff --git a/cocos/core/data/index.js b/cocos/core/data/index.js index 25869cc301..8ae9b09a7b 100644 --- a/cocos/core/data/index.js +++ b/cocos/core/data/index.js @@ -27,6 +27,6 @@ import * as _decorator from './class-decorator'; cc._decorator = _decorator; export { _decorator }; export { default as CCClass } from './class'; -export { default as CCObject } from './object'; +export { CCObject } from './object'; export { default as deserialize } from './deserialize'; export { default as instantiate } from './instantiate'; diff --git a/cocos/core/data/instantiate-jit.js b/cocos/core/data/instantiate-jit.js index 4b1b0435f3..5a92e17733 100644 --- a/cocos/core/data/instantiate-jit.js +++ b/cocos/core/data/instantiate-jit.js @@ -28,7 +28,7 @@ import * as js from '../utils/js'; import CCClass from './class'; -import CCObject from './object'; +import { CCObject } from './object'; import * as Attr from './utils/attribute'; import {flattenCodeArray} from './utils/compiler'; diff --git a/cocos/core/data/instantiate.js b/cocos/core/data/instantiate.js index 2a978447f0..f86904a04e 100644 --- a/cocos/core/data/instantiate.js +++ b/cocos/core/data/instantiate.js @@ -24,9 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -import CCObject from './object'; -import ValueType from '../value-types/value-type'; -import {isDomNode} from '../utils/misc'; +import { CCObject } from './object'; +import { ValueType } from '../value-types/value-type'; +import { isDomNode } from '../utils/misc'; const Destroyed = CCObject.Flags.Destroyed; const PersistentMask = CCObject.Flags.PersistentMask; diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts new file mode 100644 index 0000000000..96b70896d5 --- /dev/null +++ b/cocos/core/data/object.d.ts @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ + +export class CCObject { + protected static _deferredDestroy(): void; + protected _name: string; + protected _objFlags: number; + + public constructor(name?: string); + + public name: string; + public isValid: boolean; + public isRealValid: boolean; + + public destroy(): any; + public realDestroyInEditor(): void; + public _clearDeferredDestroyTimer(): void; + + protected _destruct(): void; + protected _destroyImmediate(): void; + + protected _serialize?(exporting?: any): any; + protected _deserialize?(data: any, ctx: any): any; + protected _onPreDestroy (): any; + protected Flags: object; +} diff --git a/cocos/core/data/object.js b/cocos/core/data/object.js index 77811fee5b..28f6d03d37 100644 --- a/cocos/core/data/object.js +++ b/cocos/core/data/object.js @@ -536,4 +536,4 @@ if (CC_EDITOR || CC_TEST) { } cc.Object = CCObject; -export default CCObject; +export { CCObject }; diff --git a/cocos/core/CCDirector.js b/cocos/core/director.js similarity index 97% rename from cocos/core/CCDirector.js rename to cocos/core/director.js index 9fd24790a6..d701c45a1c 100644 --- a/cocos/core/CCDirector.js +++ b/cocos/core/director.js @@ -27,17 +27,16 @@ import EventTarget from './event/event-target'; import eventManager from './platform/event-manager/CCEventManager'; -import ccobject from './data/object'; -import game from './CCGame'; -import Scheduler from './CCScheduler'; +import { CCObject } from './data/object'; +import game from './game'; +import Scheduler from './scheduler'; import { autoRelease } from '../load-pipeline/auto-release-utils'; import ComponentScheduler from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; -// import AnimationSystem from '../3d/framework/animation-system'; // import SkinningModelSystem from '../3d/framework/skinning-model-system'; -import RenderSystem from '../3d/framework/render-system'; import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; +import { Root } from './root'; // const ComponentScheduler = require('./component-scheduler'); // const NodeActivator = require('./node-activator'); @@ -122,6 +121,9 @@ class Director extends EventTarget { // purge? this._purgeDirectorInNextLoop = false; + // root + this._root = null; + // scenes this._loadingScene = ''; this._scene = null; @@ -156,6 +158,13 @@ class Director extends EventTarget { } init () { + + this._root = new Root(game._gfxDevice); + let rootInfo = {}; + if(!this._root.initialize(rootInfo)) { + return false; + } + this._totalFrames = 0; this._lastUpdate = performance.now(); this._paused = false; @@ -184,6 +193,7 @@ class Director extends EventTarget { // this.registerSystem('animation', AnimationSystem, ['AnimationComponent'], 200); // this.registerSystem('skinning-model', SkinningModelSystem, ['SkinningModelComponent'], 100); // init renderSystem + /* { this._renderSystem = new RenderSystem(); let renderComps = ['cc.CameraComponent']; @@ -191,6 +201,7 @@ class Director extends EventTarget { getClassByName(compName).system = this._renderSystem; }); } + */ { this._physicsSystem = new PhysicsSystem(); @@ -216,7 +227,7 @@ class Director extends EventTarget { * !#en * Converts a view coordinate to an WebGL coordinate
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape)
- * Implementation can be found in CCDirectorWebGL. + * Implementation can be found in directorWebGL. * !#zh 将触摸点的屏幕坐标转换为 WebGL View 下的坐标。 * @method convertToGL * @param {Vec2} uiPoint @@ -238,7 +249,7 @@ class Director extends EventTarget { * !#en * Converts an OpenGL coordinate to a view coordinate
* Useful to convert node points to window points for calls such as glScissor
- * Implementation can be found in CCDirectorWebGL. + * Implementation can be found in directorWebGL. * !#zh 将触摸点的 WebGL View 坐标转换为屏幕坐标。 * @method convertToUI * @param {Vec2} glPoint @@ -349,6 +360,9 @@ class Director extends EventTarget { this.stopAnimation(); + this._root.destroy(); + this._root = null; + // Clear all caches cc.loader.releaseAll(); } @@ -424,7 +438,7 @@ class Director extends EventTarget { this._scene = null; // purge destroyed nodes belongs to old scene - ccobject._deferredDestroy(); + CCObject._deferredDestroy(); CC_BUILD && CC_DEBUG && console.timeEnd('Destroy'); if (onBeforeLoadScene) { @@ -664,7 +678,7 @@ class Director extends EventTarget { /** * !#en * Enables or disables WebGL depth test.
- * Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js + * Implementation can be found in directorCanvas.js/directorWebGL.js * !#zh 启用/禁用深度测试(在 Canvas 渲染模式下不会生效)。 * @method setDepthTest * @param {Boolean} on @@ -680,7 +694,7 @@ class Director extends EventTarget { /** * !#en * Set color for clear screen.
- * (Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js) + * (Implementation can be found in directorCanvas.js/directorWebGL.js) * !#zh * 设置场景的默认擦除颜色。
* 支持全透明,但不支持透明度为中间值。要支持全透明需手工开启 cc.macro.ENABLE_TRANSPARENT_CANVAS。 @@ -695,6 +709,10 @@ class Director extends EventTarget { cc.Camera.main.backgroundColor = clearColor; } + get root() { + return this._root; + } + /** * !#en Returns current logic Scene. * !#zh 获取当前逻辑场景。 @@ -896,17 +914,17 @@ class Director extends EventTarget { // User can use this event to do things after update this.emit(cc.Director.EVENT_AFTER_UPDATE); // Destroy entities that have been removed recently - ccobject._deferredDestroy(); + CCObject._deferredDestroy(); } - // Render this._physicsSystem.update(this._deltaTime); + this.emit(cc.Director.EVENT_BEFORE_DRAW); - this._renderSystem.update(this._deltaTime); - // After draw + this._root.frameMove(this._deltaTime); // Render this.emit(cc.Director.EVENT_AFTER_DRAW); eventManager.frameUpdateListeners(); + if (this._scene) { this._scene.resetHasChanged(); } this._totalFrames++; } } diff --git a/cocos/core/event/callbacks-invoker-base.ts b/cocos/core/event/callbacks-invoker-base.ts new file mode 100644 index 0000000000..a9a871de01 --- /dev/null +++ b/cocos/core/event/callbacks-invoker-base.ts @@ -0,0 +1,241 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 * as js from '../utils/js'; +const fastRemoveAt = js.array.fastRemoveAt; + +type Constructor = new (...args: any[]) => T; + +class CallbackList { + public callbacks: Array = []; + + public targets: Array = []; // same length with callbacks, nullable + + public isInvoking = false; + + public containCanceled = false; + + public removeBy (array, value) { + const callbacks = this.callbacks; + const targets = this.targets; + for (let i = 0; i < array.length; ++i) { + if (array[i] === value) { + fastRemoveAt(callbacks, i); + fastRemoveAt(targets, i); + --i; + } + } + } + + public cancel (index: number) { + this.callbacks[index] = this.targets[index] = null; + this.containCanceled = true; + } + + public cancelAll () { + const callbacks = this.callbacks; + const targets = this.targets; + for (let i = 0; i < callbacks.length; i++) { + callbacks[i] = targets[i] = null; + } + this.containCanceled = true; + } + + // filter all removed callbacks and compact array + public purgeCanceled () { + this.removeBy(this.callbacks, null); + this.containCanceled = false; + } +} + +const MAX_SIZE = 16; +const callbackListPool = new js.Pool((list: CallbackList) => { + list.callbacks.length = 0; + list.targets.length = 0; + list.isInvoking = false; + list.containCanceled = false; +}, MAX_SIZE); +callbackListPool.get = function () { + return this._get() || new CallbackList(); +}; + +interface ICallbackTable { + [x: string]: CallbackList | undefined; +} + +/** + * The CallbacksHandler is an abstract class that can register and unregister callbacks by key. + * Subclasses should implement their own methods about how to invoke the callbacks. + * @private + */ +export class CallbacksHandler { + protected _callbackTable: ICallbackTable = js.createMap(true); + + /** + * @param key + * @param callback + * @param [target] - can be null + */ + public add (key: string, callback: Function, target: object | null = null) { + let list = this._callbackTable[key]; + if (!list) { + list = this._callbackTable[key] = callbackListPool.get() as CallbackList; + } + list.callbacks.push(callback); + list.targets.push(target || null); + } + + /** + * Check if the specified key has any registered callback. If a callback is also specified, + * it will only return true if the callback is registered. + * @param key + * @param [callback] + * @param [target] + */ + public hasEventListener (key: string, callback?: Function, target: Object | null = null) { + const list = this._callbackTable[key]; + if (!list) { + return false; + } + + // check any valid callback + const callbacks = list.callbacks; + if (!callback) { + // Make sure no cancelled callbacks + if (list.isInvoking) { + for (const cb of callbacks) { + if (cb) { + return true; + } + } + return false; + } else { + return callbacks.length > 0; + } + } + + target = target || null; + const targets = list.targets; + for (let i = 0; i < callbacks.length; ++i) { + if (callbacks[i] === callback && targets[i] === target) { + return true; + } + } + return false; + } + + /** + * Removes all callbacks registered in a certain event type or all callbacks registered with a certain target + * @param keyOrTarget - The event key to be removed or the target to be removed + */ + public removeAll (keyOrTarget?: string | object) { + if (typeof keyOrTarget === 'string') { + // remove by key + const list = this._callbackTable[keyOrTarget]; + if (list) { + if (list.isInvoking) { + list.cancelAll(); + } else { + callbackListPool.put(list); + delete this._callbackTable[keyOrTarget]; + } + } + } else if (keyOrTarget) { + // remove by target + for (const key in this._callbackTable) { + if (this._callbackTable.hasOwnProperty(key)) { + const list = this._callbackTable[key]!; + if (list.isInvoking) { + const targets = list.targets; + for (let i = 0; i < targets.length; ++i) { + if (targets[i] === keyOrTarget) { + list.cancel(i); + } + } + } else { + list.removeBy(list.targets, keyOrTarget); + } + } + } + } + } + + public remove (key: string, callback: Function, target: Object | null = null) { + const list = this._callbackTable[key]; + if (!list) { + return; + } + target = target || null; + const { callbacks, targets } = list; + for (let i = 0; i < callbacks.length; ++i) { + if (callbacks[i] === callback && targets[i] === target) { + if (list.isInvoking) { + list.cancel(i); + } else { + fastRemoveAt(callbacks, i); + fastRemoveAt(targets, i); + } + break; + } + } + } +} + +/** + * !#en The callbacks invoker to handle and invoke callbacks by key. + * !#zh CallbacksInvoker 用来根据 Key 管理并调用回调方法。 + */ +export class CallbacksInvoker extends CallbacksHandler { + public invoke (key: string, ...args: any[]) { + const list = this._callbackTable[key]; + if (!list) { + return; + } + const rootInvoker = !list.isInvoking; + list.isInvoking = true; + + const { callbacks, targets } = list; + for (let i = 0, len = callbacks.length; i < len; ++i) { + const callback = callbacks[i]; + if (!callback) { + continue; + } + const target = targets[i]; + if (target) { + callback.call(target, ...args); + } else { + callback(...args); + } + } + + if (rootInvoker) { + list.isInvoking = false; + if (list.containCanceled) { + list.purgeCanceled(); + } + } + } +} diff --git a/cocos/core/event/event-target-base.ts b/cocos/core/event/event-target-base.ts new file mode 100644 index 0000000000..d080cc005d --- /dev/null +++ b/cocos/core/event/event-target-base.ts @@ -0,0 +1,177 @@ +import * as js from '../utils/js'; +import { CallbacksInvoker } from './callbacks-invoker-base'; +import Event from './event'; + +const fastRemove = js.array.fastRemove; + +type Constructor = new(...args: any[]) => T; + +export type IEventTargetCallback = (...args: any[]) => void; + +class Empty {} + +export function EventTarget> (base: Base) { + class EventTarget extends base { + private _callbacksInvoker = new CallbacksInvoker(); + + /** + * !#en Checks whether the EventTarget object has any callback registered for a specific type of event. + * !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。 + * + * @param type - The type of event. + * @return True if a callback of the specified type is registered; false otherwise. + */ + public hasEventListener (type: string) { + return this._callbacksInvoker.hasEventListener(type); + } + + /** + * !#en + * Register an callback of a specific event type on the EventTarget. + * This type of event should be triggered via `emit`. + * !#zh + * 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。 + * + * @param type - A string representing the event type to listen for. + * @param callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param [target] - The target (this object) to invoke the callback, can be null + * @return - Just returns the incoming callback so you can save the anonymous function easier. + * @typescript + * on(type: string, callback: T, target?: any, useCapture?: boolean): T + * @example + * eventTarget.on('fire', function () { + * cc.log("fire in the hole"); + * }, node); + */ + public on (type: string, callback: IEventTargetCallback, target: Object | null = null, useCapture?: boolean) { + if (!callback) { + cc.errorID(6800); + return; + } + + if (!this._callbacksInvoker.hasEventListener(type, callback, target) ) { + this._callbacksInvoker.add(type, callback, target); + const targetImpl = (target as ITargetImpl); + if (target && targetImpl.__eventTargets) { + targetImpl.__eventTargets.push(this); + } + } + return callback; + } + + /** + * !#en + * Removes the listeners previously registered with the same type, callback, target and or useCapture, + * if only type is passed as parameter, all listeners registered with that type will be removed. + * !#zh + * 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 + * + * @param type - A string representing the event type being removed. + * @param [callback] - The callback to remove. + * @param [target] - The target (this object) to invoke the callback, + * if it's not given, only callback without target will be removed + * @example + * // register fire eventListener + * var callback = eventTarget.on('fire', function () { + * cc.log("fire in the hole"); + * }, target); + * // remove fire event listener + * eventTarget.off('fire', callback, target); + * // remove all fire event listeners + * eventTarget.off('fire'); + */ + public off (type: string, callback: IEventTargetCallback, target: Object | null = null) { + if (!callback) { + this._callbacksInvoker.removeAll(type); + } else { + this._callbacksInvoker.remove(type, callback, target); + const targetImpl = (target as ITargetImpl); + if (target && targetImpl.__eventTargets) { + fastRemove(targetImpl.__eventTargets, this); + } + } + } + + /** + * !#en Removes all callbacks previously registered with the same target (passed as parameter). + * This is not for removing all listeners in the current event target, + * and this is not for removing all listeners the target parameter have registered. + * It's only for removing all listeners (callback and target couple) + * registered on the current event target by the target parameter. + * !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 + * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 + * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 + * @param {Object} target - The target to be searched for all related listeners + */ + public targetOff (target: Object) { + this._callbacksInvoker.removeAll(); + } + + /** + * !#en + * Register an callback of a specific event type on the EventTarget, + * the callback will remove itself after the first time it is triggered. + * !#zh + * 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 + * + * @param type - A string representing the event type to listen for. + * @param callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param [target] - The target (this object) to invoke the callback, can be null + * @example + * eventTarget.once('fire', function () { + * cc.log("this is the callback and will be invoked only once"); + * }, node); + */ + public once (type: string, callback: IEventTargetCallback, target: Object | null = null) { + const eventType_hasOnceListener = '__ONCE_FLAG:' + type; + const hasOnceListener = this._callbacksInvoker.hasEventListener( + eventType_hasOnceListener, callback, target); + if (!hasOnceListener) { + const onceWrapper = (...args: any[]) => { + this.off(type, onceWrapper, target); + this._callbacksInvoker.remove(eventType_hasOnceListener, callback, target); + callback(...args); + }; + this.on(type, onceWrapper, target); + this._callbacksInvoker.add(eventType_hasOnceListener, callback, target); + } + } + + /** + * !#en + * Trigger an event directly with the event name and necessary arguments. + * !#zh + * 通过事件名发送自定义事件 + * + * @param type - event type + * @param args - arguments + * @example + * eventTarget.emit('fire', event); + * eventTarget.emit('fire', message, emitter); + */ + public emit (type: string, ...args: any[]) { + return this._callbacksInvoker.invoke(type, ...args); + } + + /** + * !#en + * Send an event with the event object. + * !#zh + * 通过事件对象派发事件 + * + * @param event + */ + public dispatchEvent (event: Event) { + return this._callbacksInvoker.invoke(event.type, event); + } + } + return EventTarget; +} + +interface ITargetImpl extends Object { + __eventTargets?: Object[]; +} + +export const DefaultEventTarget = EventTarget(Empty); diff --git a/cocos/core/event/event.js b/cocos/core/event/event.js deleted file mode 100644 index 12b5a4053a..0000000000 --- a/cocos/core/event/event.js +++ /dev/null @@ -1,269 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -/** - * !#en Base class of all kinds of events. - * !#zh 包含事件相关信息的对象。 - * @class Event - */ -class Event { - /** - * @method constructor - * @param {String} type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit" - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (type, bubbles) { - /** - * !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". - * !#zh 事件类型。 - * @property type - * @type {String} - */ - this.type = type; - - /** - * !#en Indicate whether the event bubbles up through the tree or not. - * !#zh 表示该事件是否进行冒泡。 - * @property bubbles - * @type {Boolean} - */ - this.bubbles = !!bubbles; - - /** - * !#en A reference to the target to which the event was originally dispatched. - * !#zh 最初事件触发的目标 - * @property target - * @type {Object} - */ - this.target = null; - - /** - * !#en A reference to the currently registered target for the event. - * !#zh 当前目标 - * @property currentTarget - * @type {Object} - */ - this.currentTarget = null; - - /** - * !#en - * Indicates which phase of the event flow is currently being evaluated. - * Returns an integer value represented by 4 constants: - * - Event.NONE = 0 - * - Event.CAPTURING_PHASE = 1 - * - Event.AT_TARGET = 2 - * - Event.BUBBLING_PHASE = 3 - * The phases are explained in the [section 3.1, Event dispatch and DOM event flow] - * (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. - * !#zh 事件阶段 - * @property eventPhase - * @type {Number} - */ - this.eventPhase = 0; - - /* - * Indicates whether or not event.stopPropagation() has been called on the event. - * @property _propagationStopped - * @type {Boolean} - * @private - */ - this._propagationStopped = false; - - /* - * Indicates whether or not event.stopPropagationImmediate() has been called on the event. - * @property _propagationImmediateStopped - * @type {Boolean} - * @private - */ - this._propagationImmediateStopped = false; - } - - /** - * !#en Reset the event for being stored in the object pool. - * !#zh 重置对象池中存储的事件。 - * @method unuse - * @returns {String} - */ - unuse () { - this.type = cc.Event.NO_TYPE; - this.target = null; - this.currentTarget = null; - this.eventPhase = cc.Event.NONE; - this._propagationStopped = false; - this._propagationImmediateStopped = false; - } - - /** - * !#en Reuse the event for being used again by the object pool. - * !#zh 用于对象池再次使用的事件。 - * @method reuse - * @returns {String} - */ - reuse (type, bubbles) { - this.type = type; - this.bubbles = bubbles || false; - } - - /** - * !#en Stops propagation for current event. - * !#zh 停止传递当前事件。 - * @method stopPropagation - */ - stopPropagation () { - this._propagationStopped = true; - } - - /** - * !#en Stops propagation for current event immediately, - * the event won't even be dispatched to the listeners attached in the current target. - * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 - * @method stopPropagationImmediate - */ - stopPropagationImmediate () { - this._propagationImmediateStopped = true; - } - - /** - * !#en Checks whether the event has been stopped. - * !#zh 检查该事件是否已经停止传递. - * @method isStopped - * @returns {Boolean} - */ - isStopped () { - return this._propagationStopped || this._propagationImmediateStopped; - } - - /** - * !#en - *

- * Gets current target of the event
- * note: It only be available when the event listener is associated with node.
- * It returns 0 when the listener is associated with fixed priority. - *

- * !#zh 获取当前目标节点 - * @method getCurrentTarget - * @returns {Node} The target with which the event associates. - */ - getCurrentTarget () { - return this.currentTarget; - } - - /** - * !#en Gets the event type. - * !#zh 获取事件类型 - * @method getType - * @returns {String} - */ - getType () { - return this.type; - } -} - -//event type -/** - * !#en Code for event without type. - * !#zh 没有类型的事件 - * @property NO_TYPE - * @static - * @type {string} - */ -Event.NO_TYPE = 'no_type'; - -/** - * !#en The type code of Touch event. - * !#zh 触摸事件类型 - * @property TOUCH - * @static - * @type {String} - */ -Event.TOUCH = 'touch'; -/** - * !#en The type code of Mouse event. - * !#zh 鼠标事件类型 - * @property MOUSE - * @static - * @type {String} - */ -Event.MOUSE = 'mouse'; -/** - * !#en The type code of Keyboard event. - * !#zh 键盘事件类型 - * @property KEYBOARD - * @static - * @type {String} - */ -Event.KEYBOARD = 'keyboard'; -/** - * !#en The type code of Acceleration event. - * !#zh 加速器事件类型 - * @property ACCELERATION - * @static - * @type {String} - */ -Event.ACCELERATION = 'acceleration'; - -//event phase -/** - * !#en Events not currently dispatched are in this phase - * !#zh 尚未派发事件阶段 - * @property NONE - * @type {Number} - * @static - */ -Event.NONE = 0; -/** - * !#en - * The capturing phase comprises the journey from the root to the last node before the event target's node - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 - * @property CAPTURING_PHASE - * @type {Number} - * @static - */ -Event.CAPTURING_PHASE = 1; -/** - * !#en - * The target phase comprises only the event target node - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 目标阶段仅包括事件目标节点。 - * @property AT_TARGET - * @type {Number} - * @static - */ -Event.AT_TARGET = 2; -/** - * !#en - * The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 - * @property BUBBLING_PHASE - * @type {Number} - * @static - */ -Event.BUBBLING_PHASE = 3; - -cc.Event = Event; -export default Event; \ No newline at end of file diff --git a/cocos/core/event/event.ts b/cocos/core/event/event.ts new file mode 100644 index 0000000000..01af21145a --- /dev/null +++ b/cocos/core/event/event.ts @@ -0,0 +1,222 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ + +/** + * !#en Base class of all kinds of events. + * !#zh 包含事件相关信息的对象。 + * @class Event + */ +export default class Event { + // Event types + + /** + * !#en Code for event without type. + * !#zh 没有类型的事件 + */ + public static NO_TYPE = 'no_type'; + + /** + * !#en The type code of Touch event. + * !#zh 触摸事件类型 + */ + public static TOUCH = 'touch'; + /** + * !#en The type code of Mouse event. + * !#zh 鼠标事件类型 + */ + public static MOUSE = 'mouse'; + /** + * !#en The type code of Keyboard event. + * !#zh 键盘事件类型 + */ + public static KEYBOARD = 'keyboard'; + /** + * !#en The type code of Acceleration event. + * !#zh 加速器事件类型 + */ + public static ACCELERATION = 'acceleration'; + + // Event phases + + /** + * !#en Events not currently dispatched are in this phase + * !#zh 尚未派发事件阶段 + */ + public static NONE = 0; + + /** + * !#en + * The capturing phase comprises the journey from the root to the last node before the event target's node + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 + */ + public static CAPTURING_PHASE = 1; + + /** + * !#en + * The target phase comprises only the event target node + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 目标阶段仅包括事件目标节点。 + */ + public static AT_TARGET = 2; + + /** + * !#en + * The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 + */ + public static BUBBLING_PHASE = 3; + + /** + * !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". + * !#zh 事件类型。 + */ + public type: string; + + /** + * !#en Indicate whether the event bubbles up through the tree or not. + * !#zh 表示该事件是否进行冒泡。 + */ + public bubbles: boolean; + + /** + * !#en A reference to the target to which the event was originally dispatched. + * !#zh 最初事件触发的目标 + */ + public target: Object | null = null; + + /** + * !#en A reference to the currently registered target for the event. + * !#zh 当前目标 + */ + public currentTarget: Object | null = null; + + /** + * !#en + * Indicates which phase of the event flow is currently being evaluated. + * Returns an integer value represented by 4 constants: + * - Event.NONE = 0 + * - Event.CAPTURING_PHASE = 1 + * - Event.AT_TARGET = 2 + * - Event.BUBBLING_PHASE = 3 + * The phases are explained in the [section 3.1, Event dispatch and DOM event flow] + * (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. + * !#zh 事件阶段 + */ + public eventPhase = 0; + + /* + * Indicates whether or not event.stopPropagation() has been called on the event. + */ + private _propagationStopped = false; + + /* + * Indicates whether or not event.stopPropagationImmediate() has been called on the event. + */ + private _propagationImmediateStopped = false; + + /** + * @param type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit" + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (type: string, bubbles?: boolean) { + this.type = type; + this.bubbles = !!bubbles; + } + + /** + * !#en Reset the event for being stored in the object pool. + * !#zh 重置对象池中存储的事件。 + */ + public unuse () { + this.type = Event.NO_TYPE; + this.target = null; + this.currentTarget = null; + this.eventPhase = Event.NONE; + this._propagationStopped = false; + this._propagationImmediateStopped = false; + } + + /** + * !#en Reuse the event for being used again by the object pool. + * !#zh 用于对象池再次使用的事件。 + */ + public reuse (type: string, bubbles?: boolean) { + this.type = type; + this.bubbles = bubbles || false; + } + + /** + * !#en Stops propagation for current event. + * !#zh 停止传递当前事件。 + */ + public stopPropagation () { + this._propagationStopped = true; + } + + /** + * !#en Stops propagation for current event immediately, + * the event won't even be dispatched to the listeners attached in the current target. + * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 + */ + public stopPropagationImmediate () { + this._propagationImmediateStopped = true; + } + + /** + * !#en Checks whether the event has been stopped. + * !#zh 检查该事件是否已经停止传递. + */ + public isStopped () { + return this._propagationStopped || this._propagationImmediateStopped; + } + + /** + * !#en + *

+ * Gets current target of the event
+ * note: It only be available when the event listener is associated with node.
+ * It returns 0 when the listener is associated with fixed priority. + *

+ * !#zh 获取当前目标节点 + * @returns The target with which the event associates. + */ + public getCurrentTarget () { + return this.currentTarget; + } + + /** + * !#en Gets the event type. + * !#zh 获取事件类型 + */ + public getType () { + return this.type; + } +} + +/* tslint:disable:no-string-literal */ +cc['Event'] = Event; diff --git a/cocos/core/CCGame.js b/cocos/core/game.js similarity index 98% rename from cocos/core/CCGame.js rename to cocos/core/game.js index f412383553..df7594afa4 100644 --- a/cocos/core/CCGame.js +++ b/cocos/core/game.js @@ -29,10 +29,6 @@ import inputManager from './platform/event-manager/CCInputManager'; import debug from './platform/CCDebug'; import { addon } from './utils/js'; -import { renderer } from '../renderer'; -import gfx from '../renderer/gfx'; -import builtinResMgr from '../3d/builtin/init'; - /** * @module cc */ @@ -127,6 +123,8 @@ var game = { _renderContext: null, + _gfxDevice: null, + _intervalId: null,//interval target of main _lastTime: null, @@ -341,6 +339,12 @@ var game = { * @method end */ end: function () { + + if(this._gfxDevice) { + this._gfxDevice.destroy(); + this._gfxDevice = null; + } + close(); }, @@ -364,8 +368,6 @@ var game = { // Init engine this._initEngine(); - this._initBuiltins(); - // Log engine version console.log('Cocos3D v' + cc.ENGINE_VERSION); @@ -765,17 +767,31 @@ var game = { { // todo, adjust opts here - let device = this._renderContext = new gfx.Device(localCanvas, {}); + + this._gfxDevice = new cc.WebGLGFXDevice; + this._gfxDevice.initialize({ + 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); + */ + + //this._renderer = new renderer.ForwardRenderer(device); } // renderer.initWebGL(localCanvas, opts); // this._renderContext = renderer.device._gl; } - if (!this._renderContext) { + + if (!this._gfxDevice) { + //if (!this._renderContext) { + // todo fix here for wechat game console.error('can not support canvas rendering in 3D'); this._renderer = null; @@ -795,14 +811,6 @@ var game = { this._rendererInitialized = true; }, - _initBuiltins: function() { - let builtins = builtinResMgr.initBuiltinRes(this._renderContext); - this._renderer.setBuiltins({ - defaultTexture: builtins['default-texture']._texture, - defaultTextureCube: builtins['default-texture-cube']._texture, - }); - }, - _initEvents: function () { var win = window, hiddenPropName; diff --git a/cocos/core/index.js b/cocos/core/index.js index 2541f653dd..3456282aa4 100644 --- a/cocos/core/index.js +++ b/cocos/core/index.js @@ -34,10 +34,10 @@ export * from './event'; export * from './platform'; export * from './value-types'; // Cause error: -// export * from './CCGame'; -import './CCGame'; -export * from './CCScheduler'; +// export * from './game'; +import './game'; +export * from './scheduler'; // Cause error: -// export * from './CCDirector'; -import './CCDirector'; -export { vmath }; \ No newline at end of file +// export * from './director'; +import './director'; +export { vmath }; diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts new file mode 100644 index 0000000000..5f7b7b4727 --- /dev/null +++ b/cocos/core/memop/cached-array.ts @@ -0,0 +1,53 @@ +export class CachedArray { + + public array: T[]; + public length: number = 0; + private cache: Array; + private _compareFn; + + constructor (length: number, compareFn?: (a: T, b: T) => number) { + this.array = new Array(length); + this.cache = this.array; + this.length = 0; + + if (compareFn !== undefined) { + this._compareFn = compareFn; + } else { + this._compareFn = (a: number, b: number) => a - b; + } + } + + public push (item: T) { + this.array[this.length++] = item; + } + + public pop (): T | undefined { + return this.array[this.length--]; + } + + public get (idx: number): T { + return this.array[idx]; + } + + public clear () { + this.cache.fill(null); + this.length = 0; + } + + public sort () { + this.array.length = this.length; + this.array.sort(this._compareFn); + } + + public concat (array: CachedArray) { + for (let i = 0; i < array.length; ++i) { + this.array[this.length++] = array.array[i]; + } + } + + public append (array: T[]) { + for (const item of array) { + this.array[this.length++] = item; + } + } +} diff --git a/cocos/core/platform/CCSys.js b/cocos/core/platform/CCSys.js index 82b19a521a..93e9339a54 100644 --- a/cocos/core/platform/CCSys.js +++ b/cocos/core/platform/CCSys.js @@ -527,6 +527,17 @@ sys.isNative = CC_JSB; */ sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !CC_WECHATGAME && !CC_QQPLAY && !CC_JSB; +/** + * Endianess of current platform + * @property {boolean} isLittleEndian + */ +sys.isLittleEndian = (() => { + const buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] === 256; +})(); + if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; sys.platform = sys.EDITOR_CORE; @@ -1011,10 +1022,13 @@ else { try { if (__audioSupport.WEB_AUDIO) { - __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); - if(__audioSupport.DELAY_CREATE_CTX) { - setTimeout(function(){ __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0); - } + __audioSupport._context = null; + Object.defineProperty(__audioSupport, 'context', { + get () { + if (this._context) return this._context; + return this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); + } + }); } } catch(error) { __audioSupport.WEB_AUDIO = false; @@ -1210,4 +1224,4 @@ sys.now = function () { cc.sys = sys; -export default sys; \ No newline at end of file +export default sys; diff --git a/cocos/core/platform/CCView.js b/cocos/core/platform/CCView.js index 085573e7c5..b63807bef8 100644 --- a/cocos/core/platform/CCView.js +++ b/cocos/core/platform/CCView.js @@ -28,7 +28,7 @@ import EventTarget from '../event/event-target'; import '../data/class'; import macro from '../platform/CCMacro'; -import game from '../CCGame'; +import game from '../game'; import Size from '../value-types/size'; import Rect from '../value-types/rect'; @@ -166,7 +166,7 @@ class View extends EventTarget { init () { __BrowserGetter.init(this); - + this._initFrameSize(); this.enableAntiAlias(true); @@ -303,9 +303,9 @@ class View extends EventTarget { /** * !#en * Sets the orientation of the game, it can be landscape, portrait or auto. - * When set it to landscape or portrait, and screen w/h ratio doesn't fit, + * When set it to landscape or portrait, and screen w/h ratio doesn't fit, * cc.view will automatically rotate the game canvas using CSS. - * Note that this function doesn't have any effect in native, + * Note that this function doesn't have any effect in native, * in native, you need to set the application orientation in native project settings * !#zh 设置游戏屏幕朝向,它能够是横版,竖版或自动。 * 当设置为横版或竖版,并且屏幕的宽高比例不匹配时, @@ -331,7 +331,7 @@ class View extends EventTarget { var isLandscape = w >= h; if (CC_EDITOR || !cc.sys.isMobile || - (isLandscape && this._orientation & macro.ORIENTATION_LANDSCAPE) || + (isLandscape && this._orientation & macro.ORIENTATION_LANDSCAPE) || (!isLandscape && this._orientation & macro.ORIENTATION_PORTRAIT)) { locFrameSize.width = w; locFrameSize.height = h; @@ -514,9 +514,9 @@ class View extends EventTarget { * @param {Boolean} enabled - Enable or disable auto full screen on mobile devices */ enableAutoFullScreen(enabled) { - if (enabled && - enabled !== this._autoFullScreen && - cc.sys.isMobile && + if (enabled && + enabled !== this._autoFullScreen && + cc.sys.isMobile && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) { // Automatically full screen when user touches on mobile version this._autoFullScreen = true; @@ -552,8 +552,12 @@ class View extends EventTarget { var canvas = game.canvas; var container = game.container; - canvas.width = width * this._devicePixelRatio; - canvas.height = height * this._devicePixelRatio; + //canvas.width = width * this._devicePixelRatio; + //canvas.height = height * this._devicePixelRatio; + + const w = width * this._devicePixelRatio; + const h = height * this._devicePixelRatio; + cc.director.root.resize(w, h); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; @@ -1486,4 +1490,4 @@ let view = cc.view = new View(); */ cc.winSize = cc.v2(); -export default view; \ No newline at end of file +export default view; diff --git a/cocos/core/platform/event-manager/CCEvent.js b/cocos/core/platform/event-manager/CCEvent.js deleted file mode 100644 index 5bbeff5a8c..0000000000 --- a/cocos/core/platform/event-manager/CCEvent.js +++ /dev/null @@ -1,578 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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 Event from '../../event/event'; - -/** - * !#en The mouse event - * !#zh 鼠标事件类型 - * @class Event.EventMouse - * @extends Event - */ -export class EventMouse extends Event { - /** - * @method constructor - * @param {Number} eventType - The mouse event type, UP, DOWN, MOVE, CANCELED - * @param {Boolean} [bubbles=false] - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (eventType, bubbles) { - super(Event.MOUSE, bubbles); - this._eventType = eventType; - this._button = 0; - this._x = 0; - this._y = 0; - this._prevX = 0; - this._prevY = 0; - this._scrollX = 0; - this._scrollY = 0; - } - - /** - * !#en Sets scroll data. - * !#zh 设置鼠标的滚动数据。 - * @method setScrollData - * @param {Number} scrollX - * @param {Number} scrollY - */ - setScrollData (scrollX, scrollY) { - this._scrollX = scrollX; - this._scrollY = scrollY; - } - - /** - * !#en Returns the x axis scroll value. - * !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 - * @method getScrollX - * @returns {Number} - */ - getScrollX () { - return this._scrollX; - } - - /** - * !#en Returns the y axis scroll value. - * !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 - * @method getScrollY - * @returns {Number} - */ - getScrollY () { - return this._scrollY; - } - - /** - * !#en Sets cursor location. - * !#zh 设置当前鼠标位置。 - * @method setLocation - * @param {Number} x - * @param {Number} y - */ - setLocation (x, y) { - this._x = x; - this._y = y; - } - - /** - * !#en Returns cursor location. - * !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 - * @method getLocation - * @return {Vec2} location - */ - getLocation () { - return cc.v2(this._x, this._y); - } - - /** - * !#en Returns the current cursor location in screen coordinates. - * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 - * @method getLocationInView - * @return {Vec2} - */ - getLocationInView() { - return cc.v2(this._x, cc.view._designResolutionSize.height - this._y); - } - - _setPrevCursor (x, y) { - this._prevX = x; - this._prevY = y; - } - - /** - * !#en Returns the previous touch location. - * !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} - */ - getPreviousLocation () { - return cc.v2(this._prevX, this._prevY); - } - - /** - * !#en Returns the delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} - */ - getDelta () { - return cc.v2(this._x - this._prevX, this._y - this._prevY); - } - - /** - * !#en Returns the X axis delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 - * @method getDeltaX - * @return {Number} - */ - getDeltaX () { - return this._x - this._prevX; - } - - /** - * !#en Returns the Y axis delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 - * @method getDeltaY - * @return {Number} - */ - getDeltaY () { - return this._y - this._prevY; - } - - /** - * !#en Sets mouse button. - * !#zh 设置鼠标按键。 - * @method setButton - * @param {Number} button - */ - setButton (button) { - this._button = button; - } - - /** - * !#en Returns mouse button. - * !#zh 获取鼠标按键。 - * @method getButton - * @returns {Number} - */ - getButton () { - return this._button; - } - - /** - * !#en Returns location X axis data. - * !#zh 获取鼠标当前位置 X 轴。 - * @method getLocationX - * @returns {Number} - */ - getLocationX () { - return this._x; - } - - /** - * !#en Returns location Y axis data. - * !#zh 获取鼠标当前位置 Y 轴。 - * @method getLocationY - * @returns {Number} - */ - getLocationY () { - return this._y; - } -} - -//Inner event types of MouseEvent -/** - * !#en The none event code of mouse event. - * !#zh 无。 - * @property NONE - * @static - * @type {Number} - */ -EventMouse.NONE = 0; -/** - * !#en The event type code of mouse down event. - * !#zh 鼠标按下事件。 - * @property DOWN - * @static - * @type {Number} - */ -EventMouse.DOWN = 1; -/** - * !#en The event type code of mouse up event. - * !#zh 鼠标按下后释放事件。 - * @property UP - * @static - * @type {Number} - */ -EventMouse.UP = 2; -/** - * !#en The event type code of mouse move event. - * !#zh 鼠标移动事件。 - * @property MOVE - * @static - * @type {Number} - */ -EventMouse.MOVE = 3; -/** - * !#en The event type code of mouse scroll event. - * !#zh 鼠标滚轮事件。 - * @property SCROLL - * @static - * @type {Number} - */ -EventMouse.SCROLL = 4; - -/** - * !#en The tag of Mouse left button. - * !#zh 鼠标左键的标签。 - * @property BUTTON_LEFT - * @static - * @type {Number} - */ -EventMouse.BUTTON_LEFT = 0; - -/** - * !#en The tag of Mouse right button (The right button number is 2 on browser). - * !#zh 鼠标右键的标签。 - * @property BUTTON_RIGHT - * @static - * @type {Number} - */ -EventMouse.BUTTON_RIGHT = 2; - -/** - * !#en The tag of Mouse middle button (The right button number is 1 on browser). - * !#zh 鼠标中键的标签。 - * @property BUTTON_MIDDLE - * @static - * @type {Number} - */ -EventMouse.BUTTON_MIDDLE = 1; - -/** - * !#en The tag of Mouse button 4. - * !#zh 鼠标按键 4 的标签。 - * @property BUTTON_4 - * @static - * @type {Number} - */ -EventMouse.BUTTON_4 = 3; - -/** - * !#en The tag of Mouse button 5. - * !#zh 鼠标按键 5 的标签。 - * @property BUTTON_5 - * @static - * @type {Number} - */ -EventMouse.BUTTON_5 = 4; - -/** - * !#en The tag of Mouse button 6. - * !#zh 鼠标按键 6 的标签。 - * @property BUTTON_6 - * @static - * @type {Number} - */ -EventMouse.BUTTON_6 = 5; - -/** - * !#en The tag of Mouse button 7. - * !#zh 鼠标按键 7 的标签。 - * @property BUTTON_7 - * @static - * @type {Number} - */ -EventMouse.BUTTON_7 = 6; - -/** - * !#en The tag of Mouse button 8. - * !#zh 鼠标按键 8 的标签。 - * @property BUTTON_8 - * @static - * @type {Number} - */ -EventMouse.BUTTON_8 = 7; - -/** - * !#en The touch event - * !#zh 触摸事件 - * @class Event.EventTouch - * @constructor - * @extends Event - */ -export class EventTouch extends Event { - /** - * @method constructor - * @param {Array} touchArr - The array of the touches - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (touchArr, bubbles) { - super(Event.TOUCH, bubbles); - this._eventCode = 0; - this._touches = touchArr || []; - /** - * !#en The current touch object - * !#zh 当前触点对象 - * @property touch - * @type {Touch} - */ - this.touch = null; - // Actually duplicated, because of history issue, currentTouch was in the original design, touch was added in creator engine - // They should point to the same object - this.currentTouch = null; - } - - /** - * !#en Returns event code. - * !#zh 获取事件类型。 - * @method getEventCode - * @returns {Number} - */ - getEventCode () { - return this._eventCode; - } - - /** - * !#en Returns touches of event. - * !#zh 获取触摸点的列表。 - * @method getTouches - * @returns {Array} - */ - getTouches () { - return this._touches; - } - - _setEventCode (eventCode) { - this._eventCode = eventCode; - } - - _setTouches (touches) { - this._touches = touches; - } - - /** - * !#en Sets touch location. - * !#zh 设置当前触点位置 - * @method setLocation - * @param {Number} x - * @param {Number} y - */ - setLocation (x, y) { - this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y); - } - - /** - * !#en Returns touch location. - * !#zh 获取触点位置。 - * @method getLocation - * @return {Vec2} location - */ - getLocation () { - return this.touch ? this.touch.getLocation() : cc.v2(); - } - - /** - * !#en Returns the current touch location in screen coordinates. - * !#zh 获取当前触点在游戏窗口中的位置。 - * @method getLocationInView - * @return {Vec2} - */ - getLocationInView() { - return this.touch ? this.touch.getLocationInView() : cc.v2(); - } - - /** - * !#en Returns the previous touch location. - * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} - */ - getPreviousLocation () { - return this.touch ? this.touch.getPreviousLocation() : cc.v2(); - } - - /** - * !#en Returns the start touch location. - * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 - * @method getStartLocation - * @returns {Vec2} - */ - getStartLocation() { - return this.touch ? this.touch.getStartLocation() : cc.v2(); - } - - /** - * !#en Returns the id of cc.Touch. - * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 - * @method getID - * @return {Number} - */ - getID () { - return this.touch ? this.touch.getID() : null; - } - - /** - * !#en Returns the delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} - */ - getDelta () { - return this.touch ? this.touch.getDelta() : cc.v2(); - } - - /** - * !#en Returns the X axis delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的 x 轴距离。 - * @method getDeltaX - * @return {Number} - */ - getDeltaX () { - return this.touch ? this.touch.getDelta().x : 0; - } - - /** - * !#en Returns the Y axis delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的 y 轴距离。 - * @method getDeltaY - * @return {Number} - */ - getDeltaY () { - return this.touch ? this.touch.getDelta().y : 0; - } - - /** - * !#en Returns location X axis data. - * !#zh 获取当前触点 X 轴位置。 - * @method getLocationX - * @returns {Number} - */ - getLocationX () { - return this.touch ? this.touch.getLocationX() : 0; - } - - /** - * !#en Returns location Y axis data. - * !#zh 获取当前触点 Y 轴位置。 - * @method getLocationY - * @returns {Number} - */ - getLocationY () { - return this.touch ? this.touch.getLocationY() : 0; - } -} - -/** - * !#en The maximum touch numbers - * !#zh 最大触摸数量。 - * @constant - * @type {Number} - */ -EventTouch.MAX_TOUCHES = 5; - -/** - * !#en The event type code of touch began event. - * !#zh 开始触摸事件 - * @constant - * @type {Number} - */ -EventTouch.BEGAN = 0; -/** - * !#en The event type code of touch moved event. - * !#zh 触摸后移动事件 - * @constant - * @type {Number} - */ -EventTouch.MOVED = 1; -/** - * !#en The event type code of touch ended event. - * !#zh 结束触摸事件 - * @constant - * @type {Number} - */ -EventTouch.ENDED = 2; -/** - * !#en The event type code of touch cancelled event. - * !#zh 取消触摸事件 - * @constant - * @type {Number} - */ -EventTouch.CANCELED = 3; - -/** - * !#en The acceleration event - * !#zh 加速度事件 - * @class Event.EventAcceleration - * @extends Event - */ -export class EventAcceleration extends Event { - /** - * @method constructor - * @param {Object} acc - The acceleration - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (acc, bubbles) { - super(Event.ACCELERATION, bubbles); - this.acc = acc; - } -} - -/** - * !#en The keyboard event - * !#zh 键盘事件 - * @class Event.EventKeyboard - * @extends Event - */ -export class EventKeyboard extends Event { - /** - * @method constructor - * @param {Number} keyCode - The key code of which triggered this event - * @param {Boolean} isPressed - A boolean indicating whether the key have been pressed - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (keyCode, isPressed, bubbles) { - super(Event.KEYBOARD, bubbles); - /** - * !#en - * The keyCode read-only property represents a system and implementation dependent numerical code identifying the unmodified value of the pressed key. - * This is usually the decimal ASCII (RFC 20) or Windows 1252 code corresponding to the key. - * If the key can't be identified, this value is 0. - * - * !#zh - * keyCode 是只读属性它表示一个系统和依赖于实现的数字代码,可以识别按键的未修改值。 - * 这通常是十进制 ASCII (RFC20) 或者 Windows 1252 代码,所对应的密钥。 - * 如果无法识别该键,则该值为 0。 - * - * @property keyCode - * @type {Number} - */ - this.keyCode = keyCode; - this.isPressed = isPressed; - } -} - -Event.EventMouse = EventMouse; -Event.EventTouch = EventTouch; -Event.EventAcceleration = EventAcceleration; -Event.EventKeyboard = EventKeyboard; diff --git a/cocos/core/platform/event-manager/CCEvent.ts b/cocos/core/platform/event-manager/CCEvent.ts new file mode 100644 index 0000000000..6133b23638 --- /dev/null +++ b/cocos/core/platform/event-manager/CCEvent.ts @@ -0,0 +1,510 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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 Event from '../../event/event'; +import { v2 } from '../../value-types/vec2'; +import Touch from './CCTouch'; + +/** + * !#en The mouse event + * !#zh 鼠标事件类型 + * @class Event.EventMouse + * @extends Event + */ +export class EventMouse extends Event { + // Inner event types of MouseEvent + + /** + * !#en The none event code of mouse event. + * !#zh 无。 + */ + public static NONE = 0; + + /** + * !#en The event type code of mouse down event. + * !#zh 鼠标按下事件。 + */ + public static DOWN = 1; + + /** + * !#en The event type code of mouse up event. + * !#zh 鼠标按下后释放事件。 + */ + public static UP = 2; + + /** + * !#en The event type code of mouse move event. + * !#zh 鼠标移动事件。 + */ + public static MOVE = 3; + + /** + * !#en The event type code of mouse scroll event. + * !#zh 鼠标滚轮事件。 + */ + public static SCROLL = 4; + + /** + * !#en The tag of Mouse left button. + * !#zh 鼠标左键的标签。 + */ + public static BUTTON_LEFT = 0; + + /** + * !#en The tag of Mouse right button (The right button number is 2 on browser). + * !#zh 鼠标右键的标签。 + */ + public static BUTTON_RIGHT = 2; + + /** + * !#en The tag of Mouse middle button (The right button number is 1 on browser). + * !#zh 鼠标中键的标签。 + */ + public static BUTTON_MIDDLE = 1; + + /** + * !#en The tag of Mouse button 4. + * !#zh 鼠标按键 4 的标签。 + */ + public static BUTTON_4 = 3; + + /** + * !#en The tag of Mouse button 5. + * !#zh 鼠标按键 5 的标签。 + */ + public static BUTTON_5 = 4; + + /** + * !#en The tag of Mouse button 6. + * !#zh 鼠标按键 6 的标签。 + */ + public static BUTTON_6 = 5; + + /** + * !#en The tag of Mouse button 7. + * !#zh 鼠标按键 7 的标签。 + */ + public static BUTTON_7 = 6; + + /** + * !#en The tag of Mouse button 8. + * !#zh 鼠标按键 8 的标签。 + */ + public static BUTTON_8 = 7; + + public movementX: number = 0; + + public movementY: number = 0; + + private _eventType: number; + + private _button: number | null = 0; + + private _x: number = 0; + + private _y: number = 0; + + private _prevX: number = 0; + + private _prevY: number = 0; + + private _scrollX: number = 0; + + private _scrollY: number = 0; + + /** + * @param eventType - The mouse event type, UP, DOWN, MOVE, CANCELED + * @param [bubbles=false] - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (eventType: number, bubbles?: boolean) { + super(Event.MOUSE, bubbles); + this._eventType = eventType; + } + + /** + * !#en Sets scroll data. + * !#zh 设置鼠标的滚动数据。 + */ + public setScrollData (scrollX: number, scrollY: number) { + this._scrollX = scrollX; + this._scrollY = scrollY; + } + + /** + * !#en Returns the x axis scroll value. + * !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 + */ + public getScrollX () { + return this._scrollX; + } + + /** + * !#en Returns the y axis scroll value. + * !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 + */ + public getScrollY () { + return this._scrollY; + } + + /** + * !#en Sets cursor location. + * !#zh 设置当前鼠标位置。 + */ + public setLocation (x: number, y: number) { + this._x = x; + this._y = y; + } + + /** + * !#en Returns cursor location. + * !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 + */ + public getLocation () { + return v2(this._x, this._y); + } + + /** + * !#en Returns the current cursor location in screen coordinates. + * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 + */ + public getLocationInView () { + return v2(this._x, cc.view._designResolutionSize.height - this._y); + } + + public _setPrevCursor (x: number, y: number) { + this._prevX = x; + this._prevY = y; + } + + /** + * !#en Returns the previous touch location. + * !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 + */ + public getPreviousLocation () { + return v2(this._prevX, this._prevY); + } + + /** + * !#en Returns the delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + */ + public getDelta () { + return v2(this._x - this._prevX, this._y - this._prevY); + } + + /** + * !#en Returns the X axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 + */ + public getDeltaX () { + return this._x - this._prevX; + } + + /** + * !#en Returns the Y axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 + */ + public getDeltaY () { + return this._y - this._prevY; + } + + /** + * !#en Sets mouse button. + * !#zh 设置鼠标按键。 + */ + public setButton (button: number | null) { + this._button = button; + } + + /** + * !#en Returns mouse button. + * !#zh 获取鼠标按键。 + */ + public getButton () { + return this._button; + } + + /** + * !#en Returns location X axis data. + * !#zh 获取鼠标当前位置 X 轴。 + */ + public getLocationX () { + return this._x; + } + + /** + * !#en Returns location Y axis data. + * !#zh 获取鼠标当前位置 Y 轴。 + */ + public getLocationY () { + return this._y; + } +} + +/** + * !#en The touch event + * !#zh 触摸事件 + * @class Event.EventTouch + * @constructor + * @extends Event + */ +export class EventTouch extends Event { + /** + * !#en The maximum touch numbers + * !#zh 最大触摸数量。 + */ + public static MAX_TOUCHES = 5; + + /** + * !#en The event type code of touch began event. + * !#zh 开始触摸事件 + */ + public static BEGAN = 0; + /** + * !#en The event type code of touch moved event. + * !#zh 触摸后移动事件 + */ + public static MOVED = 1; + /** + * !#en The event type code of touch ended event. + * !#zh 结束触摸事件 + */ + public static ENDED = 2; + /** + * !#en The event type code of touch cancelled event. + * !#zh 取消触摸事件 + */ + public static CANCELLED = 3; + + /** + * !#en The current touch object + * !#zh 当前触点对象 + */ + public touch: Touch | null = null; + + // Actually duplicated, because of history issue, + // currentTouch was in the original design, touch was added in creator engine + // They should point to the same object + public currentTouch: Touch | null = null; + + public _eventCode: number = 0; + + private _touches: Touch[]; + + /** + * @param touches - The array of the touches + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (touches?: Touch[], bubbles?: boolean) { + super(Event.TOUCH, bubbles); + this._eventCode = 0; + this._touches = touches || []; + } + + /** + * !#en Returns event code. + * !#zh 获取事件类型。 + */ + public getEventCode () { + return this._eventCode; + } + + /** + * !#en Returns touches of event. + * !#zh 获取触摸点的列表。 + */ + public getTouches () { + return this._touches; + } + + public _setEventCode (eventCode: number) { + this._eventCode = eventCode; + } + + public _setTouches (touches: Touch[]) { + this._touches = touches; + } + + /** + * !#en Sets touch location. + * !#zh 设置当前触点位置 + */ + public setLocation (x: number, y: number) { + if (this.touch) { + this.touch.setTouchInfo(this.touch.getID(), x, y); + } + } + + /** + * !#en Returns touch location. + * !#zh 获取触点位置。 + */ + public getLocation () { + return this.touch ? this.touch.getLocation() : v2(); + } + + /** + * !#en Returns the current touch location in screen coordinates. + * !#zh 获取当前触点在游戏窗口中的位置。 + */ + public getLocationInView () { + return this.touch ? this.touch.getLocationInView() : v2(); + } + + /** + * !#en Returns the previous touch location. + * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 + */ + public getPreviousLocation () { + return this.touch ? this.touch.getPreviousLocation() : v2(); + } + + /** + * !#en Returns the start touch location. + * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 + */ + public getStartLocation () { + return this.touch ? this.touch.getStartLocation() : v2(); + } + + /** + * !#en Returns the id of cc.Touch. + * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 + */ + public getID () { + return this.touch ? this.touch.getID() : null; + } + + /** + * !#en Returns the delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + */ + public getDelta () { + return this.touch ? this.touch.getDelta() : v2(); + } + + /** + * !#en Returns the X axis delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的 x 轴距离。 + */ + public getDeltaX () { + return this.touch ? this.touch.getDelta().x : 0; + } + + /** + * !#en Returns the Y axis delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的 y 轴距离。 + */ + public getDeltaY () { + return this.touch ? this.touch.getDelta().y : 0; + } + + /** + * !#en Returns location X axis data. + * !#zh 获取当前触点 X 轴位置。 + */ + public getLocationX () { + return this.touch ? this.touch.getLocationX() : 0; + } + + /** + * !#en Returns location Y axis data. + * !#zh 获取当前触点 Y 轴位置。 + */ + public getLocationY () { + return this.touch ? this.touch.getLocationY() : 0; + } +} + +/** + * !#en The acceleration event + * !#zh 加速度事件 + * @class Event.EventAcceleration + * @extends Event + */ +export class EventAcceleration extends Event { + public acc: Object; + + /** + * @param acc - The acceleration + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (acc: Object, bubbles?: boolean) { + super(Event.ACCELERATION, bubbles); + this.acc = acc; + } +} + +/** + * !#en The keyboard event + * !#zh 键盘事件 + * @class Event.EventKeyboard + * @extends Event + */ +export class EventKeyboard extends Event { + /** + * !#en + * The keyCode read-only property represents a system and implementation dependent numerical code + * identifying the unmodified value of the pressed key. + * This is usually the decimal ASCII (RFC 20) or Windows 1252 code corresponding to the key. + * If the key can't be identified, this value is 0. + * + * !#zh + * keyCode 是只读属性它表示一个系统和依赖于实现的数字代码,可以识别按键的未修改值。 + * 这通常是十进制 ASCII (RFC20) 或者 Windows 1252 代码,所对应的密钥。 + * 如果无法识别该键,则该值为 0。 + */ + public keyCode: number; + + public isPressed: boolean; + + /** + * @param keyCode - The key code of which triggered this event + * @param isPressed - A boolean indicating whether the key have been pressed + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (keyCode: number, isPressed: boolean, bubbles?: boolean) { + super(Event.KEYBOARD, bubbles); + this.keyCode = keyCode; + this.isPressed = isPressed; + } +} + +// TODO +// @ts-ignore +Event.EventMouse = EventMouse; + +// TODO +// @ts-ignore +Event.EventTouch = EventTouch; + +// TODO +// @ts-ignore +Event.EventAcceleration = EventAcceleration; + +// TODO +// @ts-ignore +Event.EventKeyboard = EventKeyboard; diff --git a/cocos/core/platform/event-manager/CCEventListener.js b/cocos/core/platform/event-manager/CCEventListener.js deleted file mode 100644 index 620003d159..0000000000 --- a/cocos/core/platform/event-manager/CCEventListener.js +++ /dev/null @@ -1,492 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://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. - ****************************************************************************/ - -/** - * !#en - *

- * The base class of event listener.
- * If you need custom listener which with different callback, you need to inherit this class.
- * For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard,
- * EventListenerTouchOneByOne, EventListenerCustom. - *

- * - * !#zh - * 封装用户的事件处理逻辑。 - * 注意:这是一个抽象类,开发者不应该直接实例化这个类,请参考 {{#crossLink "EventListener/create:method"}}cc.EventListener.create{{/crossLink}}。 - * - * @class EventListener - */ - -/** - * Constructor - * @method constructor - * @param {Number} type - * @param {Number} listenerID - * @param {Number} callback - */ -export class EventListener { - constructor (type, listenerID, callback) { - this._onEvent = callback; // Event callback function - this._type = type || 0; // Event listener type - this._listenerID = listenerID || ""; // Event listener ID - this._registered = false; // Whether the listener has been added to dispatcher. - - this._fixedPriority = 0; // The higher the number, the higher the priority, 0 is for scene graph base priority. - this._node = null; // scene graph based priority - this._target = null; - this._paused = true; // Whether the listener is paused - this._isEnabled = true; // Whether the listener is enabled - } - - /* - *

- * Sets paused state for the listener - * The paused state is only used for scene graph priority listeners. - * `EventDispatcher::resumeAllEventListenersForTarget(node)` will set the paused state to `true`, - * while `EventDispatcher::pauseAllEventListenersForTarget(node)` will set it to `false`. - * @note 1) Fixed priority listeners will never get paused. If a fixed priority doesn't want to receive events, - * call `setEnabled(false)` instead. - * 2) In `Node`'s onEnter and onExit, the `paused state` of the listeners which associated with that node will be automatically updated. - *

- * @param {Boolean} paused - * @private - */ - _setPaused (paused) { - this._paused = paused; - } - - /* - * Checks whether the listener is paused. - * @returns {Boolean} - * @private - */ - _isPaused () { - return this._paused; - } - - /* - * Marks the listener was registered by EventDispatcher. - * @param {Boolean} registered - * @private - */ - _setRegistered (registered) { - this._registered = registered; - } - - /* - * Checks whether the listener was registered by EventDispatcher - * @returns {Boolean} - * @private - */ - _isRegistered () { - return this._registered; - } - - /* - * Gets the type of this listener - * @note It's different from `EventType`, e.g. TouchEvent has two kinds of event listeners - EventListenerOneByOne, EventListenerAllAtOnce - * @returns {Number} - * @private - */ - _getType () { - return this._type; - } - - /* - * Gets the listener ID of this listener - * When event is being dispatched, listener ID is used as key for searching listeners according to event type. - * @returns {String} - * @private - */ - _getListenerID () { - return this._listenerID; - } - - /* - * Sets the fixed priority for this listener - * @note This method is only used for `fixed priority listeners`, it needs to access a non-zero value. 0 is reserved for scene graph priority listeners - * @param {Number} fixedPriority - * @private - */ - _setFixedPriority (fixedPriority) { - this._fixedPriority = fixedPriority; - } - - /* - * Gets the fixed priority of this listener - * @returns {Number} 0 if it's a scene graph priority listener, non-zero for fixed priority listener - * @private - */ - _getFixedPriority () { - return this._fixedPriority; - } - - /* - * Sets scene graph priority for this listener - * @param {cc.Node} node - * @private - */ - _setSceneGraphPriority (node) { - this._target = node; - this._node = node; - } - - /* - * Gets scene graph priority of this listener - * @returns {cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener - * @private - */ - _getSceneGraphPriority () { - return this._node; - } - - /** - * !#en Checks whether the listener is available. - * !#zh 检测监听器是否有效 - * @method checkAvailable - * @returns {Boolean} - */ - checkAvailable () { - return this._onEvent !== null; - } - - /** - * !#en Clones the listener, its subclasses have to override this method. - * !#zh 克隆监听器,它的子类必须重写此方法。 - * @method clone - * @returns {EventListener} - */ - clone () { - return null; - } - - /** - * !#en Enables or disables the listener - * !#zh 启用或禁用监听器。 - * @method setEnabled - * @param {Boolean} enabled - * @note Only listeners with `enabled` state will be able to receive events. - * When an listener was initialized, it's enabled by default. - * An event listener can receive events when it is enabled and is not paused. - * paused state is always false when it is a fixed priority listener. - */ - setEnabled(enabled){ - this._isEnabled = enabled; - } - - /** - * !#en Checks whether the listener is enabled - * !#zh 检查监听器是否可用。 - * @method isEnabled - * @returns {Boolean} - */ - isEnabled(){ - return this._isEnabled; - } -} - -// event listener type -/** - * !#en The type code of unknown event listener. - * !#zh 未知的事件监听器类型 - * @property UNKNOWN - * @type {Number} - * @static - */ -EventListener.UNKNOWN = 0; -/* - * !#en The type code of one by one touch event listener. - * !#zh 触摸事件监听器类型,触点会一个一个得分开被派发 - * @property TOUCH_ONE_BY_ONE - * @type {Number} - * @static - */ -EventListener.TOUCH_ONE_BY_ONE = 1; -/* - * !#en The type code of all at once touch event listener. - * !#zh 触摸事件监听器类型,触点会被一次性全部派发 - * @property TOUCH_ALL_AT_ONCE - * @type {Number} - * @static - */ -EventListener.TOUCH_ALL_AT_ONCE = 2; -/** - * !#en The type code of keyboard event listener. - * !#zh 键盘事件监听器类型 - * @property KEYBOARD - * @type {Number} - * @static - */ -EventListener.KEYBOARD = 3; -/* - * !#en The type code of mouse event listener. - * !#zh 鼠标事件监听器类型 - * @property MOUSE - * @type {Number} - * @static - */ -EventListener.MOUSE = 4; -/** - * !#en The type code of acceleration event listener. - * !#zh 加速器事件监听器类型 - * @property ACCELERATION - * @type {Number} - * @static - */ -EventListener.ACCELERATION = 6; -/* - * !#en The type code of custom event listener. - * !#zh 自定义事件监听器类型 - * @property CUSTOM - * @type {Number} - * @static - */ -EventListener.CUSTOM = 8; - -var ListenerID = EventListener.ListenerID = { - MOUSE: '__cc_mouse', - TOUCH_ONE_BY_ONE: '__cc_touch_one_by_one', - TOUCH_ALL_AT_ONCE: '__cc_touch_all_at_once', - KEYBOARD: '__cc_keyboard', - ACCELERATION: '__cc_acceleration', -}; - -export class Mouse extends EventListener { - constructor () { - super(EventListener.MOUSE, ListenerID.MOUSE); - this._onEvent = this._callback; - this.onMouseDown = null; - this.onMouseUp = null; - this.onMouseMove = null; - this.onMouseScroll = null; - } - - _callback (event) { - var eventType = cc.Event.EventMouse; - switch (event._eventType) { - case eventType.DOWN: - if (this.onMouseDown) - this.onMouseDown(event); - break; - case eventType.UP: - if (this.onMouseUp) - this.onMouseUp(event); - break; - case eventType.MOVE: - if (this.onMouseMove) - this.onMouseMove(event); - break; - case eventType.SCROLL: - if (this.onMouseScroll) - this.onMouseScroll(event); - break; - default: - break; - } - } - - clone () { - var eventListener = new Mouse(); - eventListener.onMouseDown = this.onMouseDown; - eventListener.onMouseUp = this.onMouseUp; - eventListener.onMouseMove = this.onMouseMove; - eventListener.onMouseScroll = this.onMouseScroll; - return eventListener; - } - - checkAvailable () { - return true; - } -} - -export class TouchOneByOne extends EventListener { - constructor () { - super(EventListener.TOUCH_ONE_BY_ONE, ListenerID.TOUCH_ONE_BY_ONE); - this._claimedTouches = []; - - this._claimedTouches = null; - this.swallowTouches = false; - this.onTouchBegan = null; - this.onTouchMoved = null; - this.onTouchEnded = null; - this.onTouchCancelled = null; - } - - setSwallowTouches (needSwallow) { - this.swallowTouches = needSwallow; - } - - isSwallowTouches(){ - return this.swallowTouches; - } - - clone () { - var eventListener = new TouchOneByOne(); - eventListener.onTouchBegan = this.onTouchBegan; - eventListener.onTouchMoved = this.onTouchMoved; - eventListener.onTouchEnded = this.onTouchEnded; - eventListener.onTouchCancelled = this.onTouchCancelled; - eventListener.swallowTouches = this.swallowTouches; - return eventListener; - } - - checkAvailable () { - if(!this.onTouchBegan){ - cc.logID(1801); - return false; - } - return true; - } -} - -export class TouchAllAtOnce extends EventListener { - constructor () { - super(EventListener.TOUCH_ALL_AT_ONCE, ListenerID.TOUCH_ALL_AT_ONCE); - - this.onTouchesBegan = null; - this.onTouchesMoved = null; - this.onTouchesEnded = null; - this.onTouchesCancelled = null; - } - - clone () { - var eventListener = new TouchAllAtOnce(); - eventListener.onTouchesBegan = this.onTouchesBegan; - eventListener.onTouchesMoved = this.onTouchesMoved; - eventListener.onTouchesEnded = this.onTouchesEnded; - eventListener.onTouchesCancelled = this.onTouchesCancelled; - return eventListener; - } - - checkAvailable () { - if (this.onTouchesBegan === null && this.onTouchesMoved === null - && this.onTouchesEnded === null && this.onTouchesCancelled === null) { - cc.logID(1802); - return false; - } - return true; - } -} - -//Acceleration -export class Acceleration extends EventListener { - constructor (callback) { - super(EventListener.ACCELERATION, ListenerID.ACCELERATION); - this._onEvent = this._callback; - this._onAccelerationEvent = callback; - this_onAccelerationEvent = null; - } - - _callback (event) { - this._onAccelerationEvent(event.acc, event); - } - - checkAvailable () { - cc.assertID(this._onAccelerationEvent, 1803); - return true; - } - - clone () { - return new Acceleration(this._onAccelerationEvent); - } -} - - -//Keyboard -export class Keyboard extends EventListener { - constructor () { - super(EventListener.KEYBOARD, ListenerID.KEYBOARD); - this._onEvent = this._callback; - this.onKeyPressed = null; - this.onKeyReleased = null; - } - - _callback (event) { - if (event.isPressed) { - if (this.onKeyPressed) - this.onKeyPressed(event.keyCode, event); - } else { - if (this.onKeyReleased) - this.onKeyReleased(event.keyCode, event); - } - } - - clone () { - var eventListener = new Keyboard(); - eventListener.onKeyPressed = this.onKeyPressed; - eventListener.onKeyReleased = this.onKeyReleased; - return eventListener; - } - - checkAvailable () { - if (this.onKeyPressed === null && this.onKeyReleased === null) { - cc.logID(1800); - return false; - } - return true; - } -} - -/** - * !#en - * Create a EventListener object with configuration including the event type, handlers and other parameters. - * In handlers, this refer to the event listener object itself. - * You can also pass custom parameters in the configuration object, - * all custom parameters will be polyfilled into the event listener object and can be accessed in handlers. - * !#zh 通过指定不同的 Event 对象来设置想要创建的事件监听器。 - * @method create - * @param {Object} argObj a json object - * @returns {EventListener} - * @static - * @example {@link cocos2d/core/event-manager/CCEventListener/create.js} - */ -EventListener.create = function (argObj) { - cc.assertID(argObj&&argObj.event, 1900); - - var listenerType = argObj.event; - delete argObj.event; - - var listener = null; - if(listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) - listener = new TouchOneByOne(); - else if(listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) - listener = new TouchAllAtOnce(); - else if(listenerType === cc.EventListener.MOUSE) - listener = new Mouse(); - else if(listenerType === cc.EventListener.KEYBOARD) - listener = new Keyboard(); - else if(listenerType === cc.EventListener.ACCELERATION){ - listener = new Acceleration(argObj.callback); - delete argObj.callback; - } - - for(var key in argObj) { - listener[key] = argObj[key]; - } - return listener; -} - -cc.EventListener = EventListener; \ No newline at end of file diff --git a/cocos/core/platform/event-manager/CCEventListener.ts b/cocos/core/platform/event-manager/CCEventListener.ts new file mode 100644 index 0000000000..df8636f435 --- /dev/null +++ b/cocos/core/platform/event-manager/CCEventListener.ts @@ -0,0 +1,496 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ + +export interface IEventListenerCreateInfo { + event?: number; + + [x: string]: any; +} + +/** + * !#en + *

+ * The base class of event listener.
+ * If you need custom listener which with different callback, you need to inherit this class.
+ * For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard,
+ * EventListenerTouchOneByOne, EventListenerCustom. + *

+ * + * !#zh + * 封装用户的事件处理逻辑。 + * 注意:这是一个抽象类,开发者不应该直接实例化这个类,请参考 {{#crossLink "EventListener/create:method"}}cc.EventListener.create{{/crossLink}}。 + */ +export class EventListener { + + public get onEvent () { + return this._onEvent; + } + /** + * !#en The type code of unknown event listener. + * !#zh 未知的事件监听器类型 + */ + public static UNKNOWN = 0; + + /* + * !#en The type code of one by one touch event listener. + * !#zh 触摸事件监听器类型,触点会一个一个得分开被派发 + */ + public static TOUCH_ONE_BY_ONE = 1; + + /* + * !#en The type code of all at once touch event listener. + * !#zh 触摸事件监听器类型,触点会被一次性全部派发 + */ + public static TOUCH_ALL_AT_ONCE = 2; + + /** + * !#en The type code of keyboard event listener. + * !#zh 键盘事件监听器类型 + */ + public static KEYBOARD = 3; + + /* + * !#en The type code of mouse event listener. + * !#zh 鼠标事件监听器类型 + */ + public static MOUSE = 4; + + /** + * !#en The type code of acceleration event listener. + * !#zh 加速器事件监听器类型 + */ + public static ACCELERATION = 6; + + /* + * !#en The type code of custom event listener. + * !#zh 自定义事件监听器类型 + */ + public static CUSTOM = 8; + + public static ListenerID = { + MOUSE: '__cc_mouse', + TOUCH_ONE_BY_ONE: '__cc_touch_one_by_one', + TOUCH_ALL_AT_ONCE: '__cc_touch_all_at_once', + KEYBOARD: '__cc_keyboard', + ACCELERATION: '__cc_acceleration', + }; + + /** + * !#en + * Create a EventListener object with configuration including the event type, handlers and other parameters. + * In handlers, this refer to the event listener object itself. + * You can also pass custom parameters in the configuration object, + * all custom parameters will be polyfilled into the event listener object and can be accessed in handlers. + * !#zh 通过指定不同的 Event 对象来设置想要创建的事件监听器。 + * @param {Object} argObj a json object + * @example {@link cocos2d/core/event-manager/CCEventListener/create.js} + */ + public static create (argObj: IEventListenerCreateInfo): EventListener { + cc.assertID(argObj && argObj.event, 1900); + + const listenerType = argObj.event; + delete argObj.event; + + let listener: EventListener | null = null; + if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) { + listener = new TouchOneByOne(); + } else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) { + listener = new TouchAllAtOnce(); + } else if (listenerType === cc.EventListener.MOUSE) { + listener = new Mouse(); + } else if (listenerType === cc.EventListener.KEYBOARD) { + listener = new Keyboard(); + } else if (listenerType === cc.EventListener.ACCELERATION) { + listener = new Acceleration(argObj.callback); + delete argObj.callback; + } + + if (listener) { + for (const key of Object.keys(argObj)) { + listener[key] = argObj[key]; + } + } + + return listener!; + } + + public _target: any = null; + + // Event callback function + protected _onEvent: ((...args: any[]) => any) | null; + + // Event listener type + private _type: number; + + // Event listener ID + private _listenerID: string; + + // Whether the listener has been added to dispatcher. + private _registered = false; + + // The higher the number, the higher the priority, 0 is for scene graph base priority. + private _fixedPriority = 0; + + // scene graph based priority + // @type {Node} + private _node: any = null; // scene graph based priority + + // Whether the listener is paused + private _paused = true; // Whether the listener is paused + + // Whether the listener is enabled + private _isEnabled = true; // Whether the listener is enabled + + constructor (type: number, listenerID: string, callback: ((...args: any[]) => any) | null) { + this._onEvent = callback; + this._type = type || 0; + this._listenerID = listenerID || ''; + } + + /** + *

+ * Sets paused state for the listener + * The paused state is only used for scene graph priority listeners. + * `EventDispatcher::resumeAllEventListenersForTarget(node)` will set the paused state to `true`, + * while `EventDispatcher::pauseAllEventListenersForTarget(node)` will set it to `false`. + * @note 1) Fixed priority listeners will never get paused. If a fixed priority doesn't want to receive events, + * call `setEnabled(false)` instead. + * 2) In `Node`'s onEnter and onExit, the `paused state` of the listeners + * which associated with that node will be automatically updated. + *

+ * @private + */ + public _setPaused (paused: boolean) { + this._paused = paused; + } + + /** + * Checks whether the listener is paused. + * @private + */ + public _isPaused () { + return this._paused; + } + + /** + * Marks the listener was registered by EventDispatcher. + * @private + */ + public _setRegistered (registered: boolean) { + this._registered = registered; + } + + /** + * Checks whether the listener was registered by EventDispatcher + * @private + */ + public _isRegistered () { + return this._registered; + } + + /** + * Gets the type of this listener + * @note It's different from `EventType`, e.g. + * TouchEvent has two kinds of event listeners - EventListenerOneByOne, EventListenerAllAtOnce + * @private + */ + public _getType () { + return this._type; + } + + /** + * Gets the listener ID of this listener + * When event is being dispatched, listener ID is used as key for searching listeners according to event type. + * @private + */ + public _getListenerID () { + return this._listenerID; + } + + /** + * Sets the fixed priority for this listener + * @note This method is only used for `fixed priority listeners`, + * it needs to access a non-zero value. 0 is reserved for scene graph priority listeners + * @private + */ + public _setFixedPriority (fixedPriority: number) { + this._fixedPriority = fixedPriority; + } + + /** + * Gets the fixed priority of this listener + * @return 0 if it's a scene graph priority listener, non-zero for fixed priority listener + * @private + */ + public _getFixedPriority () { + return this._fixedPriority; + } + + /** + * Sets scene graph priority for this listener + * @private + * @param {Node} node + */ + public _setSceneGraphPriority (node: any) { + this._target = node; + this._node = node; + } + + /** + * Gets scene graph priority of this listener + * @return if it's a fixed priority listener, non-null for scene graph priority listener + * @private + */ + public _getSceneGraphPriority () { + return this._node; + } + + /** + * !#en Checks whether the listener is available. + * !#zh 检测监听器是否有效 + */ + public checkAvailable () { + return this._onEvent !== null; + } + + /** + * !#en Clones the listener, its subclasses have to override this method. + * !#zh 克隆监听器,它的子类必须重写此方法。 + */ + public clone (): EventListener | null { + return null; + } + + /** + * !#en Enables or disables the listener + * !#zh 启用或禁用监听器。 + * @note Only listeners with `enabled` state will be able to receive events. + * When an listener was initialized, it's enabled by default. + * An event listener can receive events when it is enabled and is not paused. + * paused state is always false when it is a fixed priority listener. + */ + public setEnabled (enabled: boolean) { + this._isEnabled = enabled; + } + + /** + * !#en Checks whether the listener is enabled + * !#zh 检查监听器是否可用。 + */ + public isEnabled () { + return this._isEnabled; + } +} + +const ListenerID = EventListener.ListenerID; + +export class Mouse extends EventListener { + public onMouseDown: Function | null = null; + public onMouseUp: Function | null = null; + public onMouseMove: Function | null = null; + public onMouseScroll: Function | null = null; + + constructor () { + super(EventListener.MOUSE, ListenerID.MOUSE, null); + this._onEvent = (event: any) => this._callback(event); + } + + public _callback (event) { + const eventType = cc.Event.EventMouse; + switch (event._eventType) { + case eventType.DOWN: + if (this.onMouseDown) { + this.onMouseDown(event); + } + break; + case eventType.UP: + if (this.onMouseUp) { + this.onMouseUp(event); + } + break; + case eventType.MOVE: + if (this.onMouseMove) { + this.onMouseMove(event); + } + break; + case eventType.SCROLL: + if (this.onMouseScroll) { + this.onMouseScroll(event); + } + break; + default: + break; + } + } + + public clone () { + const eventListener = new Mouse(); + eventListener.onMouseDown = this.onMouseDown; + eventListener.onMouseUp = this.onMouseUp; + eventListener.onMouseMove = this.onMouseMove; + eventListener.onMouseScroll = this.onMouseScroll; + return eventListener; + } + + public checkAvailable () { + return true; + } +} + +export class TouchOneByOne extends EventListener { + public swallowTouches = false; + public onTouchBegan: Function | null = null; + public onTouchMoved: Function | null = null; + public onTouchEnded: Function | null = null; + public onTouchCancelled: Function | null = null; + + private _claimedTouches: any[] = []; + + constructor () { + super(EventListener.TOUCH_ONE_BY_ONE, ListenerID.TOUCH_ONE_BY_ONE, null); + } + + public setSwallowTouches (needSwallow) { + this.swallowTouches = needSwallow; + } + + public isSwallowTouches () { + return this.swallowTouches; + } + + public clone () { + const eventListener = new TouchOneByOne(); + eventListener.onTouchBegan = this.onTouchBegan; + eventListener.onTouchMoved = this.onTouchMoved; + eventListener.onTouchEnded = this.onTouchEnded; + eventListener.onTouchCancelled = this.onTouchCancelled; + eventListener.swallowTouches = this.swallowTouches; + return eventListener; + } + + public checkAvailable () { + if (!this.onTouchBegan) { + cc.logID(1801); + return false; + } + return true; + } +} + +export class TouchAllAtOnce extends EventListener { + public onTouchesBegan: Function | null = null; + public onTouchesMoved: Function | null = null; + public onTouchesEnded: Function | null = null; + public onTouchesCancelled: Function | null = null; + + constructor () { + super(EventListener.TOUCH_ALL_AT_ONCE, ListenerID.TOUCH_ALL_AT_ONCE, null); + } + + public clone () { + const eventListener = new TouchAllAtOnce(); + eventListener.onTouchesBegan = this.onTouchesBegan; + eventListener.onTouchesMoved = this.onTouchesMoved; + eventListener.onTouchesEnded = this.onTouchesEnded; + eventListener.onTouchesCancelled = this.onTouchesCancelled; + return eventListener; + } + + public checkAvailable () { + if (this.onTouchesBegan === null && this.onTouchesMoved === null + && this.onTouchesEnded === null && this.onTouchesCancelled === null) { + cc.logID(1802); + return false; + } + return true; + } +} + +// Acceleration +export class Acceleration extends EventListener { + public _onAccelerationEvent: Function | null = null; + + constructor (callback: Function | null) { + super(EventListener.ACCELERATION, ListenerID.ACCELERATION, null); + this._onEvent = (event: any) => this._callback(event); + this._onAccelerationEvent = callback; + } + + public _callback (event) { + if (this._onAccelerationEvent) { + this._onAccelerationEvent(event.acc, event); + } + } + + public checkAvailable () { + cc.assertID(this._onAccelerationEvent, 1803); + return true; + } + + public clone () { + return new Acceleration(this._onAccelerationEvent); + } +} + +// Keyboard +export class Keyboard extends EventListener { + public onKeyPressed: Function | null = null; + public onKeyReleased: Function | null = null; + + constructor () { + super(EventListener.KEYBOARD, ListenerID.KEYBOARD, null); + this._onEvent = (event: any) => this._callback(event); + } + + public _callback (event) { + if (event.isPressed) { + if (this.onKeyPressed) { + this.onKeyPressed(event.keyCode, event); + } + } else { + if (this.onKeyReleased) { + this.onKeyReleased(event.keyCode, event); + } + } + } + + public clone () { + const eventListener = new Keyboard(); + eventListener.onKeyPressed = this.onKeyPressed; + eventListener.onKeyReleased = this.onKeyReleased; + return eventListener; + } + + public checkAvailable () { + if (this.onKeyPressed === null && this.onKeyReleased === null) { + cc.logID(1800); + return false; + } + return true; + } +} + +cc.EventListener = EventListener; diff --git a/cocos/core/platform/event-manager/CCEventManager.js b/cocos/core/platform/event-manager/CCEventManager.ts similarity index 57% rename from cocos/core/platform/event-manager/CCEventManager.js rename to cocos/core/platform/event-manager/CCEventManager.ts index 4e0bcdee6a..835eeff35d 100644 --- a/cocos/core/platform/event-manager/CCEventManager.js +++ b/cocos/core/platform/event-manager/CCEventManager.ts @@ -24,689 +24,183 @@ THE SOFTWARE. ****************************************************************************/ +// tslint:disable:max-line-length + import * as js from '../../utils/js'; -import {EventListener} from './CCEventListener'; +import { EventListener } from './CCEventListener'; const ListenerID = EventListener.ListenerID; +// tslint:disable-next-line class _EventListenerVector { - constructor () { - this._fixedListeners = []; - this._sceneGraphListeners = []; - this.gt0Index = 0; - } + private _fixedListeners: EventListener[] = []; + private _sceneGraphListeners: EventListener[] = []; + private gt0Index = 0; - size () { + public size () { return this._fixedListeners.length + this._sceneGraphListeners.length; } - empty () { + public empty () { return (this._fixedListeners.length === 0) && (this._sceneGraphListeners.length === 0); } - push (listener) { - if (listener._getFixedPriority() === 0) + public push (listener: EventListener) { + if (listener._getFixedPriority() === 0) { this._sceneGraphListeners.push(listener); - else + } else { this._fixedListeners.push(listener); + } } - clearSceneGraphListeners () { + public clearSceneGraphListeners () { this._sceneGraphListeners.length = 0; } - clearFixedListeners () { + public clearFixedListeners () { this._fixedListeners.length = 0; } - clear () { + public clear () { this._sceneGraphListeners.length = 0; this._fixedListeners.length = 0; } - getFixedPriorityListeners () { + public getFixedPriorityListeners () { return this._fixedListeners; } - getSceneGraphPriorityListeners () { + public getSceneGraphPriorityListeners () { return this._sceneGraphListeners; } } -var __getListenerID = function (event) { - var eventType = cc.Event, type = event.type; - if (type === eventType.ACCELERATION) +function __getListenerID (event) { + const eventType = cc.Event; + const type = event.type; + if (type === eventType.ACCELERATION) { return ListenerID.ACCELERATION; - if (type === eventType.KEYBOARD) + } + if (type === eventType.KEYBOARD) { return ListenerID.KEYBOARD; - if (type.startsWith(eventType.MOUSE)) + } + if (type.startsWith(eventType.MOUSE)) { return ListenerID.MOUSE; - if (type.startsWith(eventType.TOUCH)){ - // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. + } + if (type.startsWith(eventType.TOUCH)) { + // Touch listener is very special, it contains two kinds of listeners: + // EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // return UNKNOWN instead. cc.logID(2000); } - return ""; -}; + return ''; +} - -//Priority dirty flag +// Priority dirty flag const DIRTY_NONE = 0; const DIRTY_FIXED_PRIORITY = 1 << 0; const DIRTY_SCENE_GRAPH_PRIORITY = 1 << 1; const DIRTY_ALL = 3; -/** - * !#en - * This class has been deprecated, please use cc.systemEvent or cc.EventTarget instead. See [Listen to and launch events](../../../manual/en/scripting/events.md) for details.
- *
- * cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching. - * The EventListener list is managed in such way so that event listeners can be added and removed - * while events are being dispatched. - * - * !#zh - * 该类已废弃,请使用 cc.systemEvent 或 cc.EventTarget 代替,详见 [监听和发射事件](../../../manual/zh/scripting/events.md)。
- *
- * 事件管理器,它主要管理事件监听器注册和派发系统事件。 - * - * @class eventManager - * @static - * @example {@link cocos2d/core/event-manager/CCEventManager/addListener.js} - * @deprecated - */ -var eventManager = { - _listenersMap: {}, - _priorityDirtyFlagMap: {}, - _nodeListenersMap: {}, - _nodePriorityMap: js.createMap(true), - _globalZOrderNodeMap: [], - _toAddedListeners: [], - _toRemovedListeners: [], - _dirtyNodes: [], - _inDispatch: 0, - _isEnabled: false, - _nodePriorityIndex: 0, - _internalCustomListenerIDs:[], - - _setDirtyForNode (node) { - // Mark the node dirty only when there is an event listener associated with it. - if (this._nodeListenersMap[node._id] !== undefined) { - this._dirtyNodes.push(node); - } - if (node.getChildren) { - var _children = node.getChildren(); - for(var i = 0, len = _children ? _children.length : 0; i < len; i++) - this._setDirtyForNode(_children[i]); - } - }, +class EventManager { + private _listenersMap = {}; + private _priorityDirtyFlagMap = {}; + private _nodeListenersMap = {}; + private _nodePriorityMap = js.createMap(true); + private _globalZOrderNodeMap: string[] = []; + private _toAddedListeners: EventListener[] = []; + private _toRemovedListeners: EventListener[] = []; + private _dirtyNodes: any[] = []; + private _inDispatch = 0; + private _isEnabled = false; + private _nodePriorityIndex = 0; + private _internalCustomListenerIDs: string[] = []; /** * !#en Pauses all listeners which are associated the specified target. * !#zh 暂停传入的 node 相关的所有监听器的事件响应。 - * @method pauseTarget * @param {Node} node - * @param {Boolean} [recursive=false] + * @param [recursive=false] */ - pauseTarget (node, recursive) { + public pauseTarget (node: any, recursive = false) { if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } - var listeners = this._nodeListenersMap[node._id], i, len; + const listeners = this._nodeListenersMap[node._id]; if (listeners) { - for (i = 0, len = listeners.length; i < len; i++) - listeners[i]._setPaused(true); + for (const listener of listeners) { + listener._setPaused(true); + } } if (recursive === true) { - var locChildren = node.getChildren(); - for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) - this.pauseTarget(locChildren[i], true); + const locChildren = node.children; + if (locChildren) { + for (const locChild of locChildren) { + this.pauseTarget(locChild, true); + } + } } - }, + } /** * !#en Resumes all listeners which are associated the specified target. * !#zh 恢复传入的 node 相关的所有监听器的事件响应。 - * @method resumeTarget * @param {Node} node - * @param {Boolean} [recursive=false] + * @param [recursive=false] */ - resumeTarget (node, recursive) { + public resumeTarget (node: any, recursive = false) { if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } - var listeners = this._nodeListenersMap[node._id], i, len; - if (listeners){ - for ( i = 0, len = listeners.length; i < len; i++) - listeners[i]._setPaused(false); + const listeners = this._nodeListenersMap[node._id]; + if (listeners) { + for (const listener of listeners) { + listener._setPaused(false); + } } this._setDirtyForNode(node); - if (recursive === true && node.getChildren) { - var locChildren = node.getChildren(); - for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) - this.resumeTarget(locChildren[i], true); - } - }, - - _addListener (listener) { - if (this._inDispatch === 0) - this._forceAddEventListener(listener); - else - this._toAddedListeners.push(listener); - }, - - _forceAddEventListener (listener) { - var listenerID = listener._getListenerID(); - var listeners = this._listenersMap[listenerID]; - if (!listeners) { - listeners = new _EventListenerVector(); - this._listenersMap[listenerID] = listeners; - } - listeners.push(listener); - - if (listener._getFixedPriority() === 0) { - this._setDirty(listenerID, DIRTY_SCENE_GRAPH_PRIORITY); - - var node = listener._getSceneGraphPriority(); - if (node === null) - cc.logID(3507); - - this._associateNodeAndEventListener(node, listener); - if (node.activeInHierarchy) - this.resumeTarget(node); - } else - this._setDirty(listenerID, DIRTY_FIXED_PRIORITY); - }, - - _getListeners (listenerID) { - return this._listenersMap[listenerID]; - }, - - _updateDirtyFlagForSceneGraph () { - if (this._dirtyNodes.length === 0) - return; - - var locDirtyNodes = this._dirtyNodes, selListeners, selListener, locNodeListenersMap = this._nodeListenersMap; - for (var i = 0, len = locDirtyNodes.length; i < len; i++) { - selListeners = locNodeListenersMap[locDirtyNodes[i]._id]; - if (selListeners) { - for (var j = 0, listenersLen = selListeners.length; j < listenersLen; j++) { - selListener = selListeners[j]; - if (selListener) - this._setDirty(selListener._getListenerID(), DIRTY_SCENE_GRAPH_PRIORITY); + if (recursive === true && node.children.length > 0) { + const locChildren = node.children; + if (locChildren) { + for (const locChild of locChildren) { + this.resumeTarget(locChild, true); } } } - this._dirtyNodes.length = 0; - }, + } - _removeAllListenersInVector (listenerVector) { - if (!listenerVector) - return; - var selListener; - for (var i = 0; i < listenerVector.length;) { - selListener = listenerVector[i]; - selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null) { - this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); - selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. - } - - if (this._inDispatch === 0) - cc.js.array.remove(listenerVector, selListener); - else - ++i; - } - }, - - _removeListenersForListenerID (listenerID) { - var listeners = this._listenersMap[listenerID], i; - if (listeners) { - var fixedPriorityListeners = listeners.getFixedPriorityListeners(); - var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - - this._removeAllListenersInVector(sceneGraphPriorityListeners); - this._removeAllListenersInVector(fixedPriorityListeners); - - // Remove the dirty flag according the 'listenerID'. - // No need to check whether the dispatcher is dispatching event. - delete this._priorityDirtyFlagMap[listenerID]; - - if (!this._inDispatch) { - listeners.clear(); - delete this._listenersMap[listenerID]; - } - } - - var locToAddedListeners = this._toAddedListeners, listener; - for (i = 0; i < locToAddedListeners.length;) { - listener = locToAddedListeners[i]; - if (listener && listener._getListenerID() === listenerID) - cc.js.array.remove(locToAddedListeners, listener); - else - ++i; - } - }, - - _sortEventListeners (listenerID) { - var dirtyFlag = DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap; - if (locFlagMap[listenerID]) - dirtyFlag = locFlagMap[listenerID]; - - if (dirtyFlag !== DIRTY_NONE) { - // Clear the dirty flag first, if `rootNode` is null, then set its dirty flag of scene graph priority - locFlagMap[listenerID] = DIRTY_NONE; - - if (dirtyFlag & DIRTY_FIXED_PRIORITY) - this._sortListenersOfFixedPriority(listenerID); - - if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY){ - var rootEntity = cc.director.getScene(); - if(rootEntity) - this._sortListenersOfSceneGraphPriority(listenerID, rootEntity); - } - } - }, - - _sortListenersOfSceneGraphPriority (listenerID, rootNode) { - var listeners = this._getListeners(listenerID); - if (!listeners) - return; - - var sceneGraphListener = listeners.getSceneGraphPriorityListeners(); - if (!sceneGraphListener || sceneGraphListener.length === 0) - return; - - // Reset priority index - this._nodePriorityIndex = 0; - this._nodePriorityMap = js.createMap(true); - - this._visitTarget(rootNode, true); - - // After sort: priority < 0, > 0 - listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); - }, - - _sortEventListenersOfSceneGraphPriorityDes (l1, l2) { - var locNodePriorityMap = eventManager._nodePriorityMap, - node1 = l1._getSceneGraphPriority(), - node2 = l2._getSceneGraphPriority(); - if (!l2 || !node2 || !locNodePriorityMap[node2._id]) - return -1; - else if (!l1 || !node1 || !locNodePriorityMap[node1._id]) - return 1; - return locNodePriorityMap[node2._id] - locNodePriorityMap[node1._id]; - }, - - _sortListenersOfFixedPriority (listenerID) { - var listeners = this._listenersMap[listenerID]; - if (!listeners) - return; - - var fixedListeners = listeners.getFixedPriorityListeners(); - if(!fixedListeners || fixedListeners.length === 0) - return; - // After sort: priority < 0, > 0 - fixedListeners.sort(this._sortListenersOfFixedPriorityAsc); - - // FIXME: Should use binary search - var index = 0; - for (var len = fixedListeners.length; index < len;) { - if (fixedListeners[index]._getFixedPriority() >= 0) - break; - ++index; - } - listeners.gt0Index = index; - }, - - _sortListenersOfFixedPriorityAsc (l1, l2) { - return l1._getFixedPriority() - l2._getFixedPriority(); - }, - - _onUpdateListeners (listeners) { - var fixedPriorityListeners = listeners.getFixedPriorityListeners(); - var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - var i, selListener, idx, toRemovedListeners = this._toRemovedListeners; - - if (sceneGraphPriorityListeners) { - for (i = 0; i < sceneGraphPriorityListeners.length;) { - selListener = sceneGraphPriorityListeners[i]; - if (!selListener._isRegistered()) { - cc.js.array.remove(sceneGraphPriorityListeners, selListener); - // if item in toRemove list, remove it from the list - idx = toRemovedListeners.indexOf(selListener); - if(idx !== -1) - toRemovedListeners.splice(idx, 1); - } else - ++i; - } - } - - if (fixedPriorityListeners) { - for (i = 0; i < fixedPriorityListeners.length;) { - selListener = fixedPriorityListeners[i]; - if (!selListener._isRegistered()) { - cc.js.array.remove(fixedPriorityListeners, selListener); - // if item in toRemove list, remove it from the list - idx = toRemovedListeners.indexOf(selListener); - if(idx !== -1) - toRemovedListeners.splice(idx, 1); - } - else - ++i; - } - } - - if (sceneGraphPriorityListeners && sceneGraphPriorityListeners.length === 0) - listeners.clearSceneGraphListeners(); - - if (fixedPriorityListeners && fixedPriorityListeners.length === 0) - listeners.clearFixedListeners(); - }, - - frameUpdateListeners () { - var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; - for (var selKey in locListenersMap) { + public frameUpdateListeners () { + const locListenersMap = this._listenersMap; + const locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; + for (const selKey in locListenersMap) { if (locListenersMap[selKey].empty()) { delete locPriorityDirtyFlagMap[selKey]; delete locListenersMap[selKey]; } } - var locToAddedListeners = this._toAddedListeners; + const locToAddedListeners = this._toAddedListeners; if (locToAddedListeners.length !== 0) { - for (var i = 0, len = locToAddedListeners.length; i < len; i++) + for (let i = 0, len = locToAddedListeners.length; i < len; i++) { this._forceAddEventListener(locToAddedListeners[i]); + } locToAddedListeners.length = 0; } if (this._toRemovedListeners.length !== 0) { this._cleanToRemovedListeners(); } - }, - - _updateTouchListeners (event) { - var locInDispatch = this._inDispatch; - cc.assertID(locInDispatch > 0, 3508); - - if (locInDispatch > 1) - return; - - var listeners; - listeners = this._listenersMap[ListenerID.TOUCH_ONE_BY_ONE]; - if (listeners) { - this._onUpdateListeners(listeners); - } - listeners = this._listenersMap[ListenerID.TOUCH_ALL_AT_ONCE]; - if (listeners) { - this._onUpdateListeners(listeners); - } - - cc.assertID(locInDispatch === 1, 3509); - - var locToAddedListeners = this._toAddedListeners; - if (locToAddedListeners.length !== 0) { - for (var i = 0, len = locToAddedListeners.length; i < len; i++) - this._forceAddEventListener(locToAddedListeners[i]); - this._toAddedListeners.length = 0; - } - - if (this._toRemovedListeners.length !== 0) { - this._cleanToRemovedListeners(); - } - }, - - //Remove all listeners in _toRemoveListeners list and cleanup - _cleanToRemovedListeners () { - var toRemovedListeners = this._toRemovedListeners; - for (var i = 0; i < toRemovedListeners.length; i++) { - var selListener = toRemovedListeners[i]; - var listeners = this._listenersMap[selListener._getListenerID()]; - if (!listeners) - continue; - - var idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(), - sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - - if (sceneGraphPriorityListeners) { - idx = sceneGraphPriorityListeners.indexOf(selListener); - if (idx !== -1) { - sceneGraphPriorityListeners.splice(idx, 1); - } - } - if (fixedPriorityListeners) { - idx = fixedPriorityListeners.indexOf(selListener); - if (idx !== -1) { - fixedPriorityListeners.splice(idx, 1); - } - } - } - toRemovedListeners.length = 0; - }, - - _onTouchEventCallback (listener, argsObj) { - // Skip if the listener was removed. - if (!listener._isRegistered) - return false; - - var event = argsObj.event, selTouch = event.currentTouch; - event.currentTarget = listener._node; - - var isClaimed = false, removedIdx; - var getCode = event.getEventCode(), EventTouch = cc.Event.EventTouch; - if (getCode === EventTouch.BEGAN) { - if (listener.onTouchBegan) { - isClaimed = listener.onTouchBegan(selTouch, event); - if (isClaimed && listener._registered) - listener._claimedTouches.push(selTouch); - } - } else if (listener._claimedTouches.length > 0 - && ((removedIdx = listener._claimedTouches.indexOf(selTouch)) !== -1)) { - isClaimed = true; - if (getCode === EventTouch.MOVED && listener.onTouchMoved) { - listener.onTouchMoved(selTouch, event); - } else if (getCode === EventTouch.ENDED) { - if (listener.onTouchEnded) - listener.onTouchEnded(selTouch, event); - if (listener._registered) - listener._claimedTouches.splice(removedIdx, 1); - } else if (getCode === EventTouch.CANCELLED) { - if (listener.onTouchCancelled) - listener.onTouchCancelled(selTouch, event); - if (listener._registered) - listener._claimedTouches.splice(removedIdx, 1); - } - } - - // If the event was stopped, return directly. - if (event.isStopped()) { - eventManager._updateTouchListeners(event); - return true; - } - - if (isClaimed && listener._registered && listener.swallowTouches) { - if (argsObj.needsMutableSet) - argsObj.touches.splice(selTouch, 1); - return true; - } - return false; - }, - - _dispatchTouchEvent (event) { - this._sortEventListeners(ListenerID.TOUCH_ONE_BY_ONE); - this._sortEventListeners(ListenerID.TOUCH_ALL_AT_ONCE); - - var oneByOneListeners = this._getListeners(ListenerID.TOUCH_ONE_BY_ONE); - var allAtOnceListeners = this._getListeners(ListenerID.TOUCH_ALL_AT_ONCE); - - // If there aren't any touch listeners, return directly. - if (null === oneByOneListeners && null === allAtOnceListeners) - return; - - var originalTouches = event.getTouches(), mutableTouches = cc.js.array.copy(originalTouches); - var oneByOneArgsObj = {event: event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null}; - - // - // process the target handlers 1st - // - if (oneByOneListeners) { - for (var i = 0; i < originalTouches.length; i++) { - event.currentTouch = originalTouches[i]; - event._propagationStopped = event._propagationImmediateStopped = false; - this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj); - } - } - - // - // process standard handlers 2nd - // - if (allAtOnceListeners && mutableTouches.length > 0) { - this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, {event: event, touches: mutableTouches}); - if (event.isStopped()) - return; - } - this._updateTouchListeners(event); - }, - - _onTouchesEventCallback (listener, callbackParams) { - // Skip if the listener was removed. - if (!listener._registered) - return false; - - var EventTouch = cc.Event.EventTouch, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode(); - event.currentTarget = listener._node; - if (getCode === EventTouch.BEGAN && listener.onTouchesBegan) - listener.onTouchesBegan(touches, event); - else if (getCode === EventTouch.MOVED && listener.onTouchesMoved) - listener.onTouchesMoved(touches, event); - else if (getCode === EventTouch.ENDED && listener.onTouchesEnded) - listener.onTouchesEnded(touches, event); - else if (getCode === EventTouch.CANCELLED && listener.onTouchesCancelled) - listener.onTouchesCancelled(touches, event); - - // If the event was stopped, return directly. - if (event.isStopped()) { - eventManager._updateTouchListeners(event); - return true; - } - return false; - }, - - _associateNodeAndEventListener (node, listener) { - var listeners = this._nodeListenersMap[node._id]; - if (!listeners) { - listeners = []; - this._nodeListenersMap[node._id] = listeners; - } - listeners.push(listener); - }, - - _dissociateNodeAndEventListener (node, listener) { - var listeners = this._nodeListenersMap[node._id]; - if (listeners) { - cc.js.array.remove(listeners, listener); - if (listeners.length === 0) - delete this._nodeListenersMap[node._id]; - } - }, - - _dispatchEventToListeners (listeners, onEvent, eventOrArgs) { - var shouldStopPropagation = false; - var fixedPriorityListeners = listeners.getFixedPriorityListeners(); - var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - - var i = 0, j, selListener; - if (fixedPriorityListeners) { // priority < 0 - if (fixedPriorityListeners.length !== 0) { - for (; i < listeners.gt0Index; ++i) { - selListener = fixedPriorityListeners[i]; - if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { - shouldStopPropagation = true; - break; - } - } - } - } - - if (sceneGraphPriorityListeners && !shouldStopPropagation) { // priority == 0, scene graph priority - for (j = 0; j < sceneGraphPriorityListeners.length; j++) { - selListener = sceneGraphPriorityListeners[j]; - if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { - shouldStopPropagation = true; - break; - } - } - } - - if (fixedPriorityListeners && !shouldStopPropagation) { // priority > 0 - for (; i < fixedPriorityListeners.length; ++i) { - selListener = fixedPriorityListeners[i]; - if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { - shouldStopPropagation = true; - break; - } - } - } - }, - - _setDirty (listenerID, flag) { - var locDirtyFlagMap = this._priorityDirtyFlagMap; - if (locDirtyFlagMap[listenerID] == null) - locDirtyFlagMap[listenerID] = flag; - else - locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID]; - }, - - _visitTarget (node, isRootNode) { - // sortAllChildren is performed the next frame, but the event is executed immediately. - if (node._reorderChildDirty) { - node.sortAllChildren(); - } - var children = node.getChildren(), i = 0; - var childrenCount = children.length, locGlobalZOrderNodeMap = this._globalZOrderNodeMap, locNodeListenersMap = this._nodeListenersMap; - - if (childrenCount > 0) { - if (locNodeListenersMap[node._id] !== undefined) { - if (!locGlobalZOrderNodeMap) - locGlobalZOrderNodeMap = []; - locGlobalZOrderNodeMap.push(node._id); - } - - var child; - for (; i < childrenCount; i++) { - child = children[i]; - if (child) - this._visitTarget(child, false); - } - } else { - if (locNodeListenersMap[node._id] !== undefined) { - if (!locGlobalZOrderNodeMap) - locGlobalZOrderNodeMap = []; - locGlobalZOrderNodeMap.push(node._id); - } - } - - if (isRootNode) { - let locNodePriorityMap = this._nodePriorityMap; - for (let j = 0; j < locGlobalZOrderNodeMap.length; j++) - locNodePriorityMap[locGlobalZOrderNodeMap[j]] = ++this._nodePriorityIndex; - this._globalZOrderNodeMap.length = 0; - } - }, - - _sortNumberAsc (a, b) { - return a - b; - }, + } /** * !#en Query whether the specified event listener id has been added. * !#zh 查询指定的事件 ID 是否存在 - * @method hasEventListener - * @param {String|Number} listenerID - The listener id. - * @return {Boolean} true or false + * @param listenerID - The listener id. + * @return true or false */ - hasEventListener (listenerID) { + public hasEventListener (listenerID: string | number) { return !!this._getListeners(listenerID); - }, + } /** * !#en @@ -723,15 +217,15 @@ var eventManager = { * 如果参数 “nodeOrPriority” 是数字,优先级则固定为该参数的数值,数字越小,优先级越高。
* * @method addListener - * @param {EventListener|Object} listener - The listener of a specified event or a object of some event parameters. - * @param {Node|Number} nodeOrPriority - The priority of the listener is based on the draw order of this node or fixedPriority The fixed priority of the listener. + * @param listener - The listener of a specified event or a object of some event parameters. + * @param nodeOrPriority - The priority of the listener is based on the draw order of this node or fixedPriority The fixed priority of the listener. * @note The priority of scene graph will be fixed value 0. So the order of listener item in the vector will be ' <0, scene graph (0 priority), >0'. * A lower priority will be called before the ones that have a higher value. 0 priority is forbidden for fixed priority since it's used for scene graph based priority. * The listener must be a cc.EventListener object when adding a fixed priority listener, because we can't remove a fixed priority listener without the listener handler, * except calls removeAllListeners(). * @return {EventListener} Return the listener. Needed in order to remove the event from the dispatcher. */ - addListener (listener, nodeOrPriority) { + public addListener (listener: EventListener, nodeOrPriority: any | number): any { cc.assertID(listener && nodeOrPriority, 3503); if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode)) { cc.warnID(3506); @@ -747,8 +241,9 @@ var eventManager = { } } - if (!listener.checkAvailable()) + if (!listener.checkAvailable()) { return; + } if (cc.js.isNumber(nodeOrPriority)) { if (nodeOrPriority === 0) { @@ -769,50 +264,52 @@ var eventManager = { } return listener; - }, + } - /* + /** * !#en Adds a Custom event listener. It will use a fixed priority of 1. * !#zh 向事件管理器添加一个自定义事件监听器。 - * @method addCustomListener - * @param {String} eventName - * @param {Function} callback - * @return {EventListener} the generated event. Needed in order to remove the event from the dispatcher + * @param eventName + * @param callback + * @return the generated event. Needed in order to remove the event from the dispatcher */ - addCustomListener (eventName, callback) { - var listener = new cc.EventListener.create({ + public addCustomListener (eventName: string, callback: Function) { + const listener = EventListener.create({ event: cc.EventListener.CUSTOM, - eventName: eventName, - callback: callback + eventName, + callback, }); this.addListener(listener, 1); return listener; - }, + } /** * !#en Remove a listener. * !#zh 移除一个已添加的监听器。 - * @method removeListener - * @param {EventListener} listener - an event listener or a registered node target + * @param listener - an event listener or a registered node target * @example {@link cocos2d/core/event-manager/CCEventManager/removeListener.js} */ - removeListener (listener) { - if (listener == null) + public removeListener (listener: EventListener) { + if (listener == null) { return; + } - var isFound, locListener = this._listenersMap; - for (var selKey in locListener) { - var listeners = locListener[selKey]; - var fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + let isFound = false; + const locListener = this._listenersMap; + for (const selKey of Object.keys(locListener)) { + const listeners = locListener[selKey]; + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener); - if (isFound){ + if (isFound) { // fixed #4160: Dirty flag need to be updated after listeners were removed. this._setDirty(listener._getListenerID(), DIRTY_SCENE_GRAPH_PRIORITY); - }else{ + } else { isFound = this._removeListenerInVector(fixedPriorityListeners, listener); - if (isFound) + if (isFound) { this._setDirty(listener._getListenerID(), DIRTY_FIXED_PRIORITY); + } } if (listeners.empty()) { @@ -820,14 +317,15 @@ var eventManager = { delete locListener[selKey]; } - if (isFound) + if (isFound) { break; + } } if (!isFound) { - var locToAddedListeners = this._toAddedListeners; - for (var i = 0, len = locToAddedListeners.length; i < len; i++) { - var selListener = locToAddedListeners[i]; + const locToAddedListeners = this._toAddedListeners; + for (let i = 0, len = locToAddedListeners.length; i < len; i++) { + const selListener = locToAddedListeners[i]; if (selListener === listener) { cc.js.array.remove(locToAddedListeners, selListener); selListener._setRegistered(false); @@ -835,53 +333,7 @@ var eventManager = { } } } - }, - - _removeListenerInCallback(listeners, callback){ - if (listeners == null) - return false; - - for (var i = 0, len = listeners.length; i < len; i++) { - var selListener = listeners[i]; - if (selListener._onCustomEvent === callback || selListener._onEvent === callback) { - selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null){ - this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); - selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. - } - - if (this._inDispatch === 0) - cc.js.array.remove(listeners, selListener); - else - this._toRemovedListeners.push(selListener); - return true; - } - } - return false; - }, - - _removeListenerInVector (listeners, listener) { - if (listeners == null) - return false; - - for (var i = 0, len = listeners.length; i < len; i++) { - var selListener = listeners[i]; - if (selListener === listener) { - selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null) { - this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); - selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. - } - - if (this._inDispatch === 0) - cc.js.array.remove(listeners, selListener); - else - this._toRemovedListeners.push(selListener); - return true; - } - } - return false; - }, + } /** * !#en Removes all listeners with the same event listener type or removes all listeners of a node. @@ -899,10 +351,9 @@ var eventManager = { * * @method removeListeners * @param {Number|Node} listenerType - listenerType or a node - * @param {Boolean} [recursive=false] + * @param [recursive=false] */ - removeListeners (listenerType, recursive) { - var i, _t = this; + public removeListeners (listenerType: number | any, recursive = false) { if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) { cc.warnID(3506); return; @@ -910,14 +361,15 @@ var eventManager = { if (listenerType._id !== undefined) { // Ensure the node is removed from these immediately also. // Don't want any dangling pointers or the possibility of dealing with deleted objects.. - delete _t._nodePriorityMap[listenerType._id]; - cc.js.array.remove(_t._dirtyNodes, listenerType); - var listeners = _t._nodeListenersMap[listenerType._id], i; + delete this._nodePriorityMap[listenerType._id]; + cc.js.array.remove(this._dirtyNodes, listenerType); + const listeners = this._nodeListenersMap[listenerType._id]; if (listeners) { - var listenersCopy = cc.js.array.copy(listeners); - for (i = 0; i < listenersCopy.length; i++) - _t.removeListener(listenersCopy[i]); - delete _t._nodeListenersMap[listenerType._id]; + const listenersCopy = cc.js.array.copy(listeners); + for (const listenerCopy of listenersCopy) { + this.removeListener(listenerCopy); + } + delete this._nodeListenersMap[listenerType._id]; } // Bug fix: ensure there are no references to the node in the list of listeners to be added. @@ -925,37 +377,41 @@ var eventManager = { // This is to catch the scenario where the node gets destroyed before it's listener // is added into the event dispatcher fully. This could happen if a node registers a listener // and gets destroyed while we are dispatching an event (touch etc.) - var locToAddedListeners = _t._toAddedListeners; - for (i = 0; i < locToAddedListeners.length; ) { - var listener = locToAddedListeners[i]; + const locToAddedListeners = this._toAddedListeners; + for (let i = 0; i < locToAddedListeners.length;) { + const listener = locToAddedListeners[i]; if (listener._getSceneGraphPriority() === listenerType) { - listener._setSceneGraphPriority(null); // Ensure no dangling ptr to the target node. + // Ensure no dangling ptr to the target node. + listener._setSceneGraphPriority(null); listener._setRegistered(false); locToAddedListeners.splice(i, 1); - } else + } else { ++i; + } } if (recursive === true) { - var locChildren = listenerType.getChildren(), len; - for (i = 0, len = locChildren.length; i< len; i++) - _t.removeListeners(locChildren[i], true); + const locChildren = listenerType.getChildren(); + for (const locChild of locChildren) { + this.removeListeners(locChild, true); + } } } else { - if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) - _t._removeListenersForListenerID(ListenerID.TOUCH_ONE_BY_ONE); - else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) - _t._removeListenersForListenerID(ListenerID.TOUCH_ALL_AT_ONCE); - else if (listenerType === cc.EventListener.MOUSE) - _t._removeListenersForListenerID(ListenerID.MOUSE); - else if (listenerType === cc.EventListener.ACCELERATION) - _t._removeListenersForListenerID(ListenerID.ACCELERATION); - else if (listenerType === cc.EventListener.KEYBOARD) - _t._removeListenersForListenerID(ListenerID.KEYBOARD); - else + if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) { + this._removeListenersForListenerID(ListenerID.TOUCH_ONE_BY_ONE); + } else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) { + this._removeListenersForListenerID(ListenerID.TOUCH_ALL_AT_ONCE); + } else if (listenerType === cc.EventListener.MOUSE) { + this._removeListenersForListenerID(ListenerID.MOUSE); + } else if (listenerType === cc.EventListener.ACCELERATION) { + this._removeListenersForListenerID(ListenerID.ACCELERATION); + } else if (listenerType === cc.EventListener.KEYBOARD) { + this._removeListenersForListenerID(ListenerID.KEYBOARD); + } else { cc.logID(3501); + } } - }, + } /* * !#en Removes all custom listeners with the same event name. @@ -963,22 +419,24 @@ var eventManager = { * @method removeCustomListeners * @param {String} customEventName */ - removeCustomListeners (customEventName) { + public removeCustomListeners (customEventName) { this._removeListenersForListenerID(customEventName); - }, + } /** * !#en Removes all listeners * !#zh 移除所有事件监听器。 * @method removeAllListeners */ - removeAllListeners () { - var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs; - for (var selKey in locListeners){ - if(locInternalCustomEventIDs.indexOf(selKey) === -1) + public removeAllListeners () { + const locListeners = this._listenersMap; + const locInternalCustomEventIDs = this._internalCustomListenerIDs; + for (const selKey in locListeners) { + if (locInternalCustomEventIDs.indexOf(selKey) === -1) { this._removeListenersForListenerID(selKey); + } } - }, + } /** * !#en Sets listener's priority with fixed value. @@ -987,19 +445,21 @@ var eventManager = { * @param {EventListener} listener * @param {Number} fixedPriority */ - setPriority (listener, fixedPriority) { - if (listener == null) + public setPriority (listener, fixedPriority) { + if (listener == null) { return; + } - var locListeners = this._listenersMap; - for (var selKey in locListeners) { - var selListeners = locListeners[selKey]; - var fixedPriorityListeners = selListeners.getFixedPriorityListeners(); + const locListeners = this._listenersMap; + for (const selKey of Object.keys(locListeners)) { + const selListeners = locListeners[selKey]; + const fixedPriorityListeners = selListeners.getFixedPriorityListeners(); if (fixedPriorityListeners) { - var found = fixedPriorityListeners.indexOf(listener); + const found = fixedPriorityListeners.indexOf(listener); if (found !== -1) { - if(listener._getSceneGraphPriority() != null) + if (listener._getSceneGraphPriority() != null) { cc.logID(3502); + } if (listener._getFixedPriority() !== fixedPriority) { listener._setFixedPriority(fixedPriority); this._setDirty(listener._getListenerID(), DIRTY_FIXED_PRIORITY); @@ -1008,7 +468,7 @@ var eventManager = { } } } - }, + } /** * !#en Whether to enable dispatching events @@ -1016,9 +476,9 @@ var eventManager = { * @method setEnabled * @param {Boolean} enabled */ - setEnabled (enabled) { + public setEnabled (enabled) { this._isEnabled = enabled; - }, + } /** * !#en Checks whether dispatching events is enabled @@ -1026,9 +486,9 @@ var eventManager = { * @method isEnabled * @returns {Boolean} */ - isEnabled () { + public isEnabled () { return this._isEnabled; - }, + } /* * !#en Dispatches the event, also removes all EventListeners marked for deletion from the event dispatcher list. @@ -1036,9 +496,10 @@ var eventManager = { * @method dispatchEvent * @param {Event} event */ - dispatchEvent (event) { - if (!this._isEnabled) + public dispatchEvent (event) { + if (!this._isEnabled) { return; + } this._updateDirtyFlagForSceneGraph(); this._inDispatch++; @@ -1052,22 +513,25 @@ var eventManager = { return; } - var listenerID = __getListenerID(event); + const listenerID = __getListenerID(event); this._sortEventListeners(listenerID); - var selListeners = this._listenersMap[listenerID]; + const selListeners = this._listenersMap[listenerID]; if (selListeners != null) { this._dispatchEventToListeners(selListeners, this._onListenerCallback, event); this._onUpdateListeners(selListeners); } this._inDispatch--; - }, + } - _onListenerCallback(listener, event){ + public _onListenerCallback (listener: EventListener, event) { event.currentTarget = listener._target; - listener._onEvent(event); + const onEvent = listener.onEvent; + if (onEvent) { + onEvent(event); + } return event.isStopped(); - }, + } /* * !#en Dispatches a Custom Event with a event name an optional user data @@ -1076,13 +540,643 @@ var eventManager = { * @param {String} eventName * @param {*} optionalUserData */ - dispatchCustomEvent (eventName, optionalUserData) { - var ev = new cc.Event.EventCustom(eventName); + public dispatchCustomEvent (eventName, optionalUserData) { + const ev = new cc.Event.EventCustom(eventName); ev.setUserData(optionalUserData); this.dispatchEvent(ev); } + + private _setDirtyForNode (node) { + // Mark the node dirty only when there is an event listener associated with it. + if (this._nodeListenersMap[node._id] !== undefined) { + this._dirtyNodes.push(node); + } + if (node.children.length > 0) { + const _children = node.children; + for (let i = 0, len = _children ? _children.length : 0; i < len; i++) { + this._setDirtyForNode(_children[i]); + } + } + } + + private _addListener (listener) { + if (this._inDispatch === 0) { + this._forceAddEventListener(listener); + } else { + this._toAddedListeners.push(listener); + } + } + + private _forceAddEventListener (listener) { + const listenerID = listener._getListenerID(); + let listeners = this._listenersMap[listenerID]; + if (!listeners) { + listeners = new _EventListenerVector(); + this._listenersMap[listenerID] = listeners; + } + listeners.push(listener); + + if (listener._getFixedPriority() === 0) { + this._setDirty(listenerID, DIRTY_SCENE_GRAPH_PRIORITY); + + const node = listener._getSceneGraphPriority(); + if (node === null) { + cc.logID(3507); + } + + this._associateNodeAndEventListener(node, listener); + if (node.activeInHierarchy) { + this.resumeTarget(node); + } + } else { + this._setDirty(listenerID, DIRTY_FIXED_PRIORITY); + } + } + + private _getListeners (listenerID) { + return this._listenersMap[listenerID]; + } + + private _updateDirtyFlagForSceneGraph () { + if (this._dirtyNodes.length === 0) { + return; + } + + const locDirtyNodes = this._dirtyNodes; + const locNodeListenersMap = this._nodeListenersMap; + for (let i = 0, len = locDirtyNodes.length; i < len; i++) { + const selListeners = locNodeListenersMap[locDirtyNodes[i]._id]; + if (selListeners) { + for (let j = 0, listenersLen = selListeners.length; j < listenersLen; j++) { + const selListener = selListeners[j]; + if (selListener) { + this._setDirty(selListener._getListenerID(), DIRTY_SCENE_GRAPH_PRIORITY); + } + } + } + } + this._dirtyNodes.length = 0; + } + + private _removeAllListenersInVector (listenerVector) { + if (!listenerVector) { + return; + } + let selListener; + for (let i = 0; i < listenerVector.length;) { + selListener = listenerVector[i]; + selListener._setRegistered(false); + if (selListener._getSceneGraphPriority() != null) { + this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); + selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. + } + + if (this._inDispatch === 0) { + cc.js.array.remove(listenerVector, selListener); + } else { + ++i; + } + } + } + + private _removeListenersForListenerID (listenerID) { + const listeners = this._listenersMap[listenerID]; + if (listeners) { + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + + this._removeAllListenersInVector(sceneGraphPriorityListeners); + this._removeAllListenersInVector(fixedPriorityListeners); + + // Remove the dirty flag according the 'listenerID'. + // No need to check whether the dispatcher is dispatching event. + delete this._priorityDirtyFlagMap[listenerID]; + + if (!this._inDispatch) { + listeners.clear(); + delete this._listenersMap[listenerID]; + } + } + + const locToAddedListeners = this._toAddedListeners; + for (let i = 0; i < locToAddedListeners.length;) { + const listener = locToAddedListeners[i]; + if (listener && listener._getListenerID() === listenerID) { + cc.js.array.remove(locToAddedListeners, listener); + } else { + ++i; + } + } + } + + private _sortEventListeners (listenerID) { + let dirtyFlag = DIRTY_NONE; + const locFlagMap = this._priorityDirtyFlagMap; + if (locFlagMap[listenerID]) { + dirtyFlag = locFlagMap[listenerID]; + } + + if (dirtyFlag !== DIRTY_NONE) { + // Clear the dirty flag first, if `rootNode` is null, then set its dirty flag of scene graph priority + locFlagMap[listenerID] = DIRTY_NONE; + + if (dirtyFlag & DIRTY_FIXED_PRIORITY) { + this._sortListenersOfFixedPriority(listenerID); + } + + if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY) { + const rootEntity = cc.director.getScene(); + if (rootEntity) { + this._sortListenersOfSceneGraphPriority(listenerID, rootEntity); + } + } + } + } + + private _sortListenersOfSceneGraphPriority (listenerID, rootNode) { + const listeners = this._getListeners(listenerID); + if (!listeners) { + return; + } + + const sceneGraphListener = listeners.getSceneGraphPriorityListeners(); + if (!sceneGraphListener || sceneGraphListener.length === 0) { + return; + } + + // Reset priority index + this._nodePriorityIndex = 0; + this._nodePriorityMap = js.createMap(true); + + this._visitTarget(rootNode, true); + + // After sort: priority < 0, > 0 + listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); + } + + private _sortEventListenersOfSceneGraphPriorityDes (l1: EventListener, l2: EventListener) { + const locNodePriorityMap = eventManager._nodePriorityMap; + const node1 = l1._getSceneGraphPriority(); + const node2 = l2._getSceneGraphPriority(); + if (!l2 || !node2 || !locNodePriorityMap[node2._id]) { + return -1; + } else if (!l1 || !node1 || !locNodePriorityMap[node1._id]) { + return 1; + } + return locNodePriorityMap[node2._id] - locNodePriorityMap[node1._id]; + } + + private _sortListenersOfFixedPriority (listenerID) { + const listeners = this._listenersMap[listenerID]; + if (!listeners) { + return; + } + + const fixedListeners = listeners.getFixedPriorityListeners(); + if (!fixedListeners || fixedListeners.length === 0) { + return; + } + // After sort: priority < 0, > 0 + fixedListeners.sort(this._sortListenersOfFixedPriorityAsc); + + // FIXME: Should use binary search + let index = 0; + for (const len = fixedListeners.length; index < len;) { + if (fixedListeners[index]._getFixedPriority() >= 0) { + break; + } + ++index; + } + listeners.gt0Index = index; + } + + private _sortListenersOfFixedPriorityAsc (l1, l2) { + return l1._getFixedPriority() - l2._getFixedPriority(); + } + + private _onUpdateListeners (listeners) { + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + const toRemovedListeners = this._toRemovedListeners; + + if (sceneGraphPriorityListeners) { + for (let i = 0; i < sceneGraphPriorityListeners.length;) { + const selListener = sceneGraphPriorityListeners[i]; + if (!selListener._isRegistered()) { + cc.js.array.remove(sceneGraphPriorityListeners, selListener); + // if item in toRemove list, remove it from the list + const idx = toRemovedListeners.indexOf(selListener); + if (idx !== -1) { + toRemovedListeners.splice(idx, 1); + } + } else { + ++i; + } + } + } + + if (fixedPriorityListeners) { + for (let i = 0; i < fixedPriorityListeners.length;) { + const selListener = fixedPriorityListeners[i]; + if (!selListener._isRegistered()) { + cc.js.array.remove(fixedPriorityListeners, selListener); + // if item in toRemove list, remove it from the list + const idx = toRemovedListeners.indexOf(selListener); + if (idx !== -1) { + toRemovedListeners.splice(idx, 1); + } + } else { + ++i; + } + } + } + + if (sceneGraphPriorityListeners && sceneGraphPriorityListeners.length === 0) { + listeners.clearSceneGraphListeners(); + } + + if (fixedPriorityListeners && fixedPriorityListeners.length === 0) { + listeners.clearFixedListeners(); + } + } + + private _updateTouchListeners (event) { + const locInDispatch = this._inDispatch; + cc.assertID(locInDispatch > 0, 3508); + + if (locInDispatch > 1) { + return; + } + + let listeners; + listeners = this._listenersMap[ListenerID.TOUCH_ONE_BY_ONE]; + if (listeners) { + this._onUpdateListeners(listeners); + } + listeners = this._listenersMap[ListenerID.TOUCH_ALL_AT_ONCE]; + if (listeners) { + this._onUpdateListeners(listeners); + } + + cc.assertID(locInDispatch === 1, 3509); + + const locToAddedListeners = this._toAddedListeners; + if (locToAddedListeners.length !== 0) { + for (let i = 0, len = locToAddedListeners.length; i < len; i++) { + this._forceAddEventListener(locToAddedListeners[i]); + } + this._toAddedListeners.length = 0; + } + + if (this._toRemovedListeners.length !== 0) { + this._cleanToRemovedListeners(); + } + } + + // Remove all listeners in _toRemoveListeners list and cleanup + private _cleanToRemovedListeners () { + const toRemovedListeners = this._toRemovedListeners; + for (const selListener of toRemovedListeners) { + const listeners = this._listenersMap[selListener._getListenerID()]; + if (!listeners) { + continue; + } + + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + + if (sceneGraphPriorityListeners) { + const idx = sceneGraphPriorityListeners.indexOf(selListener); + if (idx !== -1) { + sceneGraphPriorityListeners.splice(idx, 1); + } + } + if (fixedPriorityListeners) { + const idx = fixedPriorityListeners.indexOf(selListener); + if (idx !== -1) { + fixedPriorityListeners.splice(idx, 1); + } + } + } + toRemovedListeners.length = 0; + } + + private _onTouchEventCallback (listener, argsObj) { + // Skip if the listener was removed. + if (!listener._isRegistered) { + return false; + } + + const event = argsObj.event; + const selTouch = event.currentTouch; + event.currentTarget = listener._node; + + let isClaimed = false; + let removedIdx; + const getCode = event.getEventCode(); + const EventTouch = cc.Event.EventTouch; + if (getCode === EventTouch.BEGAN) { + if (listener.onTouchBegan) { + isClaimed = listener.onTouchBegan(selTouch, event); + if (isClaimed && listener._registered) { + listener._claimedTouches.push(selTouch); + } + } + } else if (listener._claimedTouches.length > 0) { + removedIdx = listener._claimedTouches.indexOf(selTouch); + if (removedIdx !== -1) { + isClaimed = true; + if (getCode === EventTouch.MOVED && listener.onTouchMoved) { + listener.onTouchMoved(selTouch, event); + } else if (getCode === EventTouch.ENDED) { + if (listener.onTouchEnded) { + listener.onTouchEnded(selTouch, event); + } + if (listener._registered) { + listener._claimedTouches.splice(removedIdx, 1); + } + } else if (getCode === EventTouch.CANCELLED) { + if (listener.onTouchCancelled) { + listener.onTouchCancelled(selTouch, event); + } + if (listener._registered) { + listener._claimedTouches.splice(removedIdx, 1); + } + } + } + } + + // If the event was stopped, return directly. + if (event.isStopped()) { + eventManager._updateTouchListeners(event); + return true; + } + + if (isClaimed && listener._registered && listener.swallowTouches) { + if (argsObj.needsMutableSet) { + argsObj.touches.splice(selTouch, 1); + } + return true; + } + return false; + } + + private _dispatchTouchEvent (event) { + this._sortEventListeners(ListenerID.TOUCH_ONE_BY_ONE); + this._sortEventListeners(ListenerID.TOUCH_ALL_AT_ONCE); + + const oneByOneListeners = this._getListeners(ListenerID.TOUCH_ONE_BY_ONE); + const allAtOnceListeners = this._getListeners(ListenerID.TOUCH_ALL_AT_ONCE); + + // If there aren't any touch listeners, return directly. + if (null === oneByOneListeners && null === allAtOnceListeners) { + return; + } + + const originalTouches = event.getTouches(); + const mutableTouches = cc.js.array.copy(originalTouches); + const oneByOneArgsObj = { event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null }; + + // + // process the target handlers 1st + // + if (oneByOneListeners) { + for (const originalTouch of originalTouches) { + event.currentTouch = originalTouch; + event._propagationStopped = event._propagationImmediateStopped = false; + this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj); + } + } + + // + // process standard handlers 2nd + // + if (allAtOnceListeners && mutableTouches.length > 0) { + this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, { event, touches: mutableTouches }); + if (event.isStopped()) { + return; + } + } + this._updateTouchListeners(event); + } + + private _onTouchesEventCallback (listener, callbackParams) { + // Skip if the listener was removed. + if (!listener._registered) { + return false; + } + + const EventTouch = cc.Event.EventTouch; + const event = callbackParams.event; + const touches = callbackParams.touches; + const getCode = event.getEventCode(); + event.currentTarget = listener._node; + if (getCode === EventTouch.BEGAN && listener.onTouchesBegan) { + listener.onTouchesBegan(touches, event); + } else if (getCode === EventTouch.MOVED && listener.onTouchesMoved) { + listener.onTouchesMoved(touches, event); + } else if (getCode === EventTouch.ENDED && listener.onTouchesEnded) { + listener.onTouchesEnded(touches, event); + } else if (getCode === EventTouch.CANCELLED && listener.onTouchesCancelled) { + listener.onTouchesCancelled(touches, event); + } + + // If the event was stopped, return directly. + if (event.isStopped()) { + eventManager._updateTouchListeners(event); + return true; + } + return false; + } + + private _associateNodeAndEventListener (node, listener) { + let listeners = this._nodeListenersMap[node._id]; + if (!listeners) { + listeners = []; + this._nodeListenersMap[node._id] = listeners; + } + listeners.push(listener); + } + + private _dissociateNodeAndEventListener (node, listener) { + const listeners = this._nodeListenersMap[node._id]; + if (listeners) { + cc.js.array.remove(listeners, listener); + if (listeners.length === 0) { + delete this._nodeListenersMap[node._id]; + } + } + } + + private _dispatchEventToListeners (listeners, onEvent, eventOrArgs) { + let shouldStopPropagation = false; + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + + let i = 0; + if (fixedPriorityListeners) { // priority < 0 + if (fixedPriorityListeners.length !== 0) { + for (; i < listeners.gt0Index; ++i) { + const selListener = fixedPriorityListeners[i]; + if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { + shouldStopPropagation = true; + break; + } + } + } + } + + if (sceneGraphPriorityListeners && !shouldStopPropagation) { // priority == 0, scene graph priority + for (const selListener of sceneGraphPriorityListeners) { + if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { + shouldStopPropagation = true; + break; + } + } + } + + if (fixedPriorityListeners && !shouldStopPropagation) { // priority > 0 + for (; i < fixedPriorityListeners.length; ++i) { + const selListener = fixedPriorityListeners[i]; + if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { + shouldStopPropagation = true; + break; + } + } + } + } + + private _setDirty (listenerID, flag) { + const locDirtyFlagMap = this._priorityDirtyFlagMap; + if (locDirtyFlagMap[listenerID] == null) { + locDirtyFlagMap[listenerID] = flag; + } else { + locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID]; + } + } + + private _visitTarget (node, isRootNode) { + // sortAllChildren is performed the next frame, but the event is executed immediately. + if (node._reorderChildDirty) { + node.sortAllChildren(); + } + const children = node.children; + let i = 0; + const childrenCount = children.length; + let locGlobalZOrderNodeMap = this._globalZOrderNodeMap; + const locNodeListenersMap = this._nodeListenersMap; + + if (childrenCount > 0) { + if (locNodeListenersMap[node._id] !== undefined) { + if (!locGlobalZOrderNodeMap) { + locGlobalZOrderNodeMap = []; + } + locGlobalZOrderNodeMap.push(node._id); + } + + let child; + for (; i < childrenCount; i++) { + child = children[i]; + if (child) { + this._visitTarget(child, false); + } + } + } else { + if (locNodeListenersMap[node._id] !== undefined) { + if (!locGlobalZOrderNodeMap) { + locGlobalZOrderNodeMap = []; + } + locGlobalZOrderNodeMap.push(node._id); + } + } + + if (isRootNode) { + const locNodePriorityMap = this._nodePriorityMap; + for (const locGlobalZOrderNode of locGlobalZOrderNodeMap) { + locNodePriorityMap[locGlobalZOrderNode] = ++this._nodePriorityIndex; + } + this._globalZOrderNodeMap.length = 0; + } + } + + private _sortNumberAsc (a, b) { + return a - b; + } + + private _removeListenerInCallback (listeners: EventListener[], callback) { + if (listeners == null) { + return false; + } + + for (let i = 0, len = listeners.length; i < len; i++) { + const selListener = listeners[i]; + if (selListener._onCustomEvent === callback || selListener.onEvent === callback) { + selListener._setRegistered(false); + if (selListener._getSceneGraphPriority() != null) { + this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); + // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. + selListener._setSceneGraphPriority(null); + } + + if (this._inDispatch === 0) { + cc.js.array.remove(listeners, selListener); + } else { + this._toRemovedListeners.push(selListener); + } + return true; + } + } + return false; + } + + private _removeListenerInVector (listeners: EventListener[], listener: EventListener) { + if (listeners == null) { + return false; + } + + for (let i = 0, len = listeners.length; i < len; i++) { + const selListener = listeners[i]; + if (selListener === listener) { + selListener._setRegistered(false); + if (selListener._getSceneGraphPriority() != null) { + this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); + // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. + selListener._setSceneGraphPriority(null); + } + + if (this._inDispatch === 0) { + cc.js.array.remove(listeners, selListener); + } else { + this._toRemovedListeners.push(selListener); + } + return true; + } + } + return false; + } } +/** + * !#en + * This class has been deprecated, please use cc.systemEvent or cc.EventTarget instead. + * See [Listen to and launch events](../../../manual/en/scripting/events.md) for details.
+ *
+ * cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching. + * The EventListener list is managed in such way so that event listeners can be added and removed + * while events are being dispatched. + * + * !#zh + * 该类已废弃,请使用 cc.systemEvent 或 cc.EventTarget 代替,详见 [监听和发射事件](../../../manual/zh/scripting/events.md)。
+ *
+ * 事件管理器,它主要管理事件监听器注册和派发系统事件。 + * + * @class eventManager + * @static + * @example {@link cocos2d/core/event-manager/CCEventManager/addListener.js} + * @deprecated + */ +export const eventManager = new EventManager(); + cc.eventManager = eventManager; -export default eventManager \ No newline at end of file +export default eventManager; diff --git a/cocos/core/platform/event-manager/CCInputManager.js b/cocos/core/platform/event-manager/CCInputManager.js deleted file mode 100644 index af56dcff40..0000000000 --- a/cocos/core/platform/event-manager/CCInputManager.js +++ /dev/null @@ -1,759 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -import macro from '../CCMacro'; -import sys from '../CCSys'; -import eventManager from './CCEventManager'; - -const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; - -const PORTRAIT = 0; -const LANDSCAPE_LEFT = -90; -const PORTRAIT_UPSIDE_DOWN = 180; -const LANDSCAPE_RIGHT = 90; - -let _didAccelerateFun; -let _vec2 = cc.v2(); - -/** - * !#en the device accelerometer reports values for each axis in units of g-force. - * !#zh 设备重力传感器传递的各个轴的数据。 - * @class Acceleration - * @method constructor - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @param {Number} timestamp - */ -let Acceleration = function (x, y, z, timestamp) { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.timestamp = timestamp || 0; -}; - -/** - * This class manages all events of input. include: touch, mouse, accelerometer, keyboard - */ -let inputManager = { - _mousePressed: false, - - _isRegisterEvent: false, - - _preTouchPoint: cc.v2(0,0), - _prevMousePoint: cc.v2(0,0), - - _preTouchPool: [], - _preTouchPoolPointer: 0, - - _touches: [], - _touchesIntegerDict:{}, - - _indexBitsUsed: 0, - _maxTouches: 8, - - _accelEnabled: false, - _accelInterval: 1/5, - _accelMinus: 1, - _accelCurTime: 0, - _acceleration: null, - _accelDeviceEvent: null, - - _getUnUsedIndex () { - let temp = this._indexBitsUsed; - let now = cc.sys.now(); - - for (let i = 0; i < this._maxTouches; i++) { - if (!(temp & 0x00000001)) { - this._indexBitsUsed |= (1 << i); - return i; - } - else { - let touch = this._touches[i]; - if (now - touch._lastModified > TOUCH_TIMEOUT) { - this._removeUsedIndexBit(i); - delete this._touchesIntegerDict[touch.getID()]; - return i; - } - } - temp >>= 1; - } - - // all bits are used - return -1; - }, - - _removeUsedIndexBit (index) { - if (index < 0 || index >= this._maxTouches) - return; - - let temp = 1 << index; - temp = ~temp; - this._indexBitsUsed &= temp; - }, - - _glView: null, - - /** - * @method handleTouchesBegin - * @param {Array} touches - */ - handleTouchesBegin (touches) { - let selTouch, index, curTouch, touchID, - handleTouches = [], locTouchIntDict = this._touchesIntegerDict, - now = sys.now(); - for (let i = 0, len = touches.length; i < len; i ++) { - selTouch = touches[i]; - touchID = selTouch.getID(); - index = locTouchIntDict[touchID]; - - if (index == null) { - let unusedIndex = this._getUnUsedIndex(); - if (unusedIndex === -1) { - cc.logID(2300, unusedIndex); - continue; - } - //curTouch = this._touches[unusedIndex] = selTouch; - curTouch = this._touches[unusedIndex] = new cc.Touch(selTouch._point.x, selTouch._point.y, selTouch.getID()); - curTouch._lastModified = now; - curTouch._setPrevPoint(selTouch._prevPoint); - locTouchIntDict[touchID] = unusedIndex; - handleTouches.push(curTouch); - } - } - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.BEGAN; - eventManager.dispatchEvent(touchEvent); - } - }, - - /** - * @method handleTouchesMove - * @param {Array} touches - */ - handleTouchesMove (touches) { - let selTouch, index, touchID, - handleTouches = [], locTouches = this._touches, - now = sys.now(); - for (let i = 0, len = touches.length; i < len; i++) { - selTouch = touches[i]; - touchID = selTouch.getID(); - index = this._touchesIntegerDict[touchID]; - - if (index == null) { - //cc.log("if the index doesn't exist, it is an error"); - continue; - } - if (locTouches[index]) { - locTouches[index]._setPoint(selTouch._point); - locTouches[index]._setPrevPoint(selTouch._prevPoint); - locTouches[index]._lastModified = now; - handleTouches.push(locTouches[index]); - } - } - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.MOVED; - eventManager.dispatchEvent(touchEvent); - } - }, - - /** - * @method handleTouchesEnd - * @param {Array} touches - */ - handleTouchesEnd (touches) { - let handleTouches = this.getSetOfTouchesEndOrCancel(touches); - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.ENDED; - eventManager.dispatchEvent(touchEvent); - } - this._preTouchPool.length = 0; - }, - - /** - * @method handleTouchesCancel - * @param {Array} touches - */ - handleTouchesCancel (touches) { - let handleTouches = this.getSetOfTouchesEndOrCancel(touches); - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.CANCELLED; - eventManager.dispatchEvent(touchEvent); - } - this._preTouchPool.length = 0; - }, - - /** - * @method getSetOfTouchesEndOrCancel - * @param {Array} touches - * @returns {Array} - */ - getSetOfTouchesEndOrCancel (touches) { - let selTouch, index, touchID, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict; - for (let i = 0, len = touches.length; i< len; i ++) { - selTouch = touches[i]; - touchID = selTouch.getID(); - index = locTouchesIntDict[touchID]; - - if (index == null) { - continue; //cc.log("if the index doesn't exist, it is an error"); - } - if (locTouches[index]) { - locTouches[index]._setPoint(selTouch._point); - locTouches[index]._setPrevPoint(selTouch._prevPoint); - handleTouches.push(locTouches[index]); - this._removeUsedIndexBit(index); - delete locTouchesIntDict[touchID]; - } - } - return handleTouches; - }, - - /** - * @method getHTMLElementPosition - * @param {HTMLElement} element - * @return {Object} - */ - getHTMLElementPosition (element) { - if (sys.platform === sys.WECHAT_GAME) { - return { - left: 0, - top: 0, - width: window.innerWidth, - height: window.innerHeight - }; - } - - let docElem = document.documentElement; - let leftOffset = window.pageXOffset - docElem.clientLeft; - let topOffset = window.pageYOffset - docElem.clientTop; - if (element.getBoundingClientRect) { - let box = element.getBoundingClientRect(); - return { - left: box.left + leftOffset, - top: box.top + topOffset, - width: box.width, - height: box.height - }; - } - else { - if (element instanceof HTMLCanvasElement) { - return { - left: leftOffset, - top: topOffset, - width: element.width, - height: element.height - }; - } - else { - return { - left: leftOffset, - top: topOffset, - width: parseInt(element.style.width), - height: parseInt(element.style.height) - }; - } - } - }, - - /** - * @method getPreTouch - * @param {Touch} touch - * @return {Touch} - */ - getPreTouch (touch) { - let preTouch = null; - let locPreTouchPool = this._preTouchPool; - let id = touch.getID(); - for (let i = locPreTouchPool.length - 1; i >= 0; i--) { - if (locPreTouchPool[i].getID() === id) { - preTouch = locPreTouchPool[i]; - break; - } - } - if (!preTouch) - preTouch = touch; - return preTouch; - }, - - /** - * @method setPreTouch - * @param {Touch} touch - */ - setPreTouch (touch) { - let find = false; - let locPreTouchPool = this._preTouchPool; - let id = touch.getID(); - for (let i = locPreTouchPool.length - 1; i >= 0; i--) { - if (locPreTouchPool[i].getID() === id) { - locPreTouchPool[i] = touch; - find = true; - break; - } - } - if (!find) { - if (locPreTouchPool.length <= 50) { - locPreTouchPool.push(touch); - } else { - locPreTouchPool[this._preTouchPoolPointer] = touch; - this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50; - } - } - }, - - /** - * @method getTouchByXY - * @param {Number} tx - * @param {Number} ty - * @param {Vec2} pos - * @return {Touch} - */ - getTouchByXY (tx, ty, pos) { - let locPreTouch = this._preTouchPoint; - let location = this._glView.convertToLocationInView(tx, ty, pos); - let touch = new cc.Touch(location.x, location.y, 0); - touch._setPrevPoint(locPreTouch.x, locPreTouch.y); - locPreTouch.x = location.x; - locPreTouch.y = location.y; - return touch; - }, - - /** - * @method getMouseEvent - * @param {Vec2} location - * @param {Vec2} pos - * @param {Number} eventType - * @returns {Event.EventMouse} - */ - getMouseEvent (location, pos, eventType) { - let locPreMouse = this._prevMousePoint; - let mouseEvent = new cc.Event.EventMouse(eventType); - mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y); - locPreMouse.x = location.x; - locPreMouse.y = location.y; - this._glView._convertMouseToLocationInView(locPreMouse, pos); - mouseEvent.setLocation(locPreMouse.x, locPreMouse.y); - return mouseEvent; - }, - - /** - * @method getPointByEvent - * @param {Touch} event - * @param {Vec2} pos - * @return {Vec2} - */ - getPointByEvent (event, pos) { - if (event.pageX != null) //not avalable in <= IE8 - return {x: event.pageX, y: event.pageY}; - - if (sys.platform === sys.WECHAT_GAME) { - pos.left = 0; - pos.top = 0; - } - else { - pos.left -= document.body.scrollLeft; - pos.top -= document.body.scrollTop; - } - return {x: event.clientX, y: event.clientY}; - }, - - /** - * @method getTouchesByEvent - * @param {Touch} event - * @param {Vec2} pos - * @returns {Array} - */ - getTouchesByEvent (event, pos) { - let touchArr = [], locView = this._glView; - let touch_event, touch, preLocation; - let locPreTouch = this._preTouchPoint; - - let length = event.changedTouches.length; - for (let i = 0; i < length; i++) { - touch_event = event.changedTouches[i]; - if (touch_event) { - let location; - if (sys.BROWSER_TYPE_FIREFOX === sys.browserType) - location = locView.convertToLocationInView(touch_event.pageX, touch_event.pageY, pos, _vec2); - else - location = locView.convertToLocationInView(touch_event.clientX, touch_event.clientY, pos, _vec2); - if (touch_event.identifier != null) { - touch = new cc.Touch(location.x, location.y, touch_event.identifier); - //use Touch Pool - preLocation = this.getPreTouch(touch).getLocation(); - touch._setPrevPoint(preLocation.x, preLocation.y); - this.setPreTouch(touch); - } else { - touch = new cc.Touch(location.x, location.y); - touch._setPrevPoint(locPreTouch.x, locPreTouch.y); - } - locPreTouch.x = location.x; - locPreTouch.y = location.y; - touchArr.push(touch); - } - } - return touchArr; - }, - - /** - * @method registerSystemEvent - * @param {HTMLElement} element - */ - registerSystemEvent (element) { - if(this._isRegisterEvent) return; - - this._glView = cc.view; - let selfPointer = this; - - let prohibition = sys.isMobile; - let supportMouse = ('mouse' in sys.capabilities); - let supportTouches = ('touches' in sys.capabilities); - - if (sys.platform === sys.WECHAT_GAME) { - prohibition = false; - supportTouches = true; - supportMouse = false; - } - - if (supportMouse) { - //HACK - // - At the same time to trigger the ontouch event and onmouse event - // - The function will execute 2 times - //The known browser: - // liebiao - // miui - // WECHAT - if (!prohibition) { - window.addEventListener('mousedown', function () { - selfPointer._mousePressed = true; - }, false); - - window.addEventListener('mouseup', function (event) { - if (!selfPointer._mousePressed) - return; - - selfPointer._mousePressed = false; - - let pos = selfPointer.getHTMLElementPosition(element); - let location = selfPointer.getPointByEvent(event, pos); - if (!cc.rect(pos.left, pos.top, pos.width, pos.height).contains(location)){ - selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]); - - let mouseEvent = selfPointer.getMouseEvent(location,pos,cc.Event.EventMouse.UP); - mouseEvent.setButton(event.button); - eventManager.dispatchEvent(mouseEvent); - } - }, false); - } - - // register canvas mouse event - let EventMouse = cc.Event.EventMouse; - let _mouseEventsOnElement = [ - !prohibition && ["mousedown", EventMouse.DOWN, function (event, mouseEvent, location, pos) { - selfPointer._mousePressed = true; - selfPointer.handleTouchesBegin([selfPointer.getTouchByXY(location.x, location.y, pos)]); - element.focus(); - }], - !prohibition && ["mouseup", EventMouse.UP, function (event, mouseEvent, location, pos) { - selfPointer._mousePressed = false; - selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]); - }], - !prohibition && ["mousemove", EventMouse.MOVE, function (event, mouseEvent, location, pos) { - selfPointer.handleTouchesMove([selfPointer.getTouchByXY(location.x, location.y, pos)]); - if (!selfPointer._mousePressed) { - mouseEvent.setButton(null); - } - if (event.movementX !== undefined && event.movementY !== undefined) { - mouseEvent.movementX = event.movementX; - mouseEvent.movementY = event.movementY; - } - }], - ["mousewheel", EventMouse.SCROLL, function (event, mouseEvent) { - mouseEvent.setScrollData(0, event.wheelDelta); - }], - /* firefox fix */ - ["DOMMouseScroll", EventMouse.SCROLL, function (event, mouseEvent) { - mouseEvent.setScrollData(0, event.detail * -120); - }] - ]; - for (let i = 0; i < _mouseEventsOnElement.length; ++i) { - let entry = _mouseEventsOnElement[i]; - if (entry) { - let name = entry[0]; - let type = entry[1]; - let handler = entry[2]; - element.addEventListener(name, function (event) { - let pos = selfPointer.getHTMLElementPosition(element); - let location = selfPointer.getPointByEvent(event, pos); - let mouseEvent = selfPointer.getMouseEvent(location, pos, type); - mouseEvent.setButton(event.button); - - handler(event, mouseEvent, location, pos); - - eventManager.dispatchEvent(mouseEvent); - event.stopPropagation(); - event.preventDefault(); - }, false); - } - } - } - - if (window.navigator.msPointerEnabled) { - let _pointerEventsMap = { - "MSPointerDown" : selfPointer.handleTouchesBegin, - "MSPointerMove" : selfPointer.handleTouchesMove, - "MSPointerUp" : selfPointer.handleTouchesEnd, - "MSPointerCancel" : selfPointer.handleTouchesCancel - }; - for (let eventName in _pointerEventsMap) { - let touchEvent = _pointerEventsMap[eventName]; - element.addEventListener(eventName, function (event){ - let pos = selfPointer.getHTMLElementPosition(element); - pos.left -= document.documentElement.scrollLeft; - pos.top -= document.documentElement.scrollTop; - - touchEvent.call(selfPointer, [selfPointer.getTouchByXY(event.clientX, event.clientY, pos)]); - event.stopPropagation(); - }, false); - } - } - - //register touch event - if (supportTouches) { - let _touchEventsMap = { - "touchstart": function (touchesToHandle) { - selfPointer.handleTouchesBegin(touchesToHandle); - if (sys.platform !== sys.WECHAT_GAME) { - element.focus(); - } - }, - "touchmove": function (touchesToHandle) { - selfPointer.handleTouchesMove(touchesToHandle); - }, - "touchend": function (touchesToHandle) { - selfPointer.handleTouchesEnd(touchesToHandle); - }, - "touchcancel": function (touchesToHandle) { - selfPointer.handleTouchesCancel(touchesToHandle); - } - }; - - let registerTouchEvent; - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - _touchEventsMap = { - onTouchStart: _touchEventsMap.touchstart, - onTouchMove: _touchEventsMap.touchmove, - onTouchEnd: _touchEventsMap.touchend, - onTouchCancel: _touchEventsMap.touchcancel, - }; - registerTouchEvent = function(eventName) { - let handler = _touchEventsMap[eventName]; - wx[eventName](function(event) { - if (!event.changedTouches) return; - let pos = selfPointer.getHTMLElementPosition(element); - let body = document.body; - pos.left -= body.scrollLeft || 0; - pos.top -= body.scrollTop || 0; - handler(selfPointer.getTouchesByEvent(event, pos)); - }); - }; - } - else { - registerTouchEvent = function(eventName) { - let handler = _touchEventsMap[eventName]; - element.addEventListener(eventName, (function(event) { - if (!event.changedTouches) return; - let pos = selfPointer.getHTMLElementPosition(element); - let body = document.body; - pos.left -= body.scrollLeft || 0; - pos.top -= body.scrollTop || 0; - handler(selfPointer.getTouchesByEvent(event, pos)); - event.stopPropagation(); - event.preventDefault(); - }), false); - }; - } - for (let eventName in _touchEventsMap) { - registerTouchEvent(eventName); - } - } - - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - //register keyboard event - this._registerKeyboardEvent(); - } - - this._isRegisterEvent = true; - }, - - /** - * whether enable accelerometer event - * @method setAccelerometerEnabled - * @param {Boolean} isEnable - */ - setAccelerometerEnabled (isEnable) { - let _t = this; - if(_t._accelEnabled === isEnable) - return; - - _t._accelEnabled = isEnable; - let scheduler = cc.director.getScheduler(); - scheduler.enableForTarget(_t); - if (_t._accelEnabled) { - _t._registerAccelerometerEvent(); - _t._accelCurTime = 0; - scheduler.scheduleUpdate(_t); - } else { - _t._unregisterAccelerometerEvent(); - _t._accelCurTime = 0; - scheduler.unscheduleUpdate(_t); - } - }, - - /** - * set accelerometer interval value - * @method setAccelerometerInterval - * @param {Number} interval - */ - setAccelerometerInterval (interval) { - if (this._accelInterval !== interval) { - this._accelInterval = interval; - } - }, - - _registerKeyboardEvent () { - cc.game.canvas.addEventListener("keydown", function (e) { - eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, true)); - e.stopPropagation(); - e.preventDefault(); - }, false); - cc.game.canvas.addEventListener("keyup", function (e) { - eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, false)); - e.stopPropagation(); - e.preventDefault(); - }, false); - }, - - _registerAccelerometerEvent () { - let w = window, _t = this; - _t._acceleration = new Acceleration(); - _t._accelDeviceEvent = w.DeviceMotionEvent || w.DeviceOrientationEvent; - - //TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) - _t._accelDeviceEvent = window.DeviceOrientationEvent; - - let _deviceEventType = (_t._accelDeviceEvent === w.DeviceMotionEvent) ? "devicemotion" : "deviceorientation"; - let ua = navigator.userAgent; - if (/Android/.test(ua) || (/Adr/.test(ua) && cc.sys.browserType === cc.BROWSER_TYPE_UC)) { - _t._minus = -1; - } - - _didAccelerateFun = _t.didAccelerate.bind(_t); - w.addEventListener(_deviceEventType, _didAccelerateFun, false); - }, - - _unregisterAccelerometerEvent () { - let w = window, _t = this; - let _deviceEventType = (_t._accelDeviceEvent === w.DeviceMotionEvent) ? "devicemotion" : "deviceorientation"; - if (_didAccelerateFun) { - w.removeEventListener(_deviceEventType, _didAccelerateFun, false); - } - }, - - didAccelerate (eventData) { - let _t = this, w = window; - if (!_t._accelEnabled) - return; - - let mAcceleration = _t._acceleration; - - let x, y, z; - - if (_t._accelDeviceEvent === window.DeviceMotionEvent) { - let eventAcceleration = eventData["accelerationIncludingGravity"]; - x = _t._accelMinus * eventAcceleration.x * 0.1; - y = _t._accelMinus * eventAcceleration.y * 0.1; - z = eventAcceleration.z * 0.1; - } else { - x = (eventData["gamma"] / 90) * 0.981; - y = -(eventData["beta"] / 90) * 0.981; - z = (eventData["alpha"] / 90) * 0.981; - } - - if (cc.view._isRotated) { - let tmp = x; - x = -y; - y = tmp; - } - mAcceleration.x = x; - mAcceleration.y = y; - mAcceleration.z = z; - - mAcceleration.timestamp = eventData.timeStamp || Date.now(); - - let tmpX = mAcceleration.x; - if (w.orientation === LANDSCAPE_RIGHT) { - mAcceleration.x = -mAcceleration.y; - mAcceleration.y = tmpX; - } else if (w.orientation === LANDSCAPE_LEFT) { - mAcceleration.x = mAcceleration.y; - mAcceleration.y = -tmpX; - } else if (w.orientation === PORTRAIT_UPSIDE_DOWN) { - mAcceleration.x = -mAcceleration.x; - mAcceleration.y = -mAcceleration.y; - } - // fix android acc values are opposite - if (cc.sys.os === cc.sys.OS_ANDROID && - cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ) { - mAcceleration.x = -mAcceleration.x; - mAcceleration.y = -mAcceleration.y; - } - }, - - /** - * @method update - * @param {Number} dt - */ - update (dt) { - if (this._accelCurTime > this._accelInterval) { - this._accelCurTime -= this._accelInterval; - eventManager.dispatchEvent(new cc.Event.EventAcceleration(this._acceleration)); - } - this._accelCurTime += dt; - } -}; - -_cc.inputManager = inputManager; -export default inputManager; \ No newline at end of file diff --git a/cocos/core/platform/event-manager/CCInputManager.ts b/cocos/core/platform/event-manager/CCInputManager.ts new file mode 100644 index 0000000000..9820040367 --- /dev/null +++ b/cocos/core/platform/event-manager/CCInputManager.ts @@ -0,0 +1,786 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { rect } from '../../value-types/rect'; +import Vec2, { v2 } from '../../value-types/vec2'; +import macro from '../CCMacro'; +import sys from '../CCSys'; +import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './CCEvent'; +import eventManager from './CCEventManager'; +import CCTouch from './CCTouch'; + +const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; + +const PORTRAIT = 0; +const LANDSCAPE_LEFT = -90; +const PORTRAIT_UPSIDE_DOWN = 180; +const LANDSCAPE_RIGHT = 90; + +let _didAccelerateFun; + +const _vec2 = v2(); + +interface IHTMLElementPosition { + left: number; + top: number; + width: number; + height: number; +} + +interface IView { + convertToLocationInView (tx: number, ty: number, elementPosition: IHTMLElementPosition, out?: Vec2): Vec2; + + _convertMouseToLocationInView (point: Vec2, elementPosition: IHTMLElementPosition): void; + + _convertTouchesWithScale (touches: CCTouch[]): void; +} + +/** + * !#en the device accelerometer reports values for each axis in units of g-force. + * !#zh 设备重力传感器传递的各个轴的数据。 + */ +class Acceleration { + public x: number; + public y: number; + public z: number; + public timestamp: number; + constructor (x = 0, y = 0, z = 0, timestamp = 0) { + this.x = x; + this.y = y; + this.z = z; + this.timestamp = timestamp; + } +} + +/** + * This class manages all events of input. include: touch, mouse, accelerometer, keyboard + */ +class InputManager { + private _mousePressed = false; + + private _isRegisterEvent = false; + + private _preTouchPoint = v2(0, 0); + private _prevMousePoint = v2(0, 0); + + private _preTouchPool: CCTouch[] = []; + private _preTouchPoolPointer = 0; + + private _touches: CCTouch[] = []; + private _touchesIntegerDict: { [index: number]: number | undefined; } = { }; + + private _indexBitsUsed = 0; + private _maxTouches = 8; + + private _accelEnabled = false; + private _accelInterval = 1 / 5; + private _accelMinus = 1; + private _accelCurTime = 0; + private _acceleration: Acceleration | null = null; + private _accelDeviceEvent = null; + + private _glView: IView | null = null; + + private _minus = 0; + + public handleTouchesBegin (touches: CCTouch[]) { + const handleTouches: CCTouch[] = []; + const locTouchIntDict = this._touchesIntegerDict; + const now = sys.now(); + for (const touch of touches) { + const touchID = touch.getID(); + if (touchID === null) { + continue; + } + const index = locTouchIntDict[touchID]; + if (index === undefined) { + continue; + } + const unusedIndex = this._getUnUsedIndex(); + if (unusedIndex === -1) { + cc.logID(2300, unusedIndex); + continue; + } + // curTouch = this._touches[unusedIndex] = touch; + const curTouch = new CCTouch(touch._point.x, touch._point.y, touch.getID()); + this._touches[unusedIndex] = curTouch; + curTouch._lastModified = now; + curTouch._setPrevPoint(touch._prevPoint); + locTouchIntDict[touchID] = unusedIndex; + handleTouches.push(curTouch); + } + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.BEGAN; + eventManager.dispatchEvent(touchEvent); + } + } + + public handleTouchesMove (touches: CCTouch[]) { + const handleTouches: CCTouch[] = []; + const locTouches = this._touches; + const now = sys.now(); + for (const touch of touches) { + const touchID = touch.getID(); + if (touchID === null) { + continue; + } + const index = this._touchesIntegerDict[touchID]; + if (index === undefined) { + // cc.log("if the index doesn't exist, it is an error"); + continue; + } + if (locTouches[index]) { + locTouches[index]._setPoint(touch._point); + locTouches[index]._setPrevPoint(touch._prevPoint); + locTouches[index]._lastModified = now; + handleTouches.push(locTouches[index]); + } + } + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.MOVED; + eventManager.dispatchEvent(touchEvent); + } + } + + public handleTouchesEnd (touches: CCTouch[]) { + const handleTouches = this.getSetOfTouchesEndOrCancel(touches); + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.ENDED; + eventManager.dispatchEvent(touchEvent); + } + this._preTouchPool.length = 0; + } + + public handleTouchesCancel (touches: CCTouch[]) { + const handleTouches = this.getSetOfTouchesEndOrCancel(touches); + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.CANCELLED; + eventManager.dispatchEvent(touchEvent); + } + this._preTouchPool.length = 0; + } + + public getSetOfTouchesEndOrCancel (touches: CCTouch[]) { + const handleTouches: CCTouch[] = []; + const locTouches = this._touches; + const locTouchesIntDict = this._touchesIntegerDict; + for (const touch of touches) { + const touchID = touch.getID(); + if (touchID === null) { + continue; + } + const index = locTouchesIntDict[touchID]; + if (index === undefined) { + // cc.log("if the index doesn't exist, it is an error"); + continue; + } + if (locTouches[index]) { + locTouches[index]._setPoint(touch._point); + locTouches[index]._setPrevPoint(touch._prevPoint); + handleTouches.push(locTouches[index]); + this._removeUsedIndexBit(index); + delete locTouchesIntDict[touchID]; + } + } + return handleTouches; + } + + public getHTMLElementPosition (element: HTMLElement): IHTMLElementPosition { + if (sys.platform === sys.WECHAT_GAME) { + return { + left: 0, + top: 0, + width: window.innerWidth, + height: window.innerHeight, + }; + } + + const docElem = document.documentElement; + const leftOffset = window.pageXOffset - docElem.clientLeft; + const topOffset = window.pageYOffset - docElem.clientTop; + if (element.getBoundingClientRect) { + const box = element.getBoundingClientRect(); + return { + left: box.left + leftOffset, + top: box.top + topOffset, + width: box.width, + height: box.height, + }; + } else { + if (element instanceof HTMLCanvasElement) { + return { + left: leftOffset, + top: topOffset, + width: element.width, + height: element.height, + }; + } else { + return { + left: leftOffset, + top: topOffset, + width: parseInt(element.style.width || '0', undefined), + height: parseInt(element.style.height || '0', undefined), + }; + } + } + } + + public getPreTouch (touch: CCTouch) { + let preTouch: CCTouch | null = null; + const locPreTouchPool = this._preTouchPool; + const id = touch.getID(); + for (let i = locPreTouchPool.length - 1; i >= 0; i--) { + if (locPreTouchPool[i].getID() === id) { + preTouch = locPreTouchPool[i]; + break; + } + } + if (!preTouch) { + preTouch = touch; + } + return preTouch; + } + + public setPreTouch (touch: CCTouch) { + let find = false; + const locPreTouchPool = this._preTouchPool; + const id = touch.getID(); + for (let i = locPreTouchPool.length - 1; i >= 0; i--) { + if (locPreTouchPool[i].getID() === id) { + locPreTouchPool[i] = touch; + find = true; + break; + } + } + if (!find) { + if (locPreTouchPool.length <= 50) { + locPreTouchPool.push(touch); + } else { + locPreTouchPool[this._preTouchPoolPointer] = touch; + this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50; + } + } + } + + public getTouchByXY (tx: number, ty: number, pos: IHTMLElementPosition) { + const locPreTouch = this._preTouchPoint; + const location = this._glView!.convertToLocationInView(tx, ty, pos); + const touch = new CCTouch(location.x, location.y, 0); + touch._setPrevPoint(locPreTouch.x, locPreTouch.y); + locPreTouch.x = location.x; + locPreTouch.y = location.y; + return touch; + } + + public getMouseEvent ( + location: { x: number; y: number; }, pos: IHTMLElementPosition, eventType: number): EventMouse { + const locPreMouse = this._prevMousePoint; + const mouseEvent = new EventMouse(eventType); + mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y); + locPreMouse.x = location.x; + locPreMouse.y = location.y; + this._glView!._convertMouseToLocationInView(locPreMouse, pos); + mouseEvent.setLocation(locPreMouse.x, locPreMouse.y); + return mouseEvent; + } + + public getPointByEvent (event: MouseEvent, pos: IHTMLElementPosition) { + if (event.pageX != null) { // not avalable in <= IE8 + return {x: event.pageX, y: event.pageY}; + } + + if (sys.platform === sys.WECHAT_GAME) { + pos.left = 0; + pos.top = 0; + } else { + pos.left -= document.body.scrollLeft; + pos.top -= document.body.scrollTop; + } + return {x: event.clientX, y: event.clientY}; + } + + public getTouchesByEvent (event: TouchEvent, position: IHTMLElementPosition) { + const touches: CCTouch[] = []; + const locView = this._glView; + const locPreTouch = this._preTouchPoint; + + const length = event.changedTouches.length; + for (let i = 0; i < length; i++) { + const changedTouch = event.changedTouches.item(i); + if (!changedTouch) { + continue; + } + let location; + if (sys.BROWSER_TYPE_FIREFOX === sys.browserType) { + location = locView!.convertToLocationInView( + changedTouch.pageX, changedTouch.pageY, position, _vec2); + } else { + location = locView!.convertToLocationInView( + changedTouch.clientX, changedTouch.clientY, position, _vec2); + } + let touch: CCTouch; + if (changedTouch.identifier != null) { + touch = new CCTouch(location.x, location.y, changedTouch.identifier); + // use Touch Pool + const preLocation = this.getPreTouch(touch).getLocation(); + touch._setPrevPoint(preLocation.x, preLocation.y); + this.setPreTouch(touch); + } else { + touch = new CCTouch(location.x, location.y); + touch._setPrevPoint(locPreTouch.x, locPreTouch.y); + } + locPreTouch.x = location.x; + locPreTouch.y = location.y; + touches.push(touch); + } + return touches; + } + + public registerSystemEvent (element: HTMLElement) { + if (this._isRegisterEvent) { + return; + } + + this._glView = cc.view; + + let prohibition = sys.isMobile; + let supportMouse = ('mouse' in sys.capabilities); + let supportTouches = ('touches' in sys.capabilities); + if (sys.platform === sys.WECHAT_GAME) { + prohibition = false; + supportTouches = true; + supportMouse = false; + } + + // Register mouse events. + if (supportMouse) { + this._registerMouseEvents(element, prohibition); + } + + // Register mouse pointer events. + if (window.navigator.msPointerEnabled) { + this._registerMousePointerEvents(element); + } + + // Register touch events. + if (supportTouches) { + this._registerTouchEvents(element); + } + + // Register keyboard events. + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + this._registerKeyboardEvent(); + } + + this._isRegisterEvent = true; + } + + /** + * Whether enable accelerometer event. + */ + public setAccelerometerEnabled (isEnable: boolean) { + if (this._accelEnabled === isEnable) { + return; + } + + this._accelEnabled = isEnable; + const scheduler = cc.director.getScheduler(); + scheduler.enableForTarget(this); + if (this._accelEnabled) { + this._registerAccelerometerEvent(); + this._accelCurTime = 0; + scheduler.scheduleUpdate(this); + } else { + this._unregisterAccelerometerEvent(); + this._accelCurTime = 0; + scheduler.unscheduleUpdate(this); + } + } + + public didAccelerate (eventData: DeviceMotionEvent | DeviceOrientationEvent) { + if (!this._accelEnabled) { + return; + } + + const mAcceleration = this._acceleration!; + + let x = 0; + let y = 0; + let z = 0; + + // TODO + // @ts-ignore + if (this._accelDeviceEvent === window.DeviceMotionEvent) { + const deviceMotionEvent = eventData as DeviceMotionEvent; + const eventAcceleration = deviceMotionEvent.accelerationIncludingGravity; + if (eventAcceleration) { + x = this._accelMinus * (eventAcceleration.x || 0) * 0.1; + y = this._accelMinus * (eventAcceleration.y || 0) * 0.1; + z = (eventAcceleration.z || 0) * 0.1; + } + } else { + const deviceOrientationEvent = eventData as DeviceOrientationEvent; + x = ((deviceOrientationEvent.gamma || 0) / 90) * 0.981; + y = -((deviceOrientationEvent.beta || 0) / 90) * 0.981; + z = ((deviceOrientationEvent.alpha || 0) / 90) * 0.981; + } + + if (cc.view._isRotated) { + const tmp = x; + x = -y; + y = tmp; + } + mAcceleration.x = x; + mAcceleration.y = y; + mAcceleration.z = z; + + mAcceleration.timestamp = eventData.timeStamp || Date.now(); + + const tmpX = mAcceleration.x; + if (window.orientation === LANDSCAPE_RIGHT) { + mAcceleration.x = -mAcceleration.y; + mAcceleration.y = tmpX; + } else if (window.orientation === LANDSCAPE_LEFT) { + mAcceleration.x = mAcceleration.y; + mAcceleration.y = -tmpX; + } else if (window.orientation === PORTRAIT_UPSIDE_DOWN) { + mAcceleration.x = -mAcceleration.x; + mAcceleration.y = -mAcceleration.y; + } + // fix android acc values are opposite + if (cc.sys.os === cc.sys.OS_ANDROID && + cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ) { + mAcceleration.x = -mAcceleration.x; + mAcceleration.y = -mAcceleration.y; + } + } + + public update (dt: number) { + if (this._accelCurTime > this._accelInterval) { + this._accelCurTime -= this._accelInterval; + eventManager.dispatchEvent(new EventAcceleration(this._acceleration!)); + } + this._accelCurTime += dt; + } + + private _getUnUsedIndex () { + let temp = this._indexBitsUsed; + const now = cc.sys.now(); + + for (let i = 0; i < this._maxTouches; i++) { + if (!(temp & 0x00000001)) { + this._indexBitsUsed |= (1 << i); + return i; + } else { + const touch = this._touches[i]; + if (now - touch._lastModified > TOUCH_TIMEOUT) { + this._removeUsedIndexBit(i); + const touchID = touch.getID(); + if (touchID !== null) { + delete this._touchesIntegerDict[touchID]; + } + return i; + } + } + temp >>= 1; + } + + // all bits are used + return -1; + } + + private _removeUsedIndexBit (index) { + if (index < 0 || index >= this._maxTouches) { + return; + } + + let temp = 1 << index; + temp = ~temp; + this._indexBitsUsed &= temp; + } + + /** + * set accelerometer interval value + * @method setAccelerometerInterval + * @param {Number} interval + */ + private setAccelerometerInterval (interval) { + if (this._accelInterval !== interval) { + this._accelInterval = interval; + } + } + + private _registerMouseEvents (element: HTMLElement, prohibition: boolean) { + // HACK + // - At the same time to trigger the ontouch event and onmouse event + // - The function will execute 2 times + // The known browser: + // liebiao + // miui + // WECHAT + if (!prohibition) { + this._registerWindowMouseEvents(element); + } + this._registerElementMouseEvents(element, prohibition); + } + + private _registerWindowMouseEvents (element: HTMLElement) { + window.addEventListener('mousedown', () => { + this._mousePressed = true; + }, false); + window.addEventListener('mouseup', (event: MouseEvent) => { + if (!this._mousePressed) { + return; + } + this._mousePressed = false; + const position = this.getHTMLElementPosition(element); + const location = this.getPointByEvent(event, position); + const positionRect = rect(position.left, position.top, position.width, position.height); + if (!positionRect.contains(v2(location.x, location.y))) { + this.handleTouchesEnd([this.getTouchByXY(location.x, location.y, position)]); + const mouseEvent = this.getMouseEvent(location, position, EventMouse.UP); + mouseEvent.setButton(event.button); + eventManager.dispatchEvent(mouseEvent); + } + }, false); + } + + private _registerElementMouseEvents (element: HTMLElement, prohibition: boolean) { + // Register canvas mouse events. + type Handler = ( + event: MouseEvent, + mouseEvent: EventMouse, + location: { x: number; y: number; }, + elementPosition: IHTMLElementPosition, + ) => void; + + type MouseEventNames = 'mousedown' | 'mouseup' | 'mousemove'; + + const listenDOMMouseEvent = (eventName: MouseEventNames, type: number, handler: Handler) => { + element.addEventListener(eventName, (event) => { + const pos = this.getHTMLElementPosition(element); + const location = this.getPointByEvent(event, pos); + const mouseEvent = this.getMouseEvent(location, pos, type); + mouseEvent.setButton(event.button); + + handler(event, mouseEvent, location, pos); + + eventManager.dispatchEvent(mouseEvent); + event.stopPropagation(); + event.preventDefault(); + }); + }; + + if (!prohibition) { + listenDOMMouseEvent('mousedown', EventMouse.DOWN, (event, mouseEvent, location, pos) => { + this._mousePressed = true; + this.handleTouchesBegin([this.getTouchByXY(location.x, location.y, pos)]); + element.focus(); + }); + + listenDOMMouseEvent('mouseup', EventMouse.UP, (event, mouseEvent, location, pos) => { + this._mousePressed = false; + this.handleTouchesEnd([this.getTouchByXY(location.x, location.y, pos)]); + }); + + listenDOMMouseEvent('mousemove', EventMouse.MOVE, (event, mouseEvent, location, pos) => { + this.handleTouchesMove([this.getTouchByXY(location.x, location.y, pos)]); + if (!this._mousePressed) { + mouseEvent.setButton(null); + } + if (event.movementX !== undefined && event.movementY !== undefined) { + mouseEvent.movementX = event.movementX; + mouseEvent.movementY = event.movementY; + } + }); + } + + // @ts-ignore + listenDOMMouseEvent('mousewheel', EventMouse.SCROLL, (event, mouseEvent, location, pos) => { + mouseEvent.setScrollData(0, event.wheelDelta); + }); + + /* firefox fix */ + // @ts-ignore + listenDOMMouseEvent('DOMMouseScroll', EventMouse.SCROLL, (event, mouseEvent, location, pos) => { + mouseEvent.setScrollData(0, event.detail * -120); + }); + } + + private _registerMousePointerEvents (element: HTMLElement) { + const _pointerEventsMap = { + MSPointerDown : this.handleTouchesBegin, + MSPointerMove : this.handleTouchesMove, + MSPointerUp : this.handleTouchesEnd, + MSPointerCancel : this.handleTouchesCancel, + }; + for (const eventName of Object.keys(_pointerEventsMap)) { + const touchEvent = _pointerEventsMap[eventName]; + // @ts-ignore + element.addEventListener(eventName as MSPointerEventNames, (event: MSPointerEvent) => { + const pos = this.getHTMLElementPosition(element); + pos.left -= document.documentElement.scrollLeft; + pos.top -= document.documentElement.scrollTop; + touchEvent.call(this, [this.getTouchByXY(event.clientX, event.clientY, pos)]); + event.stopPropagation(); + }, false); + } + } + + private _registerTouchEvents (element: HTMLElement) { + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + this._registerWXGameTouchEvents(element); + } else { + this._registerHTMLTouchEvents(element); + } + } + + private _registerWXGameTouchEvents (element: HTMLElement) { + const makeTouchListener = (touchesHandler: (touchesToHandle: any) => void) => { + return (event: TouchEvent) => { + const pos = this.getHTMLElementPosition(element); + const body = document.body; + pos.left -= body.scrollLeft || 0; + pos.top -= body.scrollTop || 0; + touchesHandler(this.getTouchesByEvent(event, pos)); + }; + }; + + wx.onTouchStart(makeTouchListener((touchesToHandle) => { + this.handleTouchesBegin(touchesToHandle); + })); + wx.onTouchEnd(makeTouchListener((touchesToHandle) => { + this.handleTouchesEnd(touchesToHandle); + })); + wx.onTouchMove(makeTouchListener((touchesToHandle) => { + this.handleTouchesMove(touchesToHandle); + })); + wx.onTouchCancel(makeTouchListener((touchesToHandle) => { + this.handleTouchesCancel(touchesToHandle); + })); + } + + private _registerHTMLTouchEvents (element: HTMLElement) { + const makeTouchListener = (touchesHandler: (touchesToHandle: any) => void) => { + return (event: TouchEvent) => { + if (!event.changedTouches) { + return; + } + const pos = this.getHTMLElementPosition(element); + const body = document.body; + pos.left -= body.scrollLeft || 0; + pos.top -= body.scrollTop || 0; + touchesHandler(this.getTouchesByEvent(event, pos)); + event.stopPropagation(); + event.preventDefault(); + }; + }; + + element.addEventListener('touchstart', makeTouchListener((touchesToHandle) => { + this.handleTouchesBegin(touchesToHandle); + if (sys.platform !== sys.WECHAT_GAME) { + element.focus(); + } + }), false); + + element.addEventListener('touchmove', makeTouchListener((touchesToHandle) => { + this.handleTouchesMove(touchesToHandle); + }), false); + + element.addEventListener('touchend', makeTouchListener((touchesToHandle) => { + this.handleTouchesEnd(touchesToHandle); + }), false); + + element.addEventListener('touchcancel', makeTouchListener((touchesToHandle) => { + this.handleTouchesCancel(touchesToHandle); + }), false); + } + + private _registerKeyboardEvent () { + const canvas = cc.game.canvas as HTMLCanvasElement; + canvas.addEventListener('keydown', (event: KeyboardEvent) => { + eventManager.dispatchEvent(new EventKeyboard(event.keyCode, true)); + event.stopPropagation(); + event.preventDefault(); + }, false); + canvas.addEventListener('keyup', (event: KeyboardEvent) => { + eventManager.dispatchEvent(new EventKeyboard(event.keyCode, false)); + event.stopPropagation(); + event.preventDefault(); + }, false); + } + + private _registerAccelerometerEvent () { + this._acceleration = new Acceleration(); + // TODO + // @ts-ignore + this._accelDeviceEvent = window.DeviceMotionEvent || window.DeviceOrientationEvent; + + // TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) { + // TODO + // @ts-ignore + this._accelDeviceEvent = window.DeviceOrientationEvent; + } + + const _deviceEventType = + // TODO + // @ts-ignore + this._accelDeviceEvent === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation'; + const ua = navigator.userAgent; + if (/Android/.test(ua) || (/Adr/.test(ua) && cc.sys.browserType === cc.BROWSER_TYPE_UC)) { + this._minus = -1; + } + + // @ts-ignore + _didAccelerateFun = (...args: any[]) => this.didAccelerate(...args); + window.addEventListener(_deviceEventType, _didAccelerateFun, false); + } + + private _unregisterAccelerometerEvent () { + const _deviceEventType = + // TODO + // @ts-ignore + this._accelDeviceEvent === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation'; + if (_didAccelerateFun) { + window.removeEventListener(_deviceEventType, _didAccelerateFun, false); + } + } +} + +const inputManager = new InputManager(); + +export default inputManager; + +_cc.inputManager = inputManager; diff --git a/cocos/core/platform/event-manager/CCTouch.js b/cocos/core/platform/event-manager/CCTouch.ts similarity index 64% rename from cocos/core/platform/event-manager/CCTouch.js rename to cocos/core/platform/event-manager/CCTouch.ts index 29e6967121..c53614c582 100644 --- a/cocos/core/platform/event-manager/CCTouch.js +++ b/cocos/core/platform/event-manager/CCTouch.ts @@ -1,3 +1,6 @@ +import { Vec2 } from '../../value-types'; +import { v2 } from '../../value-types/vec2'; + /**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. @@ -34,145 +37,136 @@ * @param {Number} id */ export default class Touch { - constructor (x, y, id) { - this._lastModified = 0; + public _point: Vec2 = v2(); + public _prevPoint: Vec2 = v2(); + public _lastModified = 0; + private _id: number | null = null; + private _startPoint: Vec2 = v2(); + private _startPointCaptured: boolean = false; + + constructor (x: number, y: number, id: number | null = null) { this.setTouchInfo(id, x, y); } /** * !#en Returns the current touch location in OpenGL coordinates.、 * !#zh 获取当前触点位置。 - * @method getLocation - * @return {Vec2} */ - getLocation () { - return cc.v2(this._point.x, this._point.y); + public getLocation () { + return v2(this._point.x, this._point.y); } - /** - * !#en Returns X axis location value. + /** + * !#en Returns X axis location value. * !#zh 获取当前触点 X 轴位置。 - * @method getLocationX - * @returns {Number} - */ - getLocationX () { - return this._point.x; - } + */ + public getLocationX () { + return this._point.x; + } - /** + /** * !#en Returns Y axis location value. * !#zh 获取当前触点 Y 轴位置。 - * @method getLocationY - * @returns {Number} - */ - getLocationY () { - return this._point.y; - } + */ + public getLocationY () { + return this._point.y; + } /** * !#en Returns the previous touch location in OpenGL coordinates. * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} */ - getPreviousLocation () { - return cc.v2(this._prevPoint.x, this._prevPoint.y); + public getPreviousLocation () { + return v2(this._prevPoint.x, this._prevPoint.y); } /** * !#en Returns the start touch location in OpenGL coordinates. * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 - * @method getStartLocation - * @returns {Vec2} */ - getStartLocation () { - return cc.v2(this._startPoint.x, this._startPoint.y); + public getStartLocation () { + return v2(this._startPoint.x, this._startPoint.y); } /** * !#en Returns the delta distance from the previous touche to the current one in screen coordinates. * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} */ - getDelta () { + public getDelta () { return this._point.sub(this._prevPoint); } /** * !#en Returns the current touch location in screen coordinates. * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 - * @method getLocationInView - * @return {Vec2} */ - getLocationInView () { - return cc.v2(this._point.x, cc.view._designResolutionSize.height - this._point.y); + public getLocationInView () { + return v2(this._point.x, cc.view._designResolutionSize.height - this._point.y); } /** * !#en Returns the previous touch location in screen coordinates. * !#zh 获取触点在上一次事件时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocationInView - * @return {Vec2} */ - getPreviousLocationInView () { - return cc.v2(this._prevPoint.x, cc.view._designResolutionSize.height - this._prevPoint.y); + public getPreviousLocationInView () { + return v2(this._prevPoint.x, cc.view._designResolutionSize.height - this._prevPoint.y); } /** * !#en Returns the start touch location in screen coordinates. * !#zh 获取触点落下时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 - * @method getStartLocationInView - * @return {Vec2} */ - getStartLocationInView () { - return cc.v2(this._startPoint.x, cc.view._designResolutionSize.height - this._startPoint.y); + public getStartLocationInView () { + return v2(this._startPoint.x, cc.view._designResolutionSize.height - this._startPoint.y); } /** * !#en Returns the id of cc.Touch. * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 - * @method getID - * @return {Number} */ - getID () { + public getID () { return this._id; } /** * !#en Sets information to touch. * !#zh 设置触摸相关的信息。用于监控触摸事件。 - * @method setTouchInfo - * @param {Number} id - * @param {Number} x - * @param {Number} y */ - setTouchInfo (id, x, y) { + public setTouchInfo (id: number | null = null, x?: number, y?: number) { this._prevPoint = this._point; - this._point = cc.v2(x || 0, y || 0); + this._point = v2(x || 0, y || 0); this._id = id; - if(!this._startPointCaptured){ - this._startPoint = cc.v2(this._point); + if (!this._startPointCaptured) { + this._startPoint = v2(this._point); cc.view._convertPointWithScale(this._startPoint); this._startPointCaptured = true; } } - _setPoint (x, y) { - if(y === undefined){ + public _setPoint (point: Vec2): void; + + public _setPoint (x: number, y: number): void; + + public _setPoint (x: number | Vec2, y?: number) { + if (typeof x === 'object') { this._point.x = x.x; this._point.y = x.y; - }else{ - this._point.x = x; - this._point.y = y; + } else { + this._point.x = x || 0; + this._point.y = y || 0; } } - _setPrevPoint (x, y) { - if(y === undefined) - this._prevPoint = cc.v2(x.x, x.y); - else - this._prevPoint = cc.v2(x || 0, y || 0); + public _setPrevPoint (point: Vec2): void; + + public _setPrevPoint (x: number, y: number): void; + + public _setPrevPoint (x: number | Vec2, y?: number) { + if (typeof x === 'object') { + this._prevPoint = v2(x.x, x.y); + } else { + this._prevPoint = v2(x || 0, y || 0); + } } } diff --git a/cocos/core/platform/event-manager/index.js b/cocos/core/platform/event-manager/index.ts similarity index 97% rename from cocos/core/platform/event-manager/index.js rename to cocos/core/platform/event-manager/index.ts index e420c8fb0c..fef8f81d68 100644 --- a/cocos/core/platform/event-manager/index.js +++ b/cocos/core/platform/event-manager/index.ts @@ -31,6 +31,5 @@ export * from './CCEvent'; export * from './CCTouch'; if (CC_TEST) { - cc._Test.eventManager = eventManager; + // cc._Test.eventManager = eventManager; } - diff --git a/cocos/core/root.ts b/cocos/core/root.ts new file mode 100644 index 0000000000..cfd9c400bf --- /dev/null +++ b/cocos/core/root.ts @@ -0,0 +1,246 @@ +import { builtinResMgr } from '../3d/builtin'; +import { GFXDevice } from '../gfx/device'; +import { GFXWindow, IGFXWindowInfo } from '../gfx/window'; +import { ForwardPipeline } from '../pipeline/forward/forward-pipeline'; +import { RenderPipeline } from '../pipeline/render-pipeline'; +import { IRenderViewInfo, RenderView } from '../pipeline/render-view'; +import { IRenderSceneInfo, RenderScene } from '../renderer/scene/render-scene'; +import { UI } from '../renderer/ui/ui'; + +export let _createSceneFun; +export let _createViewFun; + +// tslint:disable-next-line:no-empty-interface +export interface IRootInfo { +} + +export interface ISceneInfo { + name: string; +} + +export class Root { + + public get device (): GFXDevice { + return this._device; + } + + public get mainWindow (): GFXWindow | null { + return this._mainWindow; + } + + public get curWindow (): GFXWindow | null { + return this._curWindow; + } + + public get windows (): GFXWindow[] { + return this._windows; + } + + public get pipeline (): RenderPipeline { + return this._pipeline as RenderPipeline; + } + + public get ui (): UI { + return this._ui as UI; + } + + public get scenes (): RenderScene[] { + return this._scenes; + } + + public get views (): RenderView[] { + return this._views; + } + + public get frameTime (): number { + return this._frameTime; + } + + public _createSceneFun; + public _createViewFun; + + private _device: GFXDevice; + private _windows: GFXWindow[] = []; + private _mainWindow: GFXWindow | null = null; + private _curWindow: GFXWindow | null = null; + private _pipeline: RenderPipeline | null = null; + private _ui: UI | null = null; + private _scenes: RenderScene[] = []; + private _views: RenderView[] = []; + private _frameTime: number = 0; + + constructor (device: GFXDevice) { + this._device = device; + + RenderScene.registerCreateFunc(this); + RenderView.registerCreateFunc(this); + } + + public initialize (info: IRootInfo): boolean { + + if (!this._device.mainWindow) { + return false; + } + + this._mainWindow = this._device.mainWindow; + this._curWindow = this._mainWindow; + + const pipeline = new ForwardPipeline(this); + if (!pipeline.initialize()) { + this.destroy(); + return false; + } + + this._pipeline = pipeline; + + builtinResMgr.initBuiltinRes(this._device); + + this._ui = new UI(this); + if (!this._ui.initialize()) { + this.destroy(); + return false; + } + + return true; + } + + public destroy () { + this.destroyViews(); + this.destroyScenes(); + + if (this._pipeline) { + this._pipeline.destroy(); + this._pipeline = null; + } + + if (this._ui) { + this._ui.destroy(); + this._ui = null; + } + + this._curWindow = null; + this._mainWindow = null; + } + + public resize (width: number, height: number) { + + this._device.resize(width, height); + + for (const window of this._windows) { + window.resize(width, height); + } + + if (this._pipeline) { + this._pipeline.resize(width, height); + } + + for (const view of this._views) { + if (view.camera.isWindowSize) { + view.camera.resize(width, height); + } + } + } + + public activeWindow (window: GFXWindow) { + this._curWindow = window; + } + + public frameMove (deltaTime: number) { + + this._frameTime = deltaTime; + + for (const view of this._views) { + if (view.isEnable && view.window === this._mainWindow) { + this._pipeline!.render(view); + } + } + + this._ui!.update(deltaTime); + this._ui!.render(); + + this._device.present(); + } + + public createWindow (info: IGFXWindowInfo): GFXWindow | null { + if (this._device) { + const window = this._device.createWindow(info); + if (window) { + this._windows.push(window); + return window; + } + } + + return null; + } + + public destroyWindow (window: GFXWindow) { + for (let i = 0; i < this._windows.length; ++i) { + if (this._windows[i] === window) { + window.destroy(); + this._windows.splice(i); + return; + } + } + } + + public destroyWindows () { + for (const window of this._windows) { + window.destroy(); + } + this._windows = []; + } + + public createScene (info: IRenderSceneInfo): RenderScene { + const scene: RenderScene = this._createSceneFun(this); + scene.initialize(info); + this._scenes.push(scene); + return scene; + } + + public destroyScene (scene: RenderScene) { + for (let i = 0; i < this._scenes.length; ++i) { + if (this._scenes[i] === scene) { + scene.destroy(); + this._scenes.splice(i); + return; + } + } + } + + public destroyScenes () { + for (const scene of this._scenes) { + scene.destroy(); + } + this._scenes = []; + } + + public createView (info: IRenderViewInfo): RenderView { + const view: RenderView = this._createViewFun(this, info.camera); + view.initialize(info); + + if (!info.isUI) { + this._views.push(view); + this._views.sort((a: RenderView, b: RenderView) => { + return a.priority - b.priority; + }); + } + + return view; + } + + public destroyView (view: RenderView) { + for (let i = 0; i < this._views.length; ++i) { + if (this._views[i] === view) { + this._views.splice(i); + return; + } + } + } + + public destroyViews () { + for (const view of this._views) { + view.destroy(); + } + this._views = []; + } +} diff --git a/cocos/core/CCScheduler.js b/cocos/core/scheduler.js similarity index 99% rename from cocos/core/CCScheduler.js rename to cocos/core/scheduler.js index 4b76e4be79..fa2737e4ce 100644 --- a/cocos/core/CCScheduler.js +++ b/cocos/core/scheduler.js @@ -299,7 +299,7 @@ class Scheduler { this._arrayForTimers = []; // Speed up indexing //this._arrayForUpdates = []; // Speed up indexing } - + //-----------------------private method---------------------- _removeHashElement (element) { delete this._hashForTimers[element.target._id]; @@ -509,7 +509,7 @@ class Scheduler { * @param {Number} [repeat=cc.macro.REPEAT_FOREVER] * @param {Number} [delay=0] * @param {Boolean} paused - * @example {@link cocos2d/core/CCScheduler/schedule.js} + * @example {@link cocos2d/core/scheduler/schedule.js} * @typescript * schedule(callback: Function, target: any, interval: number, repeat: number, delay: number, paused?: boolean): void * schedule(callback: Function, target: any, interval: number, paused?: boolean): void @@ -694,7 +694,7 @@ class Scheduler { } } - /** + /** * !#en Unschedules the update callback for a given target. * !#zh 取消指定对象的 update 定时器。 * @method unscheduleUpdate @@ -724,7 +724,7 @@ class Scheduler { } } - /** + /** * !#en * Unschedules all scheduled callbacks for a given target. * This also includes the "update" callback. @@ -752,7 +752,7 @@ class Scheduler { var element = this._hashForTimers[targetId]; if (element) { var timers = element.timers; - if (timers.indexOf(element.currentTimer) > -1 && + if (timers.indexOf(element.currentTimer) > -1 && (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } @@ -839,7 +839,7 @@ class Scheduler { } } - /** + /** * !#en Checks whether a callback for a given target is scheduled. * !#zh 检查指定的回调函数和回调对象组合是否存在定时器。 * @method isScheduled @@ -862,7 +862,7 @@ class Scheduler { cc.errorID(1510); } } - + var element = this._hashForTimers[targetId]; if (!element) { @@ -1003,7 +1003,7 @@ class Scheduler { } //customer selectors - var self = this, + var self = this, element = self._hashForTimers[targetId]; if (element) { element.paused = true; diff --git a/cocos/core/utils/murmurhash2_gc.js b/cocos/core/utils/murmurhash2_gc.js new file mode 100644 index 0000000000..4e6f89fb42 --- /dev/null +++ b/cocos/core/utils/murmurhash2_gc.js @@ -0,0 +1,50 @@ +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +export function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; +} diff --git a/cocos/core/value-types/affine-transform.js b/cocos/core/value-types/affine-transform.js index 3ae7254c38..3afa27e435 100644 --- a/cocos/core/value-types/affine-transform.js +++ b/cocos/core/value-types/affine-transform.js @@ -31,13 +31,13 @@ * !#zh * AffineTransform 类代表一个仿射变换矩阵。它基本上是由平移旋转,缩放转变所组成。
* @class AffineTransform - * @method constructor - * @param {Number} a - * @param {Number} b - * @param {Number} c - * @param {Number} d - * @param {Number} tx - * @param {Number} ty + * + * @param a + * @param b + * @param c + * @param d + * @param tx + * @param ty * @see AffineTransform.create */ export default class AffineTransform { @@ -53,15 +53,15 @@ export default class AffineTransform { /** * !#en Create a AffineTransform object with all contents in the matrix. * !#zh 用在矩阵中的所有内容创建一个 AffineTransform 对象。 - * @method create + * * @static - * @param {Number} a - * @param {Number} b - * @param {Number} c - * @param {Number} d - * @param {Number} tx - * @param {Number} ty - * @return {AffineTransform} + * @param a + * @param b + * @param c + * @param d + * @param tx + * @param ty + * @return */ static create (a, b, c, d, tx, ty) { return new AffineTransform(a, b, c, d, tx, ty); @@ -77,9 +77,9 @@ export default class AffineTransform { * [ 1, 0, 0,
* 0, 1, 0 ] * - * @method identity + * * @static - * @return {AffineTransform} + * @return */ static identity () { return new AffineTransform(); @@ -88,10 +88,10 @@ export default class AffineTransform { /** * !#en Clone a AffineTransform object from the specified transform. * !#zh 克隆指定的 AffineTransform 对象。 - * @method clone + * * @static - * @param {AffineTransform} t - * @return {AffineTransform} + * @param t + * @return */ static clone (t) { return new AffineTransform(t.a, t.b, t.c, t.d, t.tx, t.ty); @@ -106,12 +106,12 @@ export default class AffineTransform { * !#zh * 拼接两个矩阵,将结果保存到 out 矩阵。这个函数不创建任何内存,你需要先创建 AffineTransform 对象用来存储结果,并作为第一个参数传入函数。 * out = t1 * t2 - * @method concat + * * @static - * @param {AffineTransform} out Out object to store the concat result - * @param {AffineTransform} t1 The first transform object. - * @param {AffineTransform} t2 The transform object to concatenate. - * @return {AffineTransform} Out object with the result of concatenation. + * @param out Out object to store the concat result + * @param t1 The first transform object. + * @param t2 The transform object to concatenate. + * @return Out object with the result of concatenation. */ static concat (out, t1, t2) { var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty; @@ -128,11 +128,11 @@ export default class AffineTransform { * !#en Get the invert transform of an AffineTransform object. * This function is memory free, you should create the output affine transform by yourself and manage its memory. * !#zh 求逆矩阵。这个函数不创建任何内存,你需要先创建 AffineTransform 对象用来存储结果,并作为第一个参数传入函数。 - * @method invert + * * @static - * @param {AffineTransform} out - * @param {AffineTransform} t - * @return {AffineTransform} Out object with inverted result. + * @param out + * @param t + * @return Out object with inverted result. */ static invert (out, t) { var a = t.a, b = t.b, c = t.c, d = t.d; @@ -151,11 +151,11 @@ export default class AffineTransform { * !#en Get an AffineTransform object from a given matrix 4x4. * This function is memory free, you should create the output affine transform by yourself and manage its memory. * !#zh 从一个 4x4 Matrix 获取 AffineTransform 对象。这个函数不创建任何内存,你需要先创建 AffineTransform 对象用来存储结果,并作为第一个参数传入函数。 - * @method invert + * * @static - * @param {AffineTransform} out - * @param {Mat4} mat - * @return {AffineTransform} Out object with inverted result. + * @param out + * @param mat + * @return Out object with inverted result. */ static fromMat4 (out, mat) { out.a = mat.m00; @@ -171,13 +171,13 @@ export default class AffineTransform { * !#en Apply the affine transformation on a point. * This function is memory free, you should create the output Vec2 by yourself and manage its memory. * !#zh 对一个点应用矩阵变换。这个函数不创建任何内存,你需要先创建一个 Vec2 对象用来存储结果,并作为第一个参数传入函数。 - * @method transformVec2 + * * @static - * @param {Vec2} out The output point to store the result + * @param out The output point to store the result * @param {Vec2|Number} point Point to apply transform or x. * @param {AffineTransform|Number} transOrY transform matrix or y. - * @param {AffineTransform} [t] transform matrix. - * @return {Vec2} + * @param [t] transform matrix. + * @return */ static transformVec2 (out, point, transOrY, t) { var x, y; @@ -198,12 +198,12 @@ export default class AffineTransform { * !#en Apply the affine transformation on a size. * This function is memory free, you should create the output Size by yourself and manage its memory. * !#zh 应用仿射变换矩阵到 Size 上。这个函数不创建任何内存,你需要先创建一个 Size 对象用来存储结果,并作为第一个参数传入函数。 - * @method transformSize + * * @static - * @param {Size} out The output point to store the result - * @param {Size} size - * @param {AffineTransform} t - * @return {Size} + * @param out The output point to store the result + * @param size + * @param t + * @return */ static transformSize (out, size, t) { out.width = t.a * size.width + t.c * size.height; @@ -215,12 +215,12 @@ export default class AffineTransform { * !#en Apply the affine transformation on a rect. * This function is memory free, you should create the output Rect by yourself and manage its memory. * !#zh 应用仿射变换矩阵到 Rect 上。这个函数不创建任何内存,你需要先创建一个 Rect 对象用来存储结果,并作为第一个参数传入函数。 - * @method transformRect + * * @static - * @param {Rect} out - * @param {Rect} rect - * @param {AffineTransform} anAffineTransform - * @return {Rect} + * @param out + * @param rect + * @param anAffineTransform + * @return */ static transformRect(out, rect, t){ var ol = rect.x; @@ -252,14 +252,14 @@ export default class AffineTransform { * !#en Apply the affine transformation on a rect, and truns to an Oriented Bounding Box. * This function is memory free, you should create the output vectors by yourself and manage their memory. * !#zh 应用仿射变换矩阵到 Rect 上, 并转换为有向包围盒。这个函数不创建任何内存,你需要先创建包围盒的四个 Vector 对象用来存储结果,并作为前四个参数传入函数。 - * @method transformObb + * * @static - * @param {Vec2} out_bl - * @param {Vec2} out_tl - * @param {Vec2} out_tr - * @param {Vec2} out_br - * @param {Rect} rect - * @param {AffineTransform} anAffineTransform + * @param out_bl + * @param out_tl + * @param out_tr + * @param out_br + * @param rect + * @param anAffineTransform */ static transformObb (out_bl, out_tl, out_tr, out_br, rect, anAffineTransform) { var x = rect.x; diff --git a/cocos/core/value-types/color.js b/cocos/core/value-types/color.ts similarity index 70% rename from cocos/core/value-types/color.js rename to cocos/core/value-types/color.ts index 3594466bf7..0e369e4994 100644 --- a/cocos/core/value-types/color.js +++ b/cocos/core/value-types/color.ts @@ -24,8 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; import CCClass from '../data/class'; +import { color4 } from '../vmath'; +import { ValueType } from './value-type'; /** * !#en @@ -46,14 +47,22 @@ import CCClass from '../data/class'; * @extends ValueType */ export default class Color extends ValueType { + private _val: number; + /** - * @method constructor - * @param {Number} [r=0] - red component of the color, default value is 0. - * @param {Number} [g=0] - green component of the color, defualt value is 0. - * @param {Number} [b=0] - blue component of the color, default value is 0. - * @param {Number} [a=255] - alpha component of the color, default value is 255. + * @param other */ - constructor ( r, g, b, a ) { + constructor (other: Color); + + /** + * @param [r=0] - red component of the color, default value is 0. + * @param [g=0] - green component of the color, defualt value is 0. + * @param [b=0] - blue component of the color, default value is 0. + * @param [a=255] - alpha component of the color, default value is 255. + */ + constructor (r?: number, g?: number, b?: number, a?: number); + + constructor (r?: number | Color, g?: number, b?: number, a?: number) { super(); if (typeof r === 'object') { g = r.g; @@ -65,16 +74,13 @@ export default class Color extends ValueType { g = g || 0; b = b || 0; a = typeof a === 'number' ? a : 255; - this._val = ((a<<24) >>> 0) + (b<<16) + (g<<8) + r; + this._val = ((a << 24) >>> 0) + (b << 16) + (g << 8) + r; } // color: [r, g, b, a] /** * !#en Solid white, RGBA is [255, 255, 255, 255]. * !#zh 纯白色,RGBA 是 [255, 255, 255, 255]。 - * @property WHITE - * @type {Color} - * @static */ static get WHITE () { return new Color(255, 255, 255, 255); @@ -83,9 +89,6 @@ export default class Color extends ValueType { /** * !#en Solid black, RGBA is [0, 0, 0, 255]. * !#zh 纯黑色,RGBA 是 [0, 0, 0, 255]。 - * @property BLACK - * @type {Color} - * @static */ static get BLACK () { return new Color(0, 0, 0, 255); @@ -94,18 +97,14 @@ export default class Color extends ValueType { /** * !#en Transparent, RGBA is [0, 0, 0, 0]. * !#zh 透明,RGBA 是 [0, 0, 0, 0]。 - * @property TRANSPARENT - * @type {Color} - * @static */ static get TRANSPARENT () { - return new Color(0, 0, 0, 0); } + return new Color(0, 0, 0, 0); + } + /** * !#en Grey, RGBA is [127.5, 127.5, 127.5]. * !#zh 灰色,RGBA 是 [127.5, 127.5, 127.5]。 - * @property GRAY - * @type {Color} - * @static */ static get GRAY () { return new Color(127.5, 127.5, 127.5, 255); @@ -114,9 +113,6 @@ export default class Color extends ValueType { /** * !#en Solid red, RGBA is [255, 0, 0]. * !#zh 纯红色,RGBA 是 [255, 0, 0]。 - * @property RED - * @type {Color} - * @static */ static get RED () { return new Color(255, 0, 0, 255); @@ -125,9 +121,6 @@ export default class Color extends ValueType { /** * !#en Solid green, RGBA is [0, 255, 0]. * !#zh 纯绿色,RGBA 是 [0, 255, 0]。 - * @property GREEN - * @type {Color} - * @static */ static get GREEN () { return new Color(0, 255, 0, 255); @@ -136,9 +129,6 @@ export default class Color extends ValueType { /** * !#en Solid blue, RGBA is [0, 0, 255]. * !#zh 纯蓝色,RGBA 是 [0, 0, 255]。 - * @property BLUE - * @type {Color} - * @static */ static get BLUE () { return new Color(0, 0, 255, 255); @@ -147,9 +137,6 @@ export default class Color extends ValueType { /** * !#en Yellow, RGBA is [255, 235, 4]. * !#zh 黄色,RGBA 是 [255, 235, 4]。 - * @property YELLOW - * @type {Color} - * @static */ static get YELLOW () { return new Color(255, 235, 4, 255); @@ -158,9 +145,6 @@ export default class Color extends ValueType { /** * !#en Orange, RGBA is [255, 127, 0]. * !#zh 橙色,RGBA 是 [255, 127, 0]。 - * @property ORANGE - * @type {Color} - * @static */ static get ORANGE () { return new Color(255, 127, 0, 255); @@ -169,9 +153,6 @@ export default class Color extends ValueType { /** * !#en Cyan, RGBA is [0, 255, 255]. * !#zh 青色,RGBA 是 [0, 255, 255]。 - * @property CYAN - * @type {Color} - * @static */ static get CYAN () { return new Color(0, 255, 255, 255); @@ -180,9 +161,6 @@ export default class Color extends ValueType { /** * !#en Magenta, RGBA is [255, 0, 255]. * !#zh 洋红色(品红色),RGBA 是 [255, 0, 255]。 - * @property MAGENTA - * @type {Color} - * @static */ static get MAGENTA () { return new Color(255, 0, 255, 255); @@ -191,7 +169,6 @@ export default class Color extends ValueType { /** * !#en red channel value * !#zh 红色通道值 - * @property r */ get r () { return this._val & 0x000000ff; @@ -199,13 +176,11 @@ export default class Color extends ValueType { set r (red) { red = ~~cc.misc.clampf(red, 0, 255); this._val = ((this._val & 0xffffff00) | red) >>> 0; - return this; } /** * !#en green channel value * !#zh 绿色通道值 - * @property g */ get g () { return (this._val & 0x0000ff00) >> 8; @@ -213,13 +188,11 @@ export default class Color extends ValueType { set g (green) { green = ~~cc.misc.clampf(green, 0, 255); this._val = ((this._val & 0xffff00ff) | (green << 8)) >>> 0; - return this; } /** * !#en blue channel value * !#zh 蓝色通道值 - * @property b */ get b () { return (this._val & 0x00ff0000) >> 16; @@ -227,13 +200,11 @@ export default class Color extends ValueType { set b (blue) { blue = ~~cc.misc.clampf(blue, 0, 255); this._val = ((this._val & 0xff00ffff) | (blue << 16)) >>> 0; - return this; } /** * !#en alpha channel value * !#zh 透明度通道值 - * @property a */ get a () { return (this._val & 0xff000000) >>> 24; @@ -241,20 +212,19 @@ export default class Color extends ValueType { set a (alpha) { alpha = ~~cc.misc.clampf(alpha, 0, 255); this._val = ((this._val & 0x00ffffff) | ((alpha << 24) >>> 0)) >>> 0; - return this; } /** * !#en Clone a new color from the current color. * !#zh 克隆当前颜色。 - * @method clone - * @return {Color} Newly created color. + * + * @return Newly created color. * @example * var color = new cc.Color(); * var newColor = color.clone();// Color {r: 0, g: 0, b: 0, a: 255} */ - clone () { - var ret = new Color(); + public clone () { + const ret = new Color(); ret._val = this._val; return ret; } @@ -262,9 +232,9 @@ export default class Color extends ValueType { /** * !#en TODO * !#zh 判断两个颜色是否相等。 - * @method equals - * @param {Color} other - * @return {Boolean} + * + * @param other + * @return * @example * var color1 = cc.Color.WHITE; * var color2 = new cc.Color(255, 255, 255); @@ -272,26 +242,26 @@ export default class Color extends ValueType { * color2 = cc.Color.RED; * cc.log(color2.equals(color1)); // false; */ - equals (other) { + public equals (other: Color) { return other && this._val === other._val; } /** * !#en TODO * !#zh 线性插值 - * @method lerp - * @param {Color} to - * @param {number} ratio - the interpolation coefficient. - * @param {Color} [out] - optional, the receiving vector. - * @return {Color} + * + * @param to + * @param ratio - the interpolation coefficient. + * @param [out] - optional, the receiving vector. + * @return * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCColor/lerp.js} */ - lerp (to, ratio, out) { + public lerp (to: Color, ratio: number, out?: Color) { out = out || new Color(); - var r = this.r; - var g = this.g; - var b = this.b; - var a = this.a; + const r = this.r; + const g = this.g; + const b = this.b; + const a = this.a; out.r = r + (to.r - r) * ratio; out.g = g + (to.g - g) * ratio; out.b = b + (to.b - b) * ratio; @@ -302,67 +272,66 @@ export default class Color extends ValueType { /** * !#en TODO * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {String} + * + * @return * @example * var color = cc.Color.WHITE; * color.toString(); // "rgba(255, 255, 255, 255)" */ - toString () { - return "rgba(" + - this.r.toFixed() + ", " + - this.g.toFixed() + ", " + - this.b.toFixed() + ", " + - this.a.toFixed() + ")"; + public toString () { + return 'rgba(' + + this.r.toFixed() + ', ' + + this.g.toFixed() + ', ' + + this.b.toFixed() + ', ' + + this.a.toFixed() + ')'; } /** * !#en Convert color to css format. * !#zh 转换为 CSS 格式。 - * @method toCSS - * @param {String} opt - "rgba", "rgb", "#rgb" or "#rrggbb". - * @return {String} + * + * @param opt - "rgba", "rgb", "#rgb" or "#rrggbb". + * @return * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCColor/toCSS.js} */ - toCSS ( opt ) { + public toCSS (opt: 'rgba' | 'rgb' | '#rgb' | '#rrggbb') { if ( opt === 'rgba' ) { - return "rgba(" + - (this.r | 0 ) + "," + - (this.g | 0 ) + "," + - (this.b | 0 ) + "," + - (this.a / 255).toFixed(2) + ")" + return 'rgba(' + + (this.r | 0 ) + ',' + + (this.g | 0 ) + ',' + + (this.b | 0 ) + ',' + + (this.a / 255).toFixed(2) + ')' ; - } - else if ( opt === 'rgb' ) { - return "rgb(" + - (this.r | 0 ) + "," + - (this.g | 0 ) + "," + - (this.b | 0 ) + ")" + } else if ( opt === 'rgb' ) { + return 'rgb(' + + (this.r | 0 ) + ',' + + (this.g | 0 ) + ',' + + (this.b | 0 ) + ')' ; - } - else { + } else { return '#' + this.toHEX(opt); } } /** - * !#en Read hex string and store color data into the current color object, the hex string must be formated as rgba or rgb. + * !#en Read hex string and store color data into the current color object, + * the hex string must be formated as rgba or rgb. * !#zh 读取 16 进制颜色。 - * @method fromHEX - * @param {String} hexString - * @return {Color} + * + * @param hexString + * @return * @chainable * @example * var color = cc.Color.BLACK; * color.fromHEX("#FFFF33"); // Color {r: 255, g: 255, b: 51, a: 255}; */ - fromHEX (hexString) { + public fromHEX (hexString: string) { hexString = (hexString.indexOf('#') === 0) ? hexString.substring(1) : hexString; - let r = parseInt(hexString.substr(0, 2), 16) || 0; - let g = parseInt(hexString.substr(2, 2), 16) || 0; - let b = parseInt(hexString.substr(4, 2), 16) || 0; - let a = parseInt(hexString.substr(6, 2), 16) || 255; - this._val = ((a<<24) >>> 0) + (b<<16) + (g<<8) + r; + const r = parseInt(hexString.substr(0, 2), 16) || 0; + const g = parseInt(hexString.substr(2, 2), 16) || 0; + const b = parseInt(hexString.substr(4, 2), 16) || 0; + const a = parseInt(hexString.substr(6, 2), 16) || 255; + this._val = ((a << 24) >>> 0) + (b << 16) + (g << 8) + r; return this; } @@ -370,36 +339,34 @@ export default class Color extends ValueType { * !#en convert Color to HEX color string. * e.g. cc.color(255,6,255) to : "#ff06ff" * !#zh 转换为 16 进制。 - * @method toHEX - * @param {String} fmt - "#rgb", "#rrggbb" or "#rrggbbaa". - * @return {String} + * + * @param fmt - "#rgb", "#rrggbb" or "#rrggbbaa". + * @return * @example * var color = cc.Color.BLACK; * color.toHEX("#rgb"); // "000"; * color.toHEX("#rrggbb"); // "000000"; */ - toHEX ( fmt ) { - var hex = [ + public toHEX (fmt: '#rgb' | '#rrggbb' | '#rrggbbaa') { + const hex = [ (this.r | 0 ).toString(16), (this.g | 0 ).toString(16), - (this.b | 0 ).toString(16) + (this.b | 0 ).toString(16), ]; - var i = -1; + let i = -1; if ( fmt === '#rgb' ) { for ( i = 0; i < hex.length; ++i ) { if ( hex[i].length > 1 ) { hex[i] = hex[i][0]; } } - } - else if ( fmt === '#rrggbb' ) { + } else if ( fmt === '#rrggbb' ) { for ( i = 0; i < hex.length; ++i ) { if ( hex[i].length === 1 ) { hex[i] = '0' + hex[i]; } } - } - else if ( fmt === '#rrggbbaa' ) { + } else if ( fmt === '#rrggbbaa' ) { hex.push((this.a | 0 ).toString(16)); for ( i = 0; i < hex.length; ++i ) { if ( hex[i].length === 1 ) { @@ -413,48 +380,48 @@ export default class Color extends ValueType { /** * !#en Convert to 24bit rgb value. * !#zh 转换为 24bit 的 RGB 值。 - * @method toRGBValue - * @return {Number} + * + * @return * @example * var color = cc.Color.YELLOW; * color.toRGBValue(); // 16771844; */ - toRGBValue () { + public toRGBValue () { return this._val & 0x00ffffff; } /** * !#en Read HSV model color and convert to RGB color * !#zh 读取 HSV(色彩模型)格式。 - * @method fromHSV - * @param {Number} h - * @param {Number} s - * @param {Number} v - * @return {Color} + * + * @param h + * @param s + * @param v + * @return * @chainable * @example * var color = cc.Color.YELLOW; * color.fromHSV(0, 0, 1); // Color {r: 255, g: 255, b: 255, a: 255}; */ - fromHSV ( h, s, v ) { - var r, g, b; + public fromHSV (h: number, s: number, v: number) { + let r: number = 0; + let g: number = 0; + let b: number = 0; if (s === 0) { r = g = b = v; - } - else { + } else { if (v === 0) { r = g = b = 0; - } - else { - if (h === 1) h = 0; + } else { + if (h === 1) { h = 0; } h *= 6; s = s; v = v; - var i = Math.floor(h); - var f = h - i; - var p = v * (1 - s); - var q = v * (1 - (s * f)); - var t = v * (1 - (s * (1 - f))); + const i = Math.floor(h); + const f = h - i; + const p = v * (1 - s); + const q = v * (1 - (s * f)); + const t = v * (1 - (s * (1 - f))); switch (i) { case 0: r = v; @@ -497,46 +464,48 @@ export default class Color extends ValueType { r *= 255; g *= 255; b *= 255; - this._val = ((this.a<<24) >>> 0) + (b<<16) + (g<<8) + r; + this._val = ((this.a << 24) >>> 0) + (b << 16) + (g << 8) + r; return this; } /** * !#en Transform to HSV model color * !#zh 转换为 HSV(色彩模型)格式。 - * @method toHSV - * @return {Object} - {h: number, s: number, v: number}. + * + * @return - {h: number, s: number, v: number}. * @example * var color = cc.Color.YELLOW; * color.toHSV(); // Object {h: 0.1533864541832669, s: 0.9843137254901961, v: 1}; */ - toHSV () { - var r = this.r / 255; - var g = this.g / 255; - var b = this.b / 255; - var hsv = { h: 0, s: 0, v: 0 }; - var max = Math.max(r,g,b); - var min = Math.min(r,g,b); - var delta = 0; + public toHSV () { + const r = this.r / 255; + const g = this.g / 255; + const b = this.b / 255; + const hsv = { h: 0, s: 0, v: 0 }; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let delta = 0; hsv.v = max; hsv.s = max ? (max - min) / max : 0; - if (!hsv.s) hsv.h = 0; - else { + if (!hsv.s) { hsv.h = 0; } else { delta = max - min; - if (r === max) hsv.h = (g - b) / delta; - else if (g === max) hsv.h = 2 + (b - r) / delta; - else hsv.h = 4 + (r - g) / delta; + if (r === max) { + hsv.h = (g - b) / delta; + } else if (g === max) { + hsv.h = 2 + (b - r) / delta; + } else { + hsv.h = 4 + (r - g) / delta; + } hsv.h /= 6; - if (hsv.h < 0) hsv.h += 1.0; + if (hsv.h < 0) { hsv.h += 1.0; } } return hsv; } - set (color) { + public set (color: Color) { if (color._val) { this._val = color._val; - } - else { + } else { this.r = color.r; this.g = color.g; this.b = color.b; @@ -544,8 +513,8 @@ export default class Color extends ValueType { } } - to01(out) { - out = out || cc.vmath.color4.create(); + public to01 (out?: color4) { + out = out || color4.create(); out.r = this.r / 255; out.g = this.g / 255; out.b = this.b / 255; @@ -557,8 +526,20 @@ export default class Color extends ValueType { CCClass.fastDefine('cc.Color', Color, {r: 0, g: 0, b: 0, a: 255}); /** - * @module cc + * !#en + * The convenience method to create a new {{#crossLink "Color/Color:method"}}cc.Color{{/crossLink}} + * Alpha channel is optional. Default value is 255. + * + * !#zh + * 通过该方法来创建一个新的 {{#crossLink "Color/Color:method"}}cc.Color{{/crossLink}} 对象。 + * Alpha 通道是可选的。默认值是 255。 + * + * + * @param other + * @return + * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCColor/color.js} */ +function color (other: Color | string): Color; /** * !#en @@ -569,23 +550,29 @@ CCClass.fastDefine('cc.Color', Color, {r: 0, g: 0, b: 0, a: 255}); * 通过该方法来创建一个新的 {{#crossLink "Color/Color:method"}}cc.Color{{/crossLink}} 对象。 * Alpha 通道是可选的。默认值是 255。 * - * @method color - * @param {Number} [r=0] - * @param {Number} [g=0] - * @param {Number} [b=0] - * @param {Number} [a=255] - * @return {Color} + * + * @param [r=0] + * @param [g=0] + * @param [b=0] + * @param [a=255] + * @return * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCColor/color.js} */ -cc.color = function color (r, g, b, a) { +function color (r?: number, g?: number, b?: number, a?: number): Color; + +function color (r?: number | Color | string, g?: number, b?: number, a?: number) { if (typeof r === 'string') { - var result = new Color(); + const result = new Color(); return result.fromHEX(r); } if (typeof r === 'object') { return new Color(r.r, r.g, r.b, r.a); } return new Color(r, g, b, a); -}; +} -cc.Color = Color; \ No newline at end of file +export { color }; + +cc.color = color; + +cc.Color = Color; diff --git a/cocos/core/value-types/enum.js b/cocos/core/value-types/enum.js index 755f04cea7..a21303a9e6 100644 --- a/cocos/core/value-types/enum.js +++ b/cocos/core/value-types/enum.js @@ -38,9 +38,9 @@ import * as js from '../utils/js'; * 定义一个枚举类型。
* 用户可以把枚举值设为任意的整数,如果设为 -1,系统将会分配为上一个枚举值 + 1。 * - * @method Enum - * @param {object} obj - a JavaScript literal object containing enum names and values, or a TypeScript enum type - * @return {object} the defined enum type + * + * @param obj - a JavaScript literal object containing enum names and values, or a TypeScript enum type + * @return the defined enum type * @example {@link cocos2d/core/platform/CCEnum/Enum.js} * @typescript Enum(obj: T): T */ @@ -85,8 +85,8 @@ Enum.isEnum = function (enumType) { }; /** - * @method getList - * @param {Object} enumDef - the enum type defined from cc.Enum + * + * @param enumDef - the enum type defined from cc.Enum * @return {Object[]} * @private */ @@ -118,4 +118,15 @@ if (CC_DEV) { } } +/** + * + * @param enumx + */ +export function ccenum(enumx) { + if ('__enums__' in enumx) { + return; + } + js.value(enumx, '__enums__', null, true); +} + cc.Enum = Enum; diff --git a/cocos/core/value-types/index.js b/cocos/core/value-types/index.ts similarity index 95% rename from cocos/core/value-types/index.js rename to cocos/core/value-types/index.ts index ad1de90e43..01e52b3897 100644 --- a/cocos/core/value-types/index.js +++ b/cocos/core/value-types/index.ts @@ -25,7 +25,7 @@ ****************************************************************************/ export { default as Enum } from './enum'; -export { default as ValueType } from './value-type'; +export { ValueType } from './value-type'; export { default as Vec2} from './vec2'; export { default as Vec3} from './vec3'; export { default as Vec4} from './vec4'; @@ -34,4 +34,4 @@ export { default as Mat4} from './mat4'; export { default as AffineTransform} from './affine-transform'; export { default as Size} from './size'; export { default as Rect} from './rect'; -export { default as Color} from './color'; \ No newline at end of file +export { default as Color} from './color'; diff --git a/cocos/core/value-types/mat4.js b/cocos/core/value-types/mat4.js deleted file mode 100644 index 3342642a80..0000000000 --- a/cocos/core/value-types/mat4.js +++ /dev/null @@ -1,396 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://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 ValueType from './value-type'; -import CCClass from '../data/class'; -import {mat4} from '../vmath'; - -/** - * !#en Representation of 4*4 matrix. - * !#zh 表示 4*4 矩阵 - * - * @class Mat4 - * @extends ValueType - */ -export default class Mat4 extends ValueType { - /** - * !#en - * Constructor - * see {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} - * !#zh - * 构造函数,可查看 {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} - * @method constructor - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m02 Component in column 0, row 2 position (index 2) - * @param {Number} m03 Component in column 0, row 3 position (index 3) - * @param {Number} m10 Component in column 1, row 0 position (index 4) - * @param {Number} m11 Component in column 1, row 1 position (index 5) - * @param {Number} m12 Component in column 1, row 2 position (index 6) - * @param {Number} m13 Component in column 1, row 3 position (index 7) - * @param {Number} m20 Component in column 2, row 0 position (index 8) - * @param {Number} m21 Component in column 2, row 1 position (index 9) - * @param {Number} m22 Component in column 2, row 2 position (index 10) - * @param {Number} m23 Component in column 2, row 3 position (index 11) - * @param {Number} m30 Component in column 3, row 0 position (index 12) - * @param {Number} m31 Component in column 3, row 1 position (index 13) - * @param {Number} m32 Component in column 3, row 2 position (index 14) - * @param {Number} m33 Component in column 3, row 3 position (index 15) - */ - constructor ( - m00 = 1, m01 = 0, m02 = 0, m03 = 0, - m04 = 0, m05 = 1, m06 = 0, m07 = 0, - m08 = 0, m09 = 0, m10 = 1, m11 = 0, - m12 = 0, m13 = 0, m14 = 0, m15 = 1) { - super(); - let t = this; - if (typeof m00 === 'object') { - m01 = m00.m01; m02 = m00.m02; m03 = m00.m03; m04 = m00.m04; - m05 = m00.m05; m06 = m00.m06; m07 = m00.m07; m08 = m00.m08; - m09 = m00.m09; m10 = m00.m10; m11 = m00.m11; m12 = m00.m12; - m13 = m00.m13; m14 = m00.m14; m15 = m00.m15; m00 = m00.m00; - } - t.m00 = m00; t.m01 = m01; t.m02 = m02; t.m03 = m03; - t.m04 = m04; t.m05 = m05; t.m06 = m06; t.m07 = m07; - t.m08 = m08; t.m09 = m09; t.m10 = m10; t.m11 = m11; - t.m12 = m12; t.m13 = m13; t.m14 = m14; t.m15 = m15; - } - - /** - * !#en clone a Mat4 object - * !#zh 克隆一个 Mat4 对象 - * @method clone - * @return {Mat4} - */ - clone () { - let t = this; - return new Mat4( - t.m00, t.m01, t.m02, t.m03, - t.m04, t.m05, t.m06, t.m07, - t.m08, t.m09, t.m10, t.m11, - t.m12, t.m13, t.m14, t.m15); - } - - /** - * !#en Sets the matrix with another one's value - * !#zh 用另一个矩阵设置这个矩阵的值。 - * @method set - * @param {Mat4} srcObj - * @return {Mat4} returns this - * @chainable - */ - set (s) { - let t = this; - t.m00 = s.m00; - t.m01 = s.m01; - t.m02 = s.m02; - t.m03 = s.m03; - t.m04 = s.m04; - t.m05 = s.m05; - t.m06 = s.m06; - t.m07 = s.m07; - t.m08 = s.m08; - t.m09 = s.m09; - t.m10 = s.m10; - t.m11 = s.m11; - t.m12 = s.m12; - t.m13 = s.m13; - t.m14 = s.m14; - t.m15 = s.m15; - return this; - } - - /** - * !#en Check whether two matrix equal - * !#zh 当前的矩阵是否与指定的矩阵相等。 - * @method equals - * @param {Mat4} other - * @return {Boolean} - */ - equals (other) { - return mat4.exactEquals(this, other); - } - - /** - * !#en Check whether two matrix equal with default degree of variance. - * !#zh - * 近似判断两个矩阵是否相等。
- * 判断 2 个矩阵是否在默认误差范围之内,如果在则返回 true,反之则返回 false。 - * @method fuzzyEquals - * @param {Mat4} other - * @return {Boolean} - */ - fuzzyEquals (other) { - return mat4.equals(this, other); - } - - /** - * !#en Transform to string with matrix informations - * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} - */ - toString () { - let t = this; - return "[\n" + - t.m00 + ", " + t.m01 + ", " + t.m02 + ", " + t.m03 + ",\n" + - t.m04 + ", " + t.m05 + ", " + t.m06 + ", " + t.m07 + ",\n" + - t.m08 + ", " + t.m09 + ", " + t.m10 + ", " + t.m11 + ",\n" + - t.m12 + ", " + t.m13 + ", " + t.m14 + ", " + t.m15 + "\n" + - "]" - ; - } - - /** - * Set the matrix to the identity matrix - * @method identity - * @returns {Mat4} self - * @chainable - */ - identity () { - return mat4.identity(this); - } - - /** - * Transpose the values of a mat4 - * @method transpose - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created. - * @returns {Mat4} out - */ - transpose (out) { - out = out || new cc.Mat4(); - return mat4.transpose(out, this); - } - - /** - * Inverts a mat4 - * @method invert - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created. - * @returns {Mat4} out - */ - invert (out) { - out = out || new cc.Mat4(); - return mat4.invert(out, this); - } - - /** - * Calculates the adjugate of a mat4 - * @method adjoint - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created. - * @returns {Mat4} out - */ - adjoint (out) { - out = out || new cc.Mat4(); - return mat4.adjoint(out, this); - } - - /** - * Calculates the determinant of a mat4 - * @method determinant - * @returns {Number} determinant of a - */ - determinant () { - return mat4.determinant(this); - } - - /** - * Adds two Mat4 - * @method add - * @param {Mat4} other the second operand - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created. - * @returns {Mat4} out - */ - add (other, out) { - out = out || new cc.Mat4(); - return mat4.add(out, this, other); - } - - /** - * Subtracts the current matrix with another one - * @method sub - * @param {Mat4} other the second operand - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created - * @returns {Mat4} out - */ - sub (other, out) { - out = out || new cc.Mat4(); - return mat4.subtract(out, this, other); - } - - /** - * Subtracts the current matrix with another one - * @method mul - * @param {Mat4} other the second operand - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created - * @returns {Mat4} out - */ - mul (other, out) { - out = out || new cc.Mat4(); - return mat4.multiply(out, this, other); - } - - /** - * Multiply each element of the matrix by a scalar. - * @method mulScalar - * @param {Number} number amount to scale the matrix's elements by - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created - * @returns {Mat4} out - */ - mulScalar (number, out) { - out = out || new cc.Mat4(); - return mat4.mulScalar(out, this, number); - } - - /** - * Translate a mat4 by the given vector - * @method translate - * @param {Vec3} v vector to translate by - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created - * @returns {Mat4} out - */ - translate (v, out) { - out = out || new cc.Mat4(); - return mat4.translate(out, this, v); - } - - /** - * Scales the mat4 by the dimensions in the given vec3 - * @method scale - * @param {Vec3} v vector to scale by - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created - * @returns {Mat4} out - */ - scale (v, out) { - out = out || new cc.Mat4(); - return mat4.scale(out, this, v); - } - - /** - * Rotates a mat4 by the given angle around the given axis - * @method rotate - * @param {Number} rad the angle to rotate the matrix by - * @param {Vec3} axis the axis to rotate around - * @param {Mat4} [out] the receiving matrix, you can pass the same matrix to save result to itself, if not provided, a new matrix will be created - * @returns {Mat4} out - */ - rotate (rad, axis, out) { - out = out || new cc.Mat4(); - return mat4.rotate(out, this, rad, axis); - } - - /** - * Returns the translation vector component of a transformation matrix. - * @method getTranslation - * @param {Vec3} out Vector to receive translation component, if not provided, a new vec3 will be created - * @return {Vec3} out - */ - getTranslation (out) { - out = out || new cc.Vec3(); - return mat4.getTranslation(out, this); - } - - /** - * Returns the scale factor component of a transformation matrix - * @method getScale - * @param {Vec3} out Vector to receive scale component, if not provided, a new vec3 will be created - * @return {Vec3} out - */ - getScale (out) { - out = out || new cc.Vec3(); - return mat4.getScaling(out, this); - } - - /** - * Returns the rotation factor component of a transformation matrix - * @method getRotation - * @param {Quat} out Vector to receive rotation component, if not provided, a new quaternion object will be created - * @return {Quat} out - */ - getRotation (out) { - out = out || new cc.Quat(); - return mat4.getRotation(out, this); - } - - /** - * Restore the matrix values from a quaternion rotation, vector translation and vector scale - * @method fromRTS - * @param {Quat} q Rotation quaternion - * @param {Vec3} v Translation vector - * @param {Vec3} s Scaling vector - * @returns {Mat4} the current mat4 object - * @chainable - */ - fromRTS (q, v, s) { - return mat4.fromRTS(this, q, v, s); - } - - /** - * Restore the matrix values from a quaternion rotation - * @method fromQuat - * @param {Quat} q Rotation quaternion - * @returns {Mat4} the current mat4 object - * @chainable - */ - fromQuat (quat) { - return mat4.fromQuat(this, quat); - } -} - -CCClass.fastDefine('cc.Mat4', Mat4, { - m00: 1, m01: 0, m02: 0, m03: 0, - m04: 0, m05: 1, m06: 0, m07: 0, - m08: 0, m09: 0, m10: 1, m11: 0, - m12: 0, m13: 0, m14: 0, m15: 1 -}); -cc.Mat4 = Mat4; -/** - * @module cc - */ - -/** - * !#en The convenience method to create a new {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}}. - * !#zh 通过该简便的函数进行创建 {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}} 对象。 - * @method mat4 - * @param {Number} m00 Component in column 0, row 0 position (index 0) - * @param {Number} m01 Component in column 0, row 1 position (index 1) - * @param {Number} m02 Component in column 0, row 2 position (index 2) - * @param {Number} m03 Component in column 0, row 3 position (index 3) - * @param {Number} m10 Component in column 1, row 0 position (index 4) - * @param {Number} m11 Component in column 1, row 1 position (index 5) - * @param {Number} m12 Component in column 1, row 2 position (index 6) - * @param {Number} m13 Component in column 1, row 3 position (index 7) - * @param {Number} m20 Component in column 2, row 0 position (index 8) - * @param {Number} m21 Component in column 2, row 1 position (index 9) - * @param {Number} m22 Component in column 2, row 2 position (index 10) - * @param {Number} m23 Component in column 2, row 3 position (index 11) - * @param {Number} m30 Component in column 3, row 0 position (index 12) - * @param {Number} m31 Component in column 3, row 1 position (index 13) - * @param {Number} m32 Component in column 3, row 2 position (index 14) - * @param {Number} m33 Component in column 3, row 3 position (index 15) - * @return {Mat4} - */ -cc.mat4 = function mat4 (m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { - return new Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); -}; diff --git a/cocos/core/value-types/mat4.ts b/cocos/core/value-types/mat4.ts new file mode 100644 index 0000000000..e9a7db86a2 --- /dev/null +++ b/cocos/core/value-types/mat4.ts @@ -0,0 +1,449 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + http://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 { Vec3 } from 'cannon'; +import CCClass from '../data/class'; +import { mat4 } from '../vmath'; +import Quat from './quat'; +import { ValueType } from './value-type'; + +/** + * !#en Representation of 4*4 matrix. + * !#zh 表示 4*4 矩阵 + */ +export default class Mat4 extends ValueType { + public m00: number; + public m01: number; + public m02: number; + public m03: number; + public m04: number; + public m05: number; + public m06: number; + public m07: number; + public m08: number; + public m09: number; + public m10: number; + public m11: number; + public m12: number; + public m13: number; + public m14: number; + public m15: number; + + /** + * !#en + * Constructor + * see {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * + * @param other + */ + constructor (other: Mat4); + + /** + * !#en + * Constructor + * see {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * + * @param m00 Component in column 0, row 0 position (index 0) + * @param m01 Component in column 0, row 1 position (index 1) + * @param m02 Component in column 0, row 2 position (index 2) + * @param m03 Component in column 0, row 3 position (index 3) + * @param m10 Component in column 1, row 0 position (index 4) + * @param m11 Component in column 1, row 1 position (index 5) + * @param m12 Component in column 1, row 2 position (index 6) + * @param m13 Component in column 1, row 3 position (index 7) + * @param m20 Component in column 2, row 0 position (index 8) + * @param m21 Component in column 2, row 1 position (index 9) + * @param m22 Component in column 2, row 2 position (index 10) + * @param m23 Component in column 2, row 3 position (index 11) + * @param m30 Component in column 3, row 0 position (index 12) + * @param m31 Component in column 3, row 1 position (index 13) + * @param m32 Component in column 3, row 2 position (index 14) + * @param m33 Component in column 3, row 3 position (index 15) + */ + constructor ( + m00?: number, m01?: number, m02?: number, m03?: number, + m04?: number, m05?: number, m06?: number, m07?: number, + m08?: number, m09?: number, m10?: number, m11?: number, + m12?: number, m13?: number, m14?: number, m15?: number); + + constructor ( + m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, + m04 = 0, m05 = 1, m06 = 0, m07 = 0, + m08 = 0, m09 = 0, m10 = 1, m11 = 0, + m12 = 0, m13 = 0, m14 = 0, m15 = 1) { + super(); + if (typeof m00 === 'object') { + this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; this.m04 = m00.m04; + this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; + this.m09 = m00.m09; this.m10 = m00.m10; this.m11 = m00.m11; this.m12 = m00.m12; + this.m13 = m00.m13; this.m14 = m00.m14; this.m15 = m00.m15; this.m00 = m00.m00; + } else { + this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; + this.m05 = m05; this.m06 = m06; this.m07 = m07; this.m08 = m08; + this.m09 = m09; this.m10 = m10; this.m11 = m11; this.m12 = m12; + this.m13 = m13; this.m14 = m14; this.m15 = m15; this.m00 = m00; + } + } + + /** + * !#en clone a Mat4 object + * !#zh 克隆一个 Mat4 对象 + * + * @return + */ + public clone () { + const t = this; + return new Mat4( + t.m00, t.m01, t.m02, t.m03, + t.m04, t.m05, t.m06, t.m07, + t.m08, t.m09, t.m10, t.m11, + t.m12, t.m13, t.m14, t.m15); + } + + /** + * !#en Sets the matrix with another one's value + * !#zh 用另一个矩阵设置这个矩阵的值。 + * + * @param srcObj + * @return returns this + * @chainable + */ + public set (other: Mat4) { + const t = this; + t.m00 = other.m00; + t.m01 = other.m01; + t.m02 = other.m02; + t.m03 = other.m03; + t.m04 = other.m04; + t.m05 = other.m05; + t.m06 = other.m06; + t.m07 = other.m07; + t.m08 = other.m08; + t.m09 = other.m09; + t.m10 = other.m10; + t.m11 = other.m11; + t.m12 = other.m12; + t.m13 = other.m13; + t.m14 = other.m14; + t.m15 = other.m15; + return this; + } + + /** + * !#en Check whether two matrix equal + * !#zh 当前的矩阵是否与指定的矩阵相等。 + * + * @param other + * @return + */ + public equals (other: Mat4) { + return mat4.exactEquals(this, other); + } + + /** + * !#en Check whether two matrix equal with default degree of variance. + * !#zh + * 近似判断两个矩阵是否相等。
+ * 判断 2 个矩阵是否在默认误差范围之内,如果在则返回 true,反之则返回 false。 + * + * @param other + * @return + */ + public fuzzyEquals (other: Mat4) { + return mat4.equals(this, other); + } + + /** + * !#en Transform to string with matrix informations + * !#zh 转换为方便阅读的字符串。 + * + * @return + */ + public toString () { + const t = this; + return '[\n' + + t.m00 + ', ' + t.m01 + ', ' + t.m02 + ', ' + t.m03 + ',\n' + + t.m04 + ', ' + t.m05 + ', ' + t.m06 + ', ' + t.m07 + ',\n' + + t.m08 + ', ' + t.m09 + ', ' + t.m10 + ', ' + t.m11 + ',\n' + + t.m12 + ', ' + t.m13 + ', ' + t.m14 + ', ' + t.m15 + '\n' + + ']' + ; + } + + /** + * Set the matrix to the identity matrix + * + * @return self + * @chainable + */ + public identity () { + return mat4.identity(this); + } + + /** + * Transpose the values of a mat4 + * + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public transpose (out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.transpose(out, this); + } + + /** + * Inverts a mat4 + * + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public invert (out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.invert(out, this); + } + + /** + * Calculates the adjugate of a mat4 + * + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public adjoint (out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.adjoint(out, this); + } + + /** + * Calculates the determinant of a mat4 + * + * @return determinant of a + */ + public determinant () { + return mat4.determinant(this); + } + + /** + * Adds two Mat4 + * + * @param other the second operand + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public add (other: Mat4, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.add(out, this, other); + } + + /** + * Subtracts the current matrix with another one + * + * @param other the second operand + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public sub (other: Mat4, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.subtract(out, this, other); + } + + /** + * Subtracts the current matrix with another one + * + * @param other the second operand + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public mul (other: Mat4, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.multiply(out, this, other); + } + + /** + * Multiply each element of the matrix by a scalar. + * + * @param number amount to scale the matrix's elements by + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public mulScalar (num: number, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.scale(out, this, num); + } + + /** + * Translate a mat4 by the given vector + * + * @param v vector to translate by + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public translate (v: Vec3, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.translate(out, this, v); + } + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param v vector to scale by + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public scale (v: Vec3, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.scale(out, this, v); + } + + /** + * Rotates a mat4 by the given angle around the given axis + * + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public rotate (rad: number, axis: Vec3, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.rotate(out, this, rad, axis); + } + + /** + * Returns the translation vector component of a transformation matrix. + * + * @param {Vec3} out Vector to receive translation component, if not provided, a new vec3 will be created + * @return out + */ + public getTranslation (out?: Mat4) { + out = out || new cc.Vec3(); + return mat4.getTranslation(out, this); + } + + /** + * Returns the scale factor component of a transformation matrix + * + * @param out Vector to receive scale component, if not provided, a new vec3 will be created + * @return out + */ + public getScale (out: Vec3) { + out = out || new cc.Vec3(); + return mat4.getScaling(out, this); + } + + /** + * Returns the rotation factor component of a transformation matrix + * + * @param out Vector to receive rotation component, if not provided, a new quaternion object will be created + * @return out + */ + public getRotation (out: Quat) { + out = out || new Quat(); + return mat4.getRotation(out, this); + } + + /** + * Restore the matrix values from a quaternion rotation, vector translation and vector scale + * + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector + * @return the current mat4 object + * @chainable + */ + public fromRTS (q: Quat, v: Vec3, s: Vec3) { + return mat4.fromRTS(this, q, v, s); + } + + /** + * Restore the matrix values from a quaternion rotation + * + * @param q Rotation quaternion + * @return the current mat4 object + * @chainable + */ + public fromQuat (quat: Quat) { + return mat4.fromQuat(this, quat); + } +} + +CCClass.fastDefine('cc.Mat4', Mat4, { + m00: 1, m01: 0, m02: 0, m03: 0, + m04: 0, m05: 1, m06: 0, m07: 0, + m08: 0, m09: 0, m10: 1, m11: 0, + m12: 0, m13: 0, m14: 0, m15: 1, +}); +cc.Mat4 = Mat4; + +/** + * !#en The convenience method to create a new {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}} 对象。 + * + * @param other + * @return + */ +function m4 (other: Mat4): Mat4; + +/** + * !#en The convenience method to create a new {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}} 对象。 + * + * @param m00 Component in column 0, row 0 position (index 0) + * @param m01 Component in column 0, row 1 position (index 1) + * @param m02 Component in column 0, row 2 position (index 2) + * @param m03 Component in column 0, row 3 position (index 3) + * @param m10 Component in column 1, row 0 position (index 4) + * @param m11 Component in column 1, row 1 position (index 5) + * @param m12 Component in column 1, row 2 position (index 6) + * @param m13 Component in column 1, row 3 position (index 7) + * @param m20 Component in column 2, row 0 position (index 8) + * @param m21 Component in column 2, row 1 position (index 9) + * @param m22 Component in column 2, row 2 position (index 10) + * @param m23 Component in column 2, row 3 position (index 11) + * @param m30 Component in column 3, row 0 position (index 12) + * @param m31 Component in column 3, row 1 position (index 13) + * @param m32 Component in column 3, row 2 position (index 14) + * @param m33 Component in column 3, row 3 position (index 15) + * @return + */ +function m4 ( + m00?: number, m01?: number, m02?: number, m03?: number, + m10?: number, m11?: number, m12?: number, m13?: number, + m20?: number, m21?: number, m22?: number, m23?: number, + m30?: number, m31?: number, m32?: number, m33?: number): Mat4; + +function m4 ( + m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, + m10 = 0, m11 = 1, m12 = 0, m13 = 0, + m20 = 0, m21 = 0, m22 = 1, m23 = 0, + m30 = 0, m31 = 0, m32 = 0, m33 = 1) { + return new Mat4(m00 as any, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); +} + +export { m4 as mat4 }; + +cc.mat4 = m4; diff --git a/cocos/core/value-types/quat.js b/cocos/core/value-types/quat.ts similarity index 61% rename from cocos/core/value-types/quat.js rename to cocos/core/value-types/quat.ts index 30dcfc5f36..e16a0bdd90 100644 --- a/cocos/core/value-types/quat.js +++ b/cocos/core/value-types/quat.ts @@ -23,75 +23,83 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; import CCClass from '../data/class'; import quat from '../vmath/quat'; +import { ValueType } from './value-type'; +import Vec3 from './vec3'; /** * !#en Representation of 2D vectors and points. * !#zh 表示 2D 向量和坐标 - * - * @class Quat - * @extends ValueType */ export default class Quat extends ValueType { + public x: number; + + public y: number; + + public z: number; + + public w: number; + /** * !#en * Constructor * see {{#crossLink "cc/quat:method"}}cc.quat{{/crossLink}} * !#zh * 构造函数,可查看 {{#crossLink "cc/quat:method"}}cc.quat{{/crossLink}} - * @method constructor - * @param {number} [x=0] - * @param {number} [y=0] - * @param {number} [z=0] - * @param {number} [w=1] + * + * @param other */ - constructor (x, y, z, w) { + constructor (other: Quat); + + /** + * !#en + * Constructor + * see {{#crossLink "cc/quat:method"}}cc.quat{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/quat:method"}}cc.quat{{/crossLink}} + * + * @param [x=0] + * @param [y=0] + * @param [z=0] + * @param [w=1] + */ + constructor (x?: number, y?: number, z?: number, w?: number); + + constructor (x?: number | Quat, y?: number, z?: number, w?: number) { super(); if (x && typeof x === 'object') { - z = x.z; - y = x.y; - x = x.x; - w = x.w; + this.x = x.x; + this.y = x.y; + this.z = x.z; + this.w = x.w; + } else { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 1; } - /** - * @property {Number} x - */ - this.x = x || 0; - /** - * @property {Number} y - */ - this.y = y || 0; - /** - * @property {Number} z - */ - this.z = z || 0; - /** - * @property {Number} w - */ - this.w = w || 1; } /** * !#en clone a Quat object and return the new object * !#zh 克隆一个四元数并返回 - * @method clone - * @return {Quat} + * + * @return */ - clone () { + public clone () { return new Quat(this.x, this.y, this.z, this.w); } /** * !#en Set values with another quaternion * !#zh 用另一个四元数的值设置到当前对象上。 - * @method set - * @param {Quat} newValue - !#en new value to set. !#zh 要设置的新值 - * @return {Quat} returns this + * + * @param newValue - !#en new value to set. !#zh 要设置的新值 + * @return returns this * @chainable */ - set (newValue) { + public set (newValue: Quat) { this.x = newValue.x; this.y = newValue.y; this.z = newValue.z; @@ -102,21 +110,21 @@ export default class Quat extends ValueType { /** * !#en Check whether current quaternion equals another * !#zh 当前的四元数是否与指定的四元数相等。 - * @method equals - * @param {Quat} other - * @return {Boolean} + * + * @param other + * @return */ - equals (other) { + public equals (other: Quat) { return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; } - getEulerAngles (out) { - out = out || cc.v3(); + public getEulerAngles (out?: Vec3) { + out = out || new Vec3(); return quat.toEuler(out, this); } - lerp (to, ratio, out) { - out = out || new cc.Quat(); + public lerp (to: Quat, ratio: number, out?: Quat) { + out = out || new Quat(); cc.vmath.quat.slerp(out, this, to, ratio); return out; } @@ -125,21 +133,32 @@ export default class Quat extends ValueType { CCClass.fastDefine('cc.Quat', Quat, { x: 0, y: 0, z: 0, w: 1 }); /** - * @module cc + * !#en The convenience method to create a new {{#crossLink "Quat"}}cc.Quat{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Quat"}}cc.Quat{{/crossLink}} 对象。 + * + * @param other + * @return */ +function q (other: Quat): Quat; /** * !#en The convenience method to create a new {{#crossLink "Quat"}}cc.Quat{{/crossLink}}. * !#zh 通过该简便的函数进行创建 {{#crossLink "Quat"}}cc.Quat{{/crossLink}} 对象。 - * @method quat - * @param {Number|Object} [x=0] - * @param {Number} [y=0] - * @param {Number} [z=0] - * @param {Number} [w=1] - * @return {Quat} + * + * @param [x=0] + * @param [y=0] + * @param [z=0] + * @param [w=1] + * @return */ -cc.quat = function(x, y, z, w) { - return new Quat(x, y, z, w); -}; +function q (x?: number, y?: number, z?: number, w?: number): Quat; + +function q (x: number | Quat = 0, y: number = 0, z: number = 0, w: number = 1) { + return new Quat(x as any, y, z, w); +} + +export {q as quat}; + +cc.quat = q; cc.Quat = Quat; diff --git a/cocos/core/value-types/rect.js b/cocos/core/value-types/rect.ts similarity index 62% rename from cocos/core/value-types/rect.js rename to cocos/core/value-types/rect.ts index dd8250d77e..390d53b4a4 100644 --- a/cocos/core/value-types/rect.js +++ b/cocos/core/value-types/rect.ts @@ -24,8 +24,11 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; import CCClass from '../data/class'; +import Mat4 from './mat4'; +import Size from './size'; +import { ValueType } from './value-type'; +import Vec2 from './vec2'; /** * !#en A 2D rectangle defined by x, y position and width, height. @@ -34,289 +37,10 @@ import CCClass from '../data/class'; * @extends ValueType */ export default class Rect extends ValueType { - /** - * !#en - * Constructor of Rect class. - * see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. - * !#zh - * Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 - * - * @method constructor - * @param {Number} [x=0] - * @param {Number} [y=0] - * @param {Number} [w=0] - * @param {Number} [h=0] - */ - constructor (x, y, w, h) { - super(); - if (x && typeof x === 'object') { - y = x.y; - w = x.width; - h = x.height; - x = x.x; - } - /** - * @property {Number} x - */ - this.x = x || 0; - /** - * @property {Number} y - */ - this.y = y || 0; - /** - * @property {Number} width - */ - this.width = w || 0; - /** - * @property {Number} height - */ - this.height = h || 0; - } - - /** - * !#en Creates a rectangle from two coordinate values. - * !#zh 根据指定 2 个坐标创建出一个矩形区域。 - * @static - * @method fromMinMax - * @param {Vec2} v1 - * @param {Vec2} v2 - * @return {Rect} - * @example - * cc.Rect.fromMinMax(cc.v2(10, 10), cc.v2(20, 20)); // Rect {x: 10, y: 10, width: 10, height: 10}; - */ - static fromMinMax (v1, v2) { - var min_x = Math.min(v1.x, v2.x); - var min_y = Math.min(v1.y, v2.y); - var max_x = Math.max(v1.x, v2.x); - var max_y = Math.max(v1.y, v2.y); - - return new Rect(min_x, min_y, max_x - min_x, max_y - min_y); - } - - /** - * !#en TODO - * !#zh 克隆一个新的 Rect。 - * @method clone - * @return {Rect} - * @example - * var a = new cc.Rect(0, 0, 10, 10); - * a.clone();// Rect {x: 0, y: 0, width: 10, height: 10} - */ - clone () { - return new Rect(this.x, this.y, this.width, this.height); - } - - /** - * !#en TODO - * !#zh 是否等于指定的矩形。 - * @method equals - * @param {Rect} other - * @return {Boolean} - * @example - * var a = new cc.Rect(0, 0, 10, 10); - * var b = new cc.Rect(0, 0, 10, 10); - * a.equals(b);// true; - */ - equals (other) { - return other && - this.x === other.x && - this.y === other.y && - this.width === other.width && - this.height === other.height; - } - - /** - * !#en TODO - * !#zh 线性插值 - * @method lerp - * @param {Rect} to - * @param {Number} ratio - the interpolation coefficient. - * @param {Rect} [out] - optional, the receiving vector. - * @return {Rect} - * @example - * var a = new cc.Rect(0, 0, 10, 10); - * var b = new cc.Rect(50, 50, 100, 100); - * update (dt) { - * // method 1; - * var c = a.lerp(b, dt * 0.1); - * // method 2; - * a.lerp(b, dt * 0.1, c); - * } - */ - lerp (to, ratio, out) { - out = out || new Rect(); - var x = this.x; - var y = this.y; - var width = this.width; - var height = this.height; - out.x = x + (to.x - x) * ratio; - out.y = y + (to.y - y) * ratio; - out.width = width + (to.width - width) * ratio; - out.height = height + (to.height - height) * ratio; - return out; - } - - set (source) { - this.x = source.x; - this.y = source.y; - this.width = source.width; - this.height = source.height; - } - - /** - * !#en Check whether the current rectangle intersects with the given one - * !#zh 当前矩形与指定矩形是否相交。 - * @method intersects - * @param {Rect} rect - * @return {Boolean} - * @example - * var a = new cc.Rect(0, 0, 10, 10); - * var b = new cc.Rect(0, 0, 20, 20); - * a.intersects(b);// true - */ - intersects (rect) { - var maxax = this.x + this.width, - maxay = this.y + this.height, - maxbx = rect.x + rect.width, - maxby = rect.y + rect.height; - return !(maxax < rect.x || maxbx < this.x || maxay < rect.y || maxby < this.y); - } - - /** - * !#en Returns the overlapping portion of 2 rectangles. - * !#zh 返回 2 个矩形重叠的部分。 - * @method intersection - * @param {Rect} out Stores the result - * @param {Rect} rectB - * @return {Rect} Returns the out parameter - * @example - * var a = new cc.Rect(0, 10, 20, 20); - * var b = new cc.Rect(0, 10, 10, 10); - * var intersection = new cc.Rect(); - * a.intersection(intersection, b); // intersection {x: 0, y: 10, width: 10, height: 10}; - */ - intersection (out, rectB) { - var axMin = this.x, ayMin = this.y, axMax = this.x + this.width, ayMax = this.y + this.height; - var bxMin = rectB.x, byMin = rectB.y, bxMax = rectB.x + rectB.width, byMax = rectB.y + rectB.height; - out.x = Math.max(axMin, bxMin); - out.y = Math.max(ayMin, byMin); - out.width = Math.min(axMax, bxMax) - out.x; - out.height = Math.min(ayMax, byMax) - out.y; - return out; - } - - /** - * !#en Check whether the current rect contains the given point - * !#zh 当前矩形是否包含指定坐标点。 - * Returns true if the point inside this rectangle. - * @method contains - * @param {Vec2} point - * @return {Boolean} - * @example - * var a = new cc.Rect(0, 0, 10, 10); - * var b = new cc.Vec2(0, 5); - * a.contains(b);// true - */ - contains (point) { - return (this.x <= point.x && - this.x + this.width >= point.x && - this.y <= point.y && - this.y + this.height >= point.y); - } - - /** - * !#en Returns true if the other rect totally inside this rectangle. - * !#zh 当前矩形是否包含指定矩形。 - * @method containsRect - * @param {Rect} rect - * @return {Boolean} - * @example - * var a = new cc.Rect(0, 0, 20, 20); - * var b = new cc.Rect(0, 0, 10, 10); - * a.containsRect(b);// true - */ - containsRect (rect) { - return (this.x <= rect.x && - this.x + this.width >= rect.x + rect.width && - this.y <= rect.y && - this.y + this.height >= rect.y + rect.height); - } - - /** - * !#en Returns the smallest rectangle that contains the current rect and the given rect. - * !#zh 返回一个包含当前矩形和指定矩形的最小矩形。 - * @method union - * @param {Rect} out Stores the result - * @param {Rect} rectB - * @return {Rect} Returns the out parameter - * @example - * var a = new cc.Rect(0, 10, 20, 20); - * var b = new cc.Rect(0, 10, 10, 10); - * var union = new cc.Rect(); - * a.union(union, b); // union {x: 0, y: 10, width: 20, height: 20}; - */ - union (out, rectB) { - var ax = this.x, ay = this.y, aw = this.width, ah = this.height; - var bx = rectB.x, by = rectB.y, bw = rectB.width, bh = rectB.height; - out.x = Math.min(ax, bx); - out.y = Math.min(ay, by); - out.width = Math.max(ax + aw, bx + bw) - out.x; - out.height = Math.max(ay + ah, by + bh) - out.y; - return out; - } - - /** - * !#en Apply matrix4 to the rect. - * !#zh 使用 mat4 对矩形进行矩阵转换。 - * @method transformMat4 - * @param out {Rect} The output rect - * @param mat {Mat4} The matrix4 - */ - transformMat4 (out, mat) { - let ol = this.x; - let ob = this.y; - let or = ol + this.width; - let ot = ob + this.height; - let lbx = mat.m00 * ol + mat.m04 * ob + mat.m12; - let lby = mat.m01 * ol + mat.m05 * ob + mat.m13; - let rbx = mat.m00 * or + mat.m04 * ob + mat.m12; - let rby = mat.m01 * or + mat.m05 * ob + mat.m13; - let ltx = mat.m00 * ol + mat.m04 * ot + mat.m12; - let lty = mat.m01 * ol + mat.m05 * ot + mat.m13; - let rtx = mat.m00 * or + mat.m04 * ot + mat.m12; - let rty = mat.m01 * or + mat.m05 * ot + mat.m13; - - let minX = Math.min(lbx, rbx, ltx, rtx); - let maxX = Math.max(lbx, rbx, ltx, rtx); - let minY = Math.min(lby, rby, lty, rty); - let maxY = Math.max(lby, rby, lty, rty); - - out.x = minX; - out.y = minY; - out.width = maxX - minX; - out.height = maxY - minY; - return out; - } - - /** - * !#en Output rect informations to string - * !#zh 转换为方便阅读的字符串 - * @method toString - * @return {String} - * @example - * var a = new cc.Rect(0, 0, 10, 10); - * a.toString();// "(0.00, 0.00, 10.00, 10.00)"; - */ - toString () { - return '(' + this.x.toFixed(2) + ', ' + this.y.toFixed(2) + ', ' + this.width.toFixed(2) + - ', ' + this.height.toFixed(2) + ')'; - } /** * !#en The minimum x value, equals to rect.x * !#zh 矩形 x 轴上的最小值,等价于 rect.x。 - * @property xMin - * @type {Number} */ get xMin () { return this.x; } set xMin (value) { @@ -327,8 +51,6 @@ export default class Rect extends ValueType { /** * !#en The minimum y value, equals to rect.y * !#zh 矩形 y 轴上的最小值。 - * @property yMin - * @type {Number} */ get yMin () { return this.y; } set yMin (value) { @@ -339,8 +61,6 @@ export default class Rect extends ValueType { /** * !#en The maximum x value. * !#zh 矩形 x 轴上的最大值。 - * @property xMax - * @type {Number} */ get xMax () { return this.x + this.width; } set xMax (value) { this.width = value - this.x; } @@ -348,8 +68,6 @@ export default class Rect extends ValueType { /** * !#en The maximum y value. * !#zh 矩形 y 轴上的最大值。 - * @property yMax - * @type {Number} */ get yMax () { return this.y + this.height; } set yMax (value) { this.height = value - this.y; } @@ -357,7 +75,6 @@ export default class Rect extends ValueType { /** * !#en The position of the center of the rectangle. * !#zh 矩形的中心点。 - * @property {Vec2} center */ get center () { return new cc.Vec2(this.x + this.width * 0.5, @@ -371,7 +88,6 @@ export default class Rect extends ValueType { /** * !#en The X and Y position of the rectangle. * !#zh 矩形的 x 和 y 坐标。 - * @property {Vec2} origin */ get origin () { return new cc.Vec2(this.x, this.y); @@ -384,15 +100,288 @@ export default class Rect extends ValueType { /** * !#en Width and height of the rectangle. * !#zh 矩形的大小。 - * @property {Size} size */ get size () { - return new cc.Size(this.width, this.height); + return new Size(this.width, this.height); } set size (value) { this.width = value.width; this.height = value.height; } + + /** + * !#en Creates a rectangle from two coordinate values. + * !#zh 根据指定 2 个坐标创建出一个矩形区域。 + * @param v1 + * @param v2 + * @return + * @example + * cc.Rect.fromMinMax(cc.v2(10, 10), cc.v2(20, 20)); // Rect {x: 10, y: 10, width: 10, height: 10}; + */ + public static fromMinMax (v1: Vec2, v2: Vec2) { + const min_x = Math.min(v1.x, v2.x); + const min_y = Math.min(v1.y, v2.y); + const max_x = Math.max(v1.x, v2.x); + const max_y = Math.max(v1.y, v2.y); + + return new Rect(min_x, min_y, max_x - min_x, max_y - min_y); + } + public x: number; + + public y: number; + + public width: number; + + public height: number; + + /** + * !#en + * Constructor of Rect class. + * see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. + * !#zh + * Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 + */ + constructor (rect: Rect); + + /** + * !#en + * Constructor of Rect class. + * see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. + * !#zh + * Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 + */ + constructor (x?: number, y?: number, width?: number, height?: number); + + constructor (x?: Rect | number, y?: number, width?: number, height?: number) { + super(); + if (x && typeof x === 'object') { + this.y = x.y; + this.width = x.width; + this.height = x.height; + this.x = x.x; + } else { + this.x = x || 0; + this.y = y || 0; + this.width = width || 0; + this.height = height || 0; + } + } + + /** + * !#en TODO + * !#zh 克隆一个新的 Rect。 + * @example + * var a = new cc.Rect(0, 0, 10, 10); + * a.clone();// Rect {x: 0, y: 0, width: 10, height: 10} + */ + public clone () { + return new Rect(this.x, this.y, this.width, this.height); + } + + /** + * !#en TODO + * !#zh 是否等于指定的矩形。 + * @param other + * @example + * var a = new cc.Rect(0, 0, 10, 10); + * var b = new cc.Rect(0, 0, 10, 10); + * a.equals(b);// true; + */ + public equals (other: Rect) { + return this.x === other.x && + this.y === other.y && + this.width === other.width && + this.height === other.height; + } + + /** + * !#en TODO + * !#zh 线性插值 + * + * @param to + * @param ratio - the interpolation coefficient. + * @param out - optional, the receiving vector. + * @example + * var a = new cc.Rect(0, 0, 10, 10); + * var b = new cc.Rect(50, 50, 100, 100); + * update (dt) { + * // method 1; + * var c = a.lerp(b, dt * 0.1); + * // method 2; + * a.lerp(b, dt * 0.1, c); + * } + */ + public lerp (to: Rect, ratio: number, out?: Rect) { + out = out || new Rect(); + const x = this.x; + const y = this.y; + const width = this.width; + const height = this.height; + out.x = x + (to.x - x) * ratio; + out.y = y + (to.y - y) * ratio; + out.width = width + (to.width - width) * ratio; + out.height = height + (to.height - height) * ratio; + return out; + } + + public set (source: Rect) { + this.x = source.x; + this.y = source.y; + this.width = source.width; + this.height = source.height; + } + + /** + * !#en Check whether the current rectangle intersects with the given one + * !#zh 当前矩形与指定矩形是否相交。 + * + * @param other + * @return + * @example + * var a = new cc.Rect(0, 0, 10, 10); + * var b = new cc.Rect(0, 0, 20, 20); + * a.intersects(b);// true + */ + public intersects (other: Rect) { + const maxax = this.x + this.width; + const maxay = this.y + this.height; + const maxbx = other.x + other.width; + const maxby = other.y + other.height; + return !(maxax < other.x || maxbx < this.x || maxay < other.y || maxby < this.y); + } + + /** + * !#en Returns the overlapping portion of 2 rectangles. + * !#zh 返回 2 个矩形重叠的部分。 + * + * @param out Stores the result + * @param rectB + * @return Returns the out parameter + * @example + * var a = new cc.Rect(0, 10, 20, 20); + * var b = new cc.Rect(0, 10, 10, 10); + * var intersection = new cc.Rect(); + * a.intersection(intersection, b); // intersection {x: 0, y: 10, width: 10, height: 10}; + */ + public intersection (out: Rect, rectB: Rect) { + const axMin = this.x; + const ayMin = this.y; + const axMax = this.x + this.width; + const ayMax = this.y + this.height; + const bxMin = rectB.x; + const byMin = rectB.y; + const bxMax = rectB.x + rectB.width; + const byMax = rectB.y + rectB.height; + out.x = Math.max(axMin, bxMin); + out.y = Math.max(ayMin, byMin); + out.width = Math.min(axMax, bxMax) - out.x; + out.height = Math.min(ayMax, byMax) - out.y; + return out; + } + + /** + * !#en Check whether the current rect contains the given point + * !#zh 当前矩形是否包含指定坐标点。 + * Returns true if the point inside this rectangle. + * @param point + * @example + * var a = new cc.Rect(0, 0, 10, 10); + * var b = new cc.Vec2(0, 5); + * a.contains(b);// true + */ + public contains (point: Vec2) { + return (this.x <= point.x && + this.x + this.width >= point.x && + this.y <= point.y && + this.y + this.height >= point.y); + } + + /** + * !#en Returns true if the other rect totally inside this rectangle. + * !#zh 当前矩形是否包含指定矩形。 + * @param other + * @example + * var a = new cc.Rect(0, 0, 20, 20); + * var b = new cc.Rect(0, 0, 10, 10); + * a.containsRect(b);// true + */ + public containsRect (other: Rect) { + return (this.x <= other.x && + this.x + this.width >= other.x + other.width && + this.y <= other.y && + this.y + this.height >= other.y + other.height); + } + + /** + * !#en Returns the smallest rectangle that contains the current rect and the given rect. + * !#zh 返回一个包含当前矩形和指定矩形的最小矩形。 + * @param out Stores the result + * @param rectB + * @return Returns the out parameter + * @example + * var a = new cc.Rect(0, 10, 20, 20); + * var b = new cc.Rect(0, 10, 10, 10); + * var union = new cc.Rect(); + * a.union(union, b); // union {x: 0, y: 10, width: 20, height: 20}; + */ + public union (out: Rect, rectB: Rect) { + const ax = this.x; + const ay = this.y; + const aw = this.width; + const ah = this.height; + const bx = rectB.x; + const by = rectB.y; + const bw = rectB.width; + const bh = rectB.height; + out.x = Math.min(ax, bx); + out.y = Math.min(ay, by); + out.width = Math.max(ax + aw, bx + bw) - out.x; + out.height = Math.max(ay + ah, by + bh) - out.y; + return out; + } + + /** + * !#en Apply matrix4 to the rect. + * !#zh 使用 mat4 对矩形进行矩阵转换。 + * @param out The output rect + * @param mat The matrix4 + */ + public transformMat4 (out: Rect, mat: Mat4) { + const ol = this.x; + const ob = this.y; + const or = ol + this.width; + const ot = ob + this.height; + const lbx = mat.m00 * ol + mat.m04 * ob + mat.m12; + const lby = mat.m01 * ol + mat.m05 * ob + mat.m13; + const rbx = mat.m00 * or + mat.m04 * ob + mat.m12; + const rby = mat.m01 * or + mat.m05 * ob + mat.m13; + const ltx = mat.m00 * ol + mat.m04 * ot + mat.m12; + const lty = mat.m01 * ol + mat.m05 * ot + mat.m13; + const rtx = mat.m00 * or + mat.m04 * ot + mat.m12; + const rty = mat.m01 * or + mat.m05 * ot + mat.m13; + + const minX = Math.min(lbx, rbx, ltx, rtx); + const maxX = Math.max(lbx, rbx, ltx, rtx); + const minY = Math.min(lby, rby, lty, rty); + const maxY = Math.max(lby, rby, lty, rty); + + out.x = minX; + out.y = minY; + out.width = maxX - minX; + out.height = maxY - minY; + return out; + } + + /** + * !#en Output rect informations to string + * !#zh 转换为方便阅读的字符串 + * @example + * var a = new cc.Rect(0, 0, 10, 10); + * a.toString();// "(0.00, 0.00, 10.00, 10.00)"; + */ + public toString () { + return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.width.toFixed(2)}, ${this.height.toFixed(2)})`; + } } CCClass.fastDefine('cc.Rect', Rect, { x: 0, y: 0, width: 0, height: 0 }); @@ -400,8 +389,16 @@ CCClass.fastDefine('cc.Rect', Rect, { x: 0, y: 0, width: 0, height: 0 }); cc.Rect = Rect; /** - * @module cc + * !#en + * The convenience method to create a new Rect. + * see {{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} + * !#zh + * 该方法用来快速创建一个新的矩形。{{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} + * @param rect + * @example + * var a = cc.rect(new Rect(0, 0, 10, 0)); */ +function rect (rect: Rect): Rect; /** * !#en @@ -409,15 +406,20 @@ cc.Rect = Rect; * see {{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} * !#zh * 该方法用来快速创建一个新的矩形。{{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} - * @method rect - * @param {Number} [x=0] - * @param {Number} [y=0] - * @param {Number} [w=0] - * @param {Number} [h=0] - * @return {Rect} + * @param rect + * @param x + * @param y + * @param width + * @param height * @example - * var a = new cc.Rect(0 , 0, 10, 0); + * var a = cc.rect(0, 0, 10, 0); */ -cc.rect = function rect (x, y, w, h) { - return new Rect(x, y, w, h); -}; \ No newline at end of file +function rect (x?: number, y?: number, width?: number, height?: number): Rect; + +function rect (x: Rect | number = 0, y: number = 0, width: number = 0, height: number = 0): Rect { + return new Rect(x as any, y, width, height); +} + +export { rect }; + +cc.rect = rect; diff --git a/cocos/core/value-types/size.js b/cocos/core/value-types/size.ts similarity index 71% rename from cocos/core/value-types/size.js rename to cocos/core/value-types/size.ts index d35ed6d8fe..fc0b0593d3 100644 --- a/cocos/core/value-types/size.js +++ b/cocos/core/value-types/size.ts @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; import CCClass from '../data/class'; +import { ValueType } from './value-type'; /** * !#en @@ -43,34 +43,28 @@ import CCClass from '../data/class'; * @class Size */ export default class Size extends ValueType { - /** - * @method constructor - * @param {Number|Size} width - * @param {Number} [height] - */ - constructor (width, height) { + public width: number; + + public height: number; + + constructor (size: Size); + + constructor (width?: number, height?: number); + + constructor (width?: Size | number, height?: number) { super(); if (width && typeof width === 'object') { - height = width.height; - width = width.width; + this.height = width.height; + this.width = width.width; + } else { + this.width = width || 0; + this.height = height || 0; } - /** - * @property {Number} width - */ - this.width = width || 0; - /** - * @property {Number} height - */ - this.height = height || 0; } /** * !#en return a Size object with width = 0 and height = 0. * !#zh 返回一个宽度为 0 和高度为 0 的 Size 对象。 - * @property ZERO - * @type {Size} - * @default new Size(0, 0) - * @static */ static get ZERO () { return new Size(0.0, 0.0); @@ -79,40 +73,32 @@ export default class Size extends ValueType { /** * !#en Clone a new size object from this one. * !#zh 克隆 size 对象。 - * @method clone - * @return {Size} * @example * var a = new cc.size(10, 10); * a.clone();// return Size {width: 0, height: 0}; */ - clone () { + public clone () { return new Size(this.width, this.height); } /** * !#en TODO * !#zh 当前 Size 对象是否等于指定 Size 对象。 - * @method equals - * @param {Size} other - * @return {Boolean} * @example * var a = new cc.size(10, 10); * a.equals(new cc.size(10, 10));// return true; */ - equals (other) { - return other && - this.width === other.width && + public equals (other: Size) { + return this.width === other.width && this.height === other.height; } /** * !#en TODO * !#zh 线性插值。 - * @method lerp - * @param {Rect} to - * @param {Number} ratio - the interpolation coefficient. - * @param {Size} [out] - optional, the receiving vector. - * @return {Size} + * @param to + * @param ratio - the interpolation coefficient. + * @param out - optional, the receiving vector. * @example * var a = new cc.size(10, 10); * var b = new cc.rect(50, 50, 100, 100); @@ -123,16 +109,16 @@ export default class Size extends ValueType { * a.lerp(b, dt * 0.1, c); * } */ - lerp (to, ratio, out) { + public lerp (to: Size, ratio: number, out?: Size) { out = out || new Size(); - var width = this.width; - var height = this.height; + const width = this.width; + const height = this.height; out.width = width + (to.width - width) * ratio; out.height = height + (to.height - height) * ratio; return out; } - set (source) { + public set (source: Size) { this.width = source.width; this.height = source.height; } @@ -140,22 +126,16 @@ export default class Size extends ValueType { /** * !#en TODO * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {String} * @example * var a = new cc.size(10, 10); * a.toString();// return "(10.00, 10.00)"; */ - toString () { - return '(' + this.width.toFixed(2) + ', ' + this.height.toFixed(2) + ')'; + public toString () { + return `(${this.width.toFixed(2)}, ${this.height.toFixed(2)})`; } } -CCClass.fastDefine('cc.Size', Size, { width: 0, height: 0}); - -/** - * @module cc - */ +CCClass.fastDefine('cc.Size', Size, { width: 0, height: 0 }); /** * !#en @@ -164,14 +144,34 @@ CCClass.fastDefine('cc.Size', Size, { width: 0, height: 0}); * !#zh * 创建一个 cc.Size 对象的帮助函数。
* 注意:可以使用 cc.p 或者是 cc.v2 代替,它们将很快取代 cc.Size。 - * @method size - * @param {Number|Size} w - width or a size object - * @param {Number} [h] - height - * @return {Size} + * + * @param size + * @return * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCSize/size.js} */ -cc.size = function (w, h) { - return new Size(w, h); -}; +function size (size: Size): Size; + +/** + * !#en + * Helper function that creates a cc.Size.
+ * Please use cc.p or cc.v2 instead, it will soon replace cc.Size. + * !#zh + * 创建一个 cc.Size 对象的帮助函数。
+ * 注意:可以使用 cc.p 或者是 cc.v2 代替,它们将很快取代 cc.Size。 + * + * @param [w] - width + * @param [h] - height + * @return + * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCSize/size.js} + */ +function size (width?: number, height?: number): Size; + +function size (width: Size | number = 0, height: number = 0) { + return new Size(width as any, height); +} + +export { size }; + +cc.size = size; cc.Size = Size; diff --git a/cocos/core/value-types/value-type.js b/cocos/core/value-types/value-type.ts similarity index 84% rename from cocos/core/value-types/value-type.js rename to cocos/core/value-types/value-type.ts index 00efa08496..b9cc00d49f 100644 --- a/cocos/core/value-types/value-type.js +++ b/cocos/core/value-types/value-type.ts @@ -32,26 +32,23 @@ import * as js from '../utils/js'; * @class ValueType * */ -export default class ValueType { +export class ValueType { /** * !#en This method returns an exact copy of current value. * !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。 - * @method clone - * @return {ValueType} + * */ - clone () { + public clone (): ValueType { cc.errorID('0100', js.getClassName(this) + '.clone'); - return null; + return this; } /** * !#en Compares this object with the other one. * !#zh 当前对象是否等于指定对象。 - * @method equals - * @param {ValueType} other - * @return {Boolean} + * @param other */ - equals (other) { + public equals (other: this) { cc.errorID('0100', js.getClassName(this) + '.equals'); return false; } @@ -63,12 +60,11 @@ export default class ValueType { * !#zh * 线性插值。
* 当 ratio = 0 时返回自身,ratio = 1 时返回目标,ratio = 0.5 返回自身和目标的平均值。。 - * @method lerp - * @param {ValueType} to - the to value - * @param {number} ratio - the interpolation coefficient - * @return {ValueType} + * @param to - the to value + * @param ratio - the interpolation coefficient + * @returns */ - lerp (to, ratio) { + public lerp (to: this, ratio: number) { cc.errorID('0100', js.getClassName(this) + '.lerp'); return this.clone(); } @@ -78,20 +74,17 @@ export default class ValueType { * Copys all the properties from another given object to this value. * !#zh * 从其它对象把所有属性复制到当前对象。 - * @method set - * @param {ValueType} source - the source to copy + * @param source - the source to copy */ - set (source) { + public set (source: this) { cc.errorID('0100', js.getClassName(this) + '.set'); } /** * !#en TODO * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} */ - toString () { + public toString () { return '' + {}; } } diff --git a/cocos/core/value-types/vec2.js b/cocos/core/value-types/vec2.ts similarity index 66% rename from cocos/core/value-types/vec2.js rename to cocos/core/value-types/vec2.ts index f577484673..9677b3f4d2 100644 --- a/cocos/core/value-types/vec2.js +++ b/cocos/core/value-types/vec2.ts @@ -24,64 +24,77 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; import CCClass from '../data/class'; -import {vec2} from '../vmath'; -import {clampf} from '../utils/misc'; +import {clamp, vec2} from '../vmath'; +import Mat4 from './mat4'; +import { ValueType } from './value-type'; /** * !#en Representation of 2D vectors and points. * !#zh 表示 2D 向量和坐标 - * - * @class Vec2 - * @extends ValueType */ export default class Vec2 extends ValueType { + public x: number; + + public y: number; + /** * !#en * Constructor * see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} * !#zh * 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} - * @method constructor - * @param {number} [x=0] - * @param {number} [y=0] + * @param v */ - constructor (x, y) { + constructor (v: Vec2); + + /** + * !#en + * Constructor + * see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} + * @param [x=0] + * @param [y=0] + */ + constructor (x?: number, y?: number); + + /** + * !#en + * Constructor + * see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} + * @param [x=0] + * @param [y=0] + */ + constructor (x?: number | Vec2, y?: number) { super(); if (x && typeof x === 'object') { - y = x.y; - x = x.x; + this.x = x.x; + this.y = x.y; + } else { + this.x = x || 0; + this.y = y || 0; } - /** - * @property {Number} x - */ - this.x = x || 0; - /** - * @property {Number} y - */ - this.y = y || 0; } /** * !#en clone a Vec2 object * !#zh 克隆一个 Vec2 对象 - * @method clone - * @return {Vec2} */ - clone () { + public clone () { return new Vec2(this.x, this.y); } /** * !#en Sets vector with another's value * !#zh 设置向量值。 - * @method set - * @param {Vec2} newValue - !#en new value to set. !#zh 要设置的新值 - * @return {Vec2} returns this + * @param newValue - !#en new value to set. !#zh 要设置的新值 + * @return returns this * @chainable */ - set (newValue) { + public set (newValue: Vec2) { this.x = newValue.x; this.y = newValue.y; return this; @@ -90,11 +103,10 @@ export default class Vec2 extends ValueType { /** * !#en Check whether two vector equal * !#zh 当前的向量是否与指定的向量相等。 - * @method equals - * @param {Vec2} other - * @return {Boolean} + * @param other + * @return */ - equals (other) { + public equals (other: Vec2) { return other && this.x === other.x && this.y === other.y; } @@ -103,15 +115,15 @@ export default class Vec2 extends ValueType { * !#zh * 近似判断两个点是否相等。
* 判断 2 个向量是否在指定数值的范围之内,如果在则返回 true,反之则返回 false。 - * @method fuzzyEquals - * @param {Vec2} other - * @param {Number} variance - * @return {Boolean} + * @param other + * @param variance + * @return */ - fuzzyEquals (other, variance) { + public fuzzyEquals (other: Vec2, variance: number) { if (this.x - variance <= other.x && other.x <= this.x + variance) { - if (this.y - variance <= other.y && other.y <= this.y + variance) + if (this.y - variance <= other.y && other.y <= this.y + variance) { return true; + } } return false; } @@ -119,29 +131,24 @@ export default class Vec2 extends ValueType { /** * !#en Transform to string with vector informations * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} */ - toString () { - return "(" + - this.x.toFixed(2) + ", " + - this.y.toFixed(2) + ")" - ; + public toString () { + return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)})`; } /** * !#en Calculate linear interpolation result between this vector and another one with given ratio * !#zh 线性插值。 - * @method lerp - * @param {Vec2} to - * @param {number} ratio - the interpolation coefficient - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} + * @param to + * @param ratio - the interpolation coefficient + * @param [out] - optional, the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @return */ - lerp (to, ratio, out) { + public lerp (to: Vec2, ratio: number, out?: Vec2) { out = out || new Vec2(); - var x = this.x; - var y = this.y; + const x = this.x; + const y = this.y; out.x = x + (to.x - x) * ratio; out.y = y + (to.y - y) * ratio; return out; @@ -154,10 +161,9 @@ export default class Vec2 extends ValueType { * 向量大于 max_inclusive 则返回 max_inclusive。
* 向量小于 min_inclusive 则返回 min_inclusive。
* 否则返回自身。 - * @method clampf - * @param {Vec2} min_inclusive - * @param {Vec2} max_inclusive - * @return {Vec2} + * @param min_inclusive + * @param max_inclusive + * @return * @example * var min_inclusive = cc.v2(0, 0); * var max_inclusive = cc.v2(20, 20); @@ -165,24 +171,23 @@ export default class Vec2 extends ValueType { * var v2 = cc.v2(0, 0).clamp(min_inclusive, max_inclusive); // Vec2 {x: 0, y: 0}; * var v3 = cc.v2(10, 10).clamp(min_inclusive, max_inclusive); // Vec2 {x: 10, y: 10}; */ - clampf (min_inclusive, max_inclusive) { - this.x = clampf(this.x, min_inclusive.x, max_inclusive.x); - this.y = clampf(this.y, min_inclusive.y, max_inclusive.y); + public clampf (min_inclusive: Vec2, max_inclusive: Vec2) { + this.x = clamp(this.x, min_inclusive.x, max_inclusive.x); + this.y = clamp(this.y, min_inclusive.y, max_inclusive.y); return this; } /** * !#en Adds this vector. If you want to save result to another vector, use add() instead. * !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 - * @method addSelf - * @param {Vec2} vector - * @return {Vec2} returns this + * @param vector + * @return returns this * @chainable * @example * var v = cc.v2(10, 10); * v.addSelf(cc.v2(5, 5));// return Vec2 {x: 15, y: 15}; */ - addSelf (vector) { + public addSelf (vector: Vec2) { this.x += vector.x; this.y += vector.y; return this; @@ -191,17 +196,17 @@ export default class Vec2 extends ValueType { /** * !#en Adds two vectors, and returns the new result. * !#zh 向量加法,并返回新结果。 - * @method add - * @param {Vec2} vector - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} the result + * @param vector + * @param [out] - optional, the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @return the result * @example * var v = cc.v2(10, 10); * v.add(cc.v2(5, 5)); // return Vec2 {x: 15, y: 15}; * var v1; * v.add(cc.v2(5, 5), v1); // return Vec2 {x: 15, y: 15}; */ - add (vector, out) { + public add (vector: Vec2, out?: Vec2) { out = out || new Vec2(); out.x = this.x + vector.x; out.y = this.y + vector.y; @@ -211,15 +216,14 @@ export default class Vec2 extends ValueType { /** * !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. * !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 - * @method subSelf - * @param {Vec2} vector - * @return {Vec2} returns this + * @param vector + * @return returns this * @chainable * @example * var v = cc.v2(10, 10); * v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5}; */ - subSelf (vector) { + public subSelf (vector: Vec2) { this.x -= vector.x; this.y -= vector.y; return this; @@ -228,17 +232,17 @@ export default class Vec2 extends ValueType { /** * !#en Subtracts one vector from this, and returns the new result. * !#zh 向量减法,并返回新结果。 - * @method sub - * @param {Vec2} vector - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} the result + * @param vector + * @param [out] - optional, the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @return the result * @example * var v = cc.v2(10, 10); * v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5}; * var v1; * v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5}; */ - sub (vector, out) { + public sub (vector: Vec2, out?: Vec2) { out = out || new Vec2(); out.x = this.x - vector.x; out.y = this.y - vector.y; @@ -248,15 +252,14 @@ export default class Vec2 extends ValueType { /** * !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. * !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 - * @method mulSelf - * @param {number} num - * @return {Vec2} returns this + * @param num + * @return returns this * @chainable * @example * var v = cc.v2(10, 10); * v.mulSelf(5);// return Vec2 {x: 50, y: 50}; */ - mulSelf (num) { + public mulSelf (num: number) { this.x *= num; this.y *= num; return this; @@ -265,17 +268,17 @@ export default class Vec2 extends ValueType { /** * !#en Multiplies by a number, and returns the new result. * !#zh 缩放向量,并返回新结果。 - * @method mul - * @param {number} num - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} the result + * @param num + * @param [out] - optional, the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @return the result * @example * var v = cc.v2(10, 10); * v.mul(5); // return Vec2 {x: 50, y: 50}; * var v1; * v.mul(5, v1); // return Vec2 {x: 50, y: 50}; */ - mul (num, out) { + public mul (num: number, out?: Vec2) { out = out || new Vec2(); out.x = this.x * num; out.y = this.y * num; @@ -285,15 +288,14 @@ export default class Vec2 extends ValueType { /** * !#en Multiplies two vectors. * !#zh 分量相乘。 - * @method scaleSelf - * @param {Vec2} vector - * @return {Vec2} returns this + * @param vector + * @return returns this * @chainable * @example * var v = cc.v2(10, 10); * v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50}; */ - scaleSelf (vector) { + public scaleSelf (vector: Vec2) { this.x *= vector.x; this.y *= vector.y; return this; @@ -302,17 +304,18 @@ export default class Vec2 extends ValueType { /** * !#en Multiplies two vectors, and returns the new result. * !#zh 分量相乘,并返回新的结果。 - * @method scale - * @param {Vec2} vector - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} the result + * + * @param vector + * @param [out] - optional, the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @return the result * @example * var v = cc.v2(10, 10); * v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50}; * var v1; * v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50}; */ - scale (vector, out) { + public scale (vector: Vec2, out?: Vec2) { out = out || new Vec2(); out.x = this.x * vector.x; out.y = this.y * vector.y; @@ -322,15 +325,14 @@ export default class Vec2 extends ValueType { /** * !#en Divides by a number. If you want to save result to another vector, use div() instead. * !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 - * @method divSelf - * @param {Vec2} divisor - * @return {Vec2} returns this + * @param divisor + * @return returns this * @chainable * @example * var v = cc.v2(10, 10); * v.divSelf(5); // return Vec2 {x: 2, y: 2}; */ - divSelf (num) { + public divSelf (num: number) { this.x /= num; this.y /= num; return this; @@ -339,17 +341,18 @@ export default class Vec2 extends ValueType { /** * !#en Divides by a number, and returns the new result. * !#zh 向量除法,并返回新的结果。 - * @method div - * @param {Vec2} divisor - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} the result + * + * @param divisor + * @param [out] - optional, the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @return the result * @example * var v = cc.v2(10, 10); * v.div(5); // return Vec2 {x: 2, y: 2}; * var v1; * v.div(5, v1); // return Vec2 {x: 2, y: 2}; */ - div (num, out) { + public div (num: number, out?: Vec2) { out = out || new Vec2(); out.x = this.x / num; out.y = this.y / num; @@ -359,14 +362,13 @@ export default class Vec2 extends ValueType { /** * !#en Negates the components. If you want to save result to another vector, use neg() instead. * !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 - * @method negSelf - * @return {Vec2} returns this + * @return returns this * @chainable * @example * var v = cc.v2(10, 10); * v.negSelf(); // return Vec2 {x: -10, y: -10}; */ - negSelf () { + public negSelf () { this.x = -this.x; this.y = -this.y; return this; @@ -375,15 +377,15 @@ export default class Vec2 extends ValueType { /** * !#en Negates the components, and returns the new result. * !#zh 返回取反后的新向量。 - * @method neg - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} the result + * @param [out] - optional, the receiving vector, you can pass the same vec2 to + * save result to itself, if not provided, a new vec2 will be created + * @return the result * @example * var v = cc.v2(10, 10); * var v1; * v.neg(v1); // return Vec2 {x: -10, y: -10}; */ - neg (out) { + public neg (out?: Vec2) { out = out || new Vec2(); out.x = -this.x; out.y = -this.y; @@ -393,77 +395,73 @@ export default class Vec2 extends ValueType { /** * !#en Dot product * !#zh 当前向量与指定向量进行点乘。 - * @method dot - * @param {Vec2} [vector] - * @return {number} the result + * @param [vector] + * @return the result * @example * var v = cc.v2(10, 10); * v.dot(cc.v2(5, 5)); // return 100; */ - dot (vector) { + public dot (vector: Vec2) { return this.x * vector.x + this.y * vector.y; } /** * !#en Cross product * !#zh 当前向量与指定向量进行叉乘。 - * @method cross - * @param {Vec2} [vector] - * @return {number} the result + * @param [vector] + * @return the result * @example * var v = cc.v2(10, 10); * v.cross(cc.v2(5, 5)); // return 0; */ - cross (vector) { + public cross (vector: Vec2) { return this.x * vector.y - this.y * vector.x; } /** * !#en Returns the length of this vector. * !#zh 返回该向量的长度。 - * @method mag - * @return {number} the result + * @return the result * @example * var v = cc.v2(10, 10); * v.mag(); // return 14.142135623730951; */ - mag () { + public mag () { return Math.sqrt(this.x * this.x + this.y * this.y); } /** * !#en Returns the squared length of this vector. * !#zh 返回该向量的长度平方。 - * @method magSqr - * @return {number} the result + * @return the result * @example * var v = cc.v2(10, 10); * v.magSqr(); // return 200; */ - magSqr () { + public magSqr () { return this.x * this.x + this.y * this.y; } /** * !#en Make the length of this vector to 1. * !#zh 向量归一化,让这个向量的长度为 1。 - * @method normalizeSelf - * @return {Vec2} returns this + * @return returns this * @chainable * @example * var v = cc.v2(10, 10); * v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; */ - normalizeSelf () { - var magSqr = this.x * this.x + this.y * this.y; - if (magSqr === 1.0) + public normalizeSelf () { + const magSqr = this.x * this.x + this.y * this.y; + if (magSqr === 1.0) { return this; + } if (magSqr === 0.0) { return this; } - var invsqrt = 1.0 / Math.sqrt(magSqr); + const invsqrt = 1.0 / Math.sqrt(magSqr); this.x *= invsqrt; this.y *= invsqrt; @@ -474,18 +472,19 @@ export default class Vec2 extends ValueType { * !#en * Returns this vector with a magnitude of 1.
*
- * Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. + * Note that the current vector is unchanged and a new normalized vector is returned. + * If you want to normalize the current vector, use normalizeSelf function. * !#zh * 返回归一化后的向量。
*
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 - * @method normalize - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} result + * @param [out] - optional, the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @return result * var v = cc.v2(10, 10); * v.normalize(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; */ - normalize (out) { + public normalize (out?: Vec2) { out = out || new Vec2(); out.x = this.x; out.y = this.y; @@ -496,46 +495,44 @@ export default class Vec2 extends ValueType { /** * !#en Get angle in radian between this and vector. * !#zh 夹角的弧度。 - * @method angle - * @param {Vec2} vector - * @return {number} from 0 to Math.PI + * @param vector + * @return from 0 to Math.PI */ - angle (vector) { - var magSqr1 = this.magSqr(); - var magSqr2 = vector.magSqr(); + public angle (vector: Vec2) { + const magSqr1 = this.magSqr(); + const magSqr2 = vector.magSqr(); if (magSqr1 === 0 || magSqr2 === 0) { - console.warn("Can't get angle between zero vector"); + console.warn('Can\'t get angle between zero vector'); return 0.0; } - var dot = this.dot(vector); - var theta = dot / (Math.sqrt(magSqr1 * magSqr2)); - theta = clampf(theta, -1.0, 1.0); + const dot = this.dot(vector); + let theta = dot / (Math.sqrt(magSqr1 * magSqr2)); + theta = clamp(theta, -1.0, 1.0); return Math.acos(theta); } /** * !#en Get angle in radian between this and vector with direction. * !#zh 带方向的夹角的弧度。 - * @method signAngle - * @param {Vec2} vector - * @return {number} from -MathPI to Math.PI + * @param vector + * @return from -MathPI to Math.PI */ - signAngle (vector) { - let angle = this.angle(vector); + public signAngle (vector: Vec2) { + const angle = this.angle(vector); return this.cross(vector) < 0 ? -angle : angle; } /** * !#en rotate * !#zh 返回旋转给定弧度后的新向量。 - * @method rotate - * @param {number} radians - * @param {Vec2} [out] - optional, the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @return {Vec2} the result + * @param radians + * @param [out] - optional, the receiving vector, you can pass the same vec2 to + * save result to itself, if not provided, a new vec2 will be created + * @return the result */ - rotate (radians, out) { + public rotate (radians: number, out?: Vec2) { out = out || new Vec2(); out.x = this.x; out.y = this.y; @@ -545,15 +542,14 @@ export default class Vec2 extends ValueType { /** * !#en rotate self * !#zh 按指定弧度旋转向量。 - * @method rotateSelf - * @param {number} radians - * @return {Vec2} returns this + * @param radians + * @return returns this * @chainable */ - rotateSelf (radians) { - var sin = Math.sin(radians); - var cos = Math.cos(radians); - var x = this.x; + public rotateSelf (radians: number) { + const sin = Math.sin(radians); + const cos = Math.cos(radians); + const x = this.x; this.x = cos * x - sin * this.y; this.y = sin * x + cos * this.y; return this; @@ -562,46 +558,42 @@ export default class Vec2 extends ValueType { /** * !#en Calculates the projection of the current vector over the given vector. * !#zh 返回当前向量在指定 vector 向量上的投影向量。 - * @method project - * @param {Vec2} vector - * @return {Vec2} + * @param vector + * @return * @example * var v1 = cc.v2(20, 20); * var v2 = cc.v2(5, 5); * v1.project(v2); // Vec2 {x: 20, y: 20}; */ - project (vector) { + public project (vector: Vec2) { return vector.mul(this.dot(vector) / vector.dot(vector)); } /** * Transforms the vec2 with a mat4. 3rd vector component is implicitly '0', 4th vector component is implicitly '1' - * @method transformMat4 - * @param {mat4} m matrix to transform with - * @param {Vec2} [out] the receiving vector, you can pass the same vec2 to save result to itself, if not provided, a new vec2 will be created - * @returns {Vec2} out + * @param m matrix to transform with + * @param [out] the receiving vector, you can pass the same vec2 + * to save result to itself, if not provided, a new vec2 will be created + * @returns out */ - transformMat4 (m, out) { + public transformMat4 (m: Mat4, out?: Vec2) { out = out || new Vec2(); vec2.transformMat4(out, this, m); } - //_serialize: function () { + // _serialize: function () { // return [this.x, this.y]; - //}, - //_deserialize: function (data) { + // }, + // _deserialize: function (data) { // this.x = data[0]; // this.y = data[1]; - //} + // } // static /** * !#en return a Vec2 object with x = 1 and y = 1. * !#zh 新 Vec2 对象。 - * @property ONE - * @type Vec2 - * @static */ static get ONE () { return new Vec2(1.0, 1.0); @@ -610,9 +602,6 @@ export default class Vec2 extends ValueType { /** * !#en return a Vec2 object with x = 0 and y = 0. * !#zh 返回 x = 0 和 y = 0 的 Vec2 对象。 - * @property ZERO - * @type Vec2 - * @static */ static get ZERO () { return new Vec2(0.0, 0.0); @@ -621,9 +610,6 @@ export default class Vec2 extends ValueType { /** * !#en return a Vec2 object with x = 0 and y = 1. * !#zh 返回 x = 0 和 y = 1 的 Vec2 对象。 - * @property UP - * @type Vec2 - * @static */ static get UP () { return new Vec2(0.0, 1.0); @@ -632,9 +618,6 @@ export default class Vec2 extends ValueType { /** * !#en return a Vec2 object with x = 1 and y = 0. * !#zh 返回 x = 1 和 y = 0 的 Vec2 对象。 - * @property RIGHT - * @type Vec2 - * @static */ static get RIGHT () { return new Vec2(1.0, 0.0); @@ -646,22 +629,32 @@ CCClass.fastDefine('cc.Vec2', Vec2, { x: 0, y: 0 }); cc.Vec2 = Vec2; /** - * @module cc + * !#en The convenience method to create a new {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}} 对象。 + * @param v + * @return + * @example + * var v1 = cc.v2(0, 0); + * var v2 = cc.v2(v1); */ +function v2 (v: Vec2): Vec2; /** * !#en The convenience method to create a new {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}}. * !#zh 通过该简便的函数进行创建 {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}} 对象。 - * @method v2 - * @param {Number|Object} [x=0] - * @param {Number} [y=0] - * @return {Vec2} + * @param [x=0] + * @param [y=0] + * @return * @example * var v1 = cc.v2(); * var v2 = cc.v2(0, 0); - * var v3 = cc.v2(v2); - * var v4 = cc.v2({x: 100, y: 100}); */ -cc.v2 = function v2 (x, y) { - return new Vec2(x, y); -}; \ No newline at end of file +function v2 (x?: number, y?: number): Vec2; + +function v2 (x?: number | Vec2, y?: number) { + return new Vec2(x as any, y); +} + +export { v2 }; + +cc.v2 = v2; diff --git a/cocos/core/value-types/vec3.js b/cocos/core/value-types/vec3.ts similarity index 63% rename from cocos/core/value-types/vec3.js rename to cocos/core/value-types/vec3.ts index b11afc79e7..bdddc417e5 100644 --- a/cocos/core/value-types/vec3.js +++ b/cocos/core/value-types/vec3.ts @@ -24,70 +24,74 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; import CCClass from '../data/class'; -import {vec3} from '../vmath'; -import {clampf} from '../utils/misc'; +import {clamp, vec3} from '../vmath'; +import Mat4 from './mat4'; +import { ValueType } from './value-type'; /** * !#en Representation of 3D vectors and points. * !#zh 表示 3D 向量和坐标 - * - * @class Vec3 - * @extends ValueType */ export default class Vec3 extends ValueType { + public x: number; + + public y: number; + + public z: number; + /** * !#en * Constructor * see {{#crossLink "cc/vec3:method"}}cc.v3{{/crossLink}} * !#zh * 构造函数,可查看 {{#crossLink "cc/vec3:method"}}cc.v3{{/crossLink}} - * @method constructor - * @param {number} [x=0] - * @param {number} [y=0] - * @param {number} [z=0] + * @param v */ - constructor (x, y, z) { + constructor (v: Vec3); + + /** + * !#en + * Constructor + * see {{#crossLink "cc/vec3:method"}}cc.v3{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/vec3:method"}}cc.v3{{/crossLink}} + * @param [x=0] + * @param [y=0] + * @param [z=0] + */ + constructor (x?: number, y?: number, z?: number); + + constructor (x?: number | Vec3, y?: number, z?: number) { super(); if (x && typeof x === 'object') { - z = x.z; - y = x.y; - x = x.x; + this.x = x.x; + this.y = x.y; + this.z = x.z; + } else { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; } - /** - * @property {Number} x - */ - this.x = x || 0; - /** - * @property {Number} y - */ - this.y = y || 0; - /** - * @property {Number} z - */ - this.z = z || 0; } /** * !#en clone a Vec3 value * !#zh 克隆一个 Vec3 值 - * @method clone - * @return {Vec3} */ - clone () { + public clone () { return new Vec3(this.x, this.y, this.z); } /** * !#en Set the current vector value with the given vector. * !#zh 用另一个向量设置当前的向量对象值。 - * @method set - * @param {Vec3} newValue - !#en new value to set. !#zh 要设置的新值 - * @return {Vec3} returns this + * + * @param newValue - !#en new value to set. !#zh 要设置的新值 + * @return returns this * @chainable */ - set (newValue) { + public set (newValue: Vec3) { this.x = newValue.x; this.y = newValue.y; this.z = newValue.z; @@ -97,30 +101,30 @@ export default class Vec3 extends ValueType { /** * !#en Check whether the vector equals another one * !#zh 当前的向量是否与指定的向量相等。 - * @method equals - * @param {Vec3} other - * @return {Boolean} + * + * @param other + * @return */ - equals (other) { - return other && this.x === other.x && this.y === other.y && this.z === other.z; + public equals (other: Vec3) { + return this.x === other.x && this.y === other.y && this.z === other.z; } - /** * !#en Check whether two vector equal with some degree of variance. * !#zh * 近似判断两个点是否相等。
* 判断 2 个向量是否在指定数值的范围之内,如果在则返回 true,反之则返回 false。 - * @method fuzzyEquals - * @param {Vec3} other - * @param {Number} variance - * @return {Boolean} + * + * @param other + * @param variance + * @return */ - fuzzyEquals (other, variance) { + public fuzzyEquals (other: Vec3, variance: number) { if (this.x - variance <= other.x && other.x <= this.x + variance) { if (this.y - variance <= other.y && other.y <= this.y + variance) { - if (this.z - variance <= other.z && other.z <= this.z + variance) + if (this.z - variance <= other.z && other.z <= this.z + variance) { return true; + } } } return false; @@ -129,26 +133,23 @@ export default class Vec3 extends ValueType { /** * !#en Transform to string with vector informations * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} + * + * @return */ - toString () { - return "(" + - this.x.toFixed(2) + ", " + - this.y.toFixed(2) + ", " + - this.z.toFixed(2) + ")"; + public toString () { + return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)})`; } /** * !#en Calculate linear interpolation result between this vector and another one with given ratio * !#zh 线性插值。 - * @method lerp - * @param {Vec3} to - * @param {number} ratio - the interpolation coefficient - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} + * + * @param to + * @param ratio - the interpolation coefficient + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return */ - lerp (to, ratio, out) { + public lerp (to: Vec3, ratio: number, out?: Vec3) { out = out || new Vec3(); vec3.lerp(out, this, to, ratio); return out; @@ -161,27 +162,27 @@ export default class Vec3 extends ValueType { * 向量大于 max_inclusive 则返回 max_inclusive。
* 向量小于 min_inclusive 则返回 min_inclusive。
* 否则返回自身。 - * @method clampf - * @param {Vec3} min_inclusive - * @param {Vec3} max_inclusive - * @return {Vec3} + * + * @param min_inclusive + * @param max_inclusive + * @return */ - clampf (min_inclusive, max_inclusive) { - this.x = clampf(this.x, min_inclusive.x, max_inclusive.x); - this.y = clampf(this.y, min_inclusive.y, max_inclusive.y); - this.z = clampf(this.z, min_inclusive.z, max_inclusive.z); + public clampf (min_inclusive: Vec3, max_inclusive: Vec3) { + this.x = clamp(this.x, min_inclusive.x, max_inclusive.x); + this.y = clamp(this.y, min_inclusive.y, max_inclusive.y); + this.z = clamp(this.z, min_inclusive.z, max_inclusive.z); return this; } /** * !#en Adds this vector. If you want to save result to another vector, use add() instead. * !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 - * @method addSelf - * @param {Vec3} vector - * @return {Vec3} returns this + * + * @param vector + * @return returns this * @chainable */ - addSelf (vector) { + public addSelf (vector: Vec3) { this.x += vector.x; this.y += vector.y; this.z += vector.z; @@ -191,12 +192,12 @@ export default class Vec3 extends ValueType { /** * !#en Adds two vectors, and returns the new result. * !#zh 向量加法,并返回新结果。 - * @method add - * @param {Vec3} vector - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - add (vector, out) { + public add (vector: Vec3, out?: Vec3) { out = out || new Vec3(); out.x = this.x + vector.x; out.y = this.y + vector.y; @@ -207,12 +208,12 @@ export default class Vec3 extends ValueType { /** * !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. * !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 - * @method subSelf - * @param {Vec3} vector - * @return {Vec3} returns this + * + * @param vector + * @return returns this * @chainable */ - subSelf (vector) { + public subSelf (vector: Vec3) { this.x -= vector.x; this.y -= vector.y; this.z -= vector.z; @@ -222,12 +223,12 @@ export default class Vec3 extends ValueType { /** * !#en Subtracts one vector from this, and returns the new result. * !#zh 向量减法,并返回新结果。 - * @method sub - * @param {Vec3} vector - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - sub (vector, out) { + public sub (vector: Vec3, out?: Vec3) { out = out || new Vec3(); out.x = this.x - vector.x; out.y = this.y - vector.y; @@ -238,12 +239,12 @@ export default class Vec3 extends ValueType { /** * !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. * !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 - * @method mulSelf - * @param {number} num - * @return {Vec3} returns this + * + * @param num + * @return returns this * @chainable */ - mulSelf (num) { + public mulSelf (num: number) { this.x *= num; this.y *= num; this.z *= num; @@ -253,12 +254,12 @@ export default class Vec3 extends ValueType { /** * !#en Multiplies by a number, and returns the new result. * !#zh 缩放向量,并返回新结果。 - * @method mul - * @param {number} num - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} the result + * + * @param num + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - mul (num, out) { + public mul (num: number, out?: Vec3) { out = out || new Vec3(); out.x = this.x * num; out.y = this.y * num; @@ -269,12 +270,12 @@ export default class Vec3 extends ValueType { /** * !#en Multiplies two vectors. * !#zh 分量相乘。 - * @method scaleSelf - * @param {Vec3} vector - * @return {Vec3} returns this + * + * @param vector + * @return returns this * @chainable */ - scaleSelf (vector) { + public scaleSelf (vector: Vec3) { this.x *= vector.x; this.y *= vector.y; this.z *= vector.z; @@ -284,12 +285,12 @@ export default class Vec3 extends ValueType { /** * !#en Multiplies two vectors, and returns the new result. * !#zh 分量相乘,并返回新的结果。 - * @method scale - * @param {Vec3} vector - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - scale (vector, out) { + public scale (vector: Vec3, out?: Vec3) { out = out || new Vec3(); out.x = this.x * vector.x; out.y = this.y * vector.y; @@ -300,12 +301,12 @@ export default class Vec3 extends ValueType { /** * !#en Divides by a number. If you want to save result to another vector, use div() instead. * !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 - * @method divSelf - * @param {Vec3} vector - * @return {Vec3} returns this + * + * @param vector + * @return returns this * @chainable */ - divSelf (num) { + public divSelf (num: number) { this.x /= num; this.y /= num; this.z /= num; @@ -315,12 +316,12 @@ export default class Vec3 extends ValueType { /** * !#en Divides by a number, and returns the new result. * !#zh 向量除法,并返回新的结果。 - * @method div - * @param {Vec3} vector - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - div (num, out) { + public div (num: number, out?: Vec3) { out = out || new Vec3(); out.x = this.x / num; out.y = this.y / num; @@ -331,11 +332,11 @@ export default class Vec3 extends ValueType { /** * !#en Negates the components. If you want to save result to another vector, use neg() instead. * !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 - * @method negSelf - * @return {Vec3} returns this + * + * @return returns this * @chainable */ - negSelf () { + public negSelf () { this.x = -this.x; this.y = -this.y; this.z = -this.z; @@ -345,11 +346,11 @@ export default class Vec3 extends ValueType { /** * !#en Negates the components, and returns the new result. * !#zh 返回取反后的新向量。 - * @method neg - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} the result + * + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - neg (out) { + public neg (out?: Vec3) { out = out || new Vec3(); out.x = -this.x; out.y = -this.y; @@ -360,59 +361,59 @@ export default class Vec3 extends ValueType { /** * !#en Dot product * !#zh 当前向量与指定向量进行点乘。 - * @method dot - * @param {Vec3} [vector] - * @return {number} the result + * + * @param [vector] + * @return the result */ - dot (vector) { + public dot (vector: Vec3) { return this.x * vector.x + this.y * vector.y + this.z * vector.z; } /** * !#en Cross product * !#zh 当前向量与指定向量进行叉乘。 - * @method cross - * @param {Vec3} vector - * @param {Vec3} [out] - * @return {Vec3} the result + * + * @param vector + * @param [out] + * @return the result */ - cross (vector, out) { + public cross (vector: Vec3, out?: Vec3) { out = out || new Vec3(); - vec3.cross(out, this, vector) + vec3.cross(out, this, vector); return out; } /** * !#en Returns the length of this vector. * !#zh 返回该向量的长度。 - * @method mag - * @return {number} the result + * + * @return the result * @example * var v = cc.v2(10, 10); * v.mag(); // return 14.142135623730951; */ - mag () { + public mag () { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } /** * !#en Returns the squared length of this vector. * !#zh 返回该向量的长度平方。 - * @method magSqr - * @return {number} the result + * + * @return the result */ - magSqr () { + public magSqr () { return this.x * this.x + this.y * this.y + this.z * this.z; } /** * !#en Make the length of this vector to 1. * !#zh 向量归一化,让这个向量的长度为 1。 - * @method normalizeSelf - * @return {Vec3} returns this + * + * @return returns this * @chainable */ - normalizeSelf () { + public normalizeSelf () { vec3.normalize(this, this); return this; } @@ -421,16 +422,17 @@ export default class Vec3 extends ValueType { * !#en * Returns this vector with a magnitude of 1.
*
- * Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. + * Note that the current vector is unchanged and a new normalized vector is returned. + * If you want to normalize the current vector, use normalizeSelf function. * !#zh * 返回归一化后的向量。
*
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 - * @method normalize - * @param {Vec3} [out] - optional, the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @return {Vec3} result + * + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return result */ - normalize (out) { + public normalize (out?: Vec3) { out = out || new Vec3(); vec3.normalize(out, this); return out; @@ -438,12 +440,12 @@ export default class Vec3 extends ValueType { /** * Transforms the vec3 with a mat4. 4th vector component is implicitly '1' - * @method transformMat4 - * @param {mat4} m matrix to transform with - * @param {vec3} [out] the receiving vector, you can pass the same vec3 to save result to itself, if not provided, a new vec3 will be created - * @returns {vec3} out + * + * @param m matrix to transform with + * @param [out] The receiving vector, can be `this`; if absent, a new vector would be created. + * @returns out */ - transformMat4 (m, out) { + public transformMat4 (m: Mat4, out?: Vec3) { out = out || new Vec3(); vec3.transformMat4(out, this, m); return out; @@ -456,17 +458,35 @@ cc.Vec3 = Vec3; /** * !#en The convenience method to create a new {{#crossLink "Vec3"}}cc.Vec3{{/crossLink}}. * !#zh 通过该简便的函数进行创建 {{#crossLink "Vec3"}}cc.Vec3{{/crossLink}} 对象。 - * @method v3 - * @param {Number|Object} [x=0] - * @param {Number} [y=0] - * @param {Number} [z=0] - * @return {Vec3} + * @param v + * @return * @example * var v1 = cc.v3(); * var v2 = cc.v3(0, 0, 0); * var v3 = cc.v3(v2); * var v4 = cc.v3({x: 100, y: 100, z: 0}); */ -cc.v3 = function v3 (x, y, z) { - return new Vec3(x, y, z); -}; \ No newline at end of file +function v3 (v: Vec3): Vec3; + +/** + * !#en The convenience method to create a new {{#crossLink "Vec3"}}cc.Vec3{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Vec3"}}cc.Vec3{{/crossLink}} 对象。 + * @param [x=0] + * @param [y=0] + * @param [z=0] + * @return + * @example + * var v1 = cc.v3(); + * var v2 = cc.v3(0, 0, 0); + * var v3 = cc.v3(v2); + * var v4 = cc.v3({x: 100, y: 100, z: 0}); + */ +function v3 (x?: number, y?: number, z?: number): Vec3; + +function v3 (x?: number | Vec3, y?: number, z?: number) { + return new Vec3(x as any, y, z); +} + +export { v3 }; + +cc.v3 = v3; diff --git a/cocos/core/value-types/vec4.js b/cocos/core/value-types/vec4.ts similarity index 62% rename from cocos/core/value-types/vec4.js rename to cocos/core/value-types/vec4.ts index 71de353c27..41e3dc37c1 100644 --- a/cocos/core/value-types/vec4.js +++ b/cocos/core/value-types/vec4.ts @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; import CCClass from '../data/class'; -import {vec4} from '../vmath'; -import {clampf} from '../utils/misc'; +import {clamp, vec3, vec4} from '../vmath'; +import Mat4 from './mat4'; +import { ValueType } from './value-type'; /** * !#en Representation of 3D vectors and points. @@ -37,63 +37,73 @@ import {clampf} from '../utils/misc'; * @extends ValueType */ export default class Vec4 extends ValueType { + public x: number; + + public y: number; + + public z: number; + + public w: number; + /** * !#en * Constructor * see {{#crossLink "cc/vec4:method"}}cc.v4{{/crossLink}} * !#zh * 构造函数,可查看 {{#crossLink "cc/vec4:method"}}cc.v4{{/crossLink}} - * @method constructor - * @param {number} [x=0] - * @param {number} [y=0] - * @param {number} [z=0] - * @param {number} [w=0] + * + * @param v */ - constructor (x, y, z, w) { + constructor (v: Vec4); + + /** + * !#en + * Constructor + * see {{#crossLink "cc/vec4:method"}}cc.v4{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/vec4:method"}}cc.v4{{/crossLink}} + * + * @param [x=0] + * @param [y=0] + * @param [z=0] + * @param [w=0] + */ + constructor (x?: number, y?: number, z?: number, w?: number); + + constructor (x?: number | Vec4, y?: number, z?: number, w?: number) { super(); if (x && typeof x === 'object') { - w = x.w; - z = x.z; - y = x.y; - x = x.x; + this.x = x.x; + this.y = x.y; + this.z = x.z; + this.w = x.w; + } else { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = w || 0; } - /** - * @property {Number} x - */ - this.x = x || 0; - /** - * @property {Number} y - */ - this.y = y || 0; - /** - * @property {Number} z - */ - this.z = z || 0; - /** - * @property {Number} z - */ - this.w = w || 0; } /** * !#en clone a Vec4 value * !#zh 克隆一个 Vec4 值 - * @method clone - * @return {Vec4} + * + * @return */ - clone () { + public clone () { return new Vec4(this.x, this.y, this.z, this.w); } /** * !#en Set the current vector value with the given vector. * !#zh 用另一个向量设置当前的向量对象值。 - * @method set - * @param {Vec4} newValue - !#en new value to set. !#zh 要设置的新值 - * @return {Vec4} returns this + * + * @param newValue - !#en new value to set. !#zh 要设置的新值 + * @return returns this * @chainable */ - set (newValue) { + public set (newValue: Vec4) { this.x = newValue.x; this.y = newValue.y; this.z = newValue.z; @@ -104,31 +114,31 @@ export default class Vec4 extends ValueType { /** * !#en Check whether the vector equals another one * !#zh 当前的向量是否与指定的向量相等。 - * @method equals - * @param {Vec4} other - * @return {Boolean} + * + * @param other + * @return */ - equals (other) { - return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; + public equals (other: Vec4) { + return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; } - /** * !#en Check whether two vector equal with some degree of variance. * !#zh * 近似判断两个点是否相等。
* 判断 2 个向量是否在指定数值的范围之内,如果在则返回 true,反之则返回 false。 - * @method fuzzyEquals - * @param {Vec4} other - * @param {Number} variance - * @return {Boolean} + * + * @param other + * @param variance + * @return */ - fuzzyEquals (other, variance) { + public fuzzyEquals (other: Vec4, variance: number) { if (this.x - variance <= other.x && other.x <= this.x + variance) { if (this.y - variance <= other.y && other.y <= this.y + variance) { if (this.z - variance <= other.z && other.z <= this.z + variance) { - if (this.w - variance <= other.w && other.w <= this.w + variance) + if (this.w - variance <= other.w && other.w <= this.w + variance) { return true; + } } } } @@ -138,27 +148,23 @@ export default class Vec4 extends ValueType { /** * !#en Transform to string with vector informations * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} + * + * @return */ - toString () { - return "(" + - this.x.toFixed(2) + ", " + - this.y.toFixed(2) + ", " + - this.z.toFixed(2) + ", " + - this.w.toFixed(2) + ")"; + public toString () { + return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)}, ${this.w.toFixed(2)})`; } /** * !#en Calculate linear interpolation result between this vector and another one with given ratio * !#zh 线性插值。 - * @method lerp - * @param {Vec4} to - * @param {number} ratio - the interpolation coefficient - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} + * + * @param to + * @param ratio - the interpolation coefficient + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return */ - lerp (to, ratio, out) { + public lerp (to: Vec4, ratio: number, out?: Vec4) { out = out || new Vec4(); vec4.lerp(out, this, to, ratio); return out; @@ -171,28 +177,28 @@ export default class Vec4 extends ValueType { * 向量大于 max_inclusive 则返回 max_inclusive。
* 向量小于 min_inclusive 则返回 min_inclusive。
* 否则返回自身。 - * @method clampf - * @param {Vec4} min_inclusive - * @param {Vec4} max_inclusive - * @return {Vec4} + * + * @param min_inclusive + * @param max_inclusive + * @return */ - clampf (min_inclusive, max_inclusive) { - this.x = clampf(this.x, min_inclusive.x, max_inclusive.x); - this.y = clampf(this.y, min_inclusive.y, max_inclusive.y); - this.z = clampf(this.z, min_inclusive.z, max_inclusive.z); - this.w = clampf(this.w, min_inclusive.w, max_inclusive.w); + public clampf (min_inclusive: Vec4, max_inclusive: Vec4) { + this.x = clamp(this.x, min_inclusive.x, max_inclusive.x); + this.y = clamp(this.y, min_inclusive.y, max_inclusive.y); + this.z = clamp(this.z, min_inclusive.z, max_inclusive.z); + this.w = clamp(this.w, min_inclusive.w, max_inclusive.w); return this; } /** * !#en Adds this vector. If you want to save result to another vector, use add() instead. * !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 - * @method addSelf - * @param {Vec4} vector - * @return {Vec4} returns this + * + * @param vector + * @return returns this * @chainable */ - addSelf (vector) { + public addSelf (vector: Vec4) { this.x += vector.x; this.y += vector.y; this.z += vector.z; @@ -203,12 +209,12 @@ export default class Vec4 extends ValueType { /** * !#en Adds two vectors, and returns the new result. * !#zh 向量加法,并返回新结果。 - * @method add - * @param {Vec4} vector - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - add (vector, out) { + public add (vector: Vec4, out?: Vec4) { out = out || new Vec4(); out.x = this.x + vector.x; out.y = this.y + vector.y; @@ -220,12 +226,12 @@ export default class Vec4 extends ValueType { /** * !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. * !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 - * @method subSelf - * @param {Vec4} vector - * @return {Vec4} returns this + * + * @param vector + * @return returns this * @chainable */ - subSelf (vector) { + public subSelf (vector: Vec4) { this.x -= vector.x; this.y -= vector.y; this.z -= vector.z; @@ -236,12 +242,12 @@ export default class Vec4 extends ValueType { /** * !#en Subtracts one vector from this, and returns the new result. * !#zh 向量减法,并返回新结果。 - * @method sub - * @param {Vec4} vector - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - sub (vector, out) { + public sub (vector: Vec4, out?: Vec4) { out = out || new Vec4(); out.x = this.x - vector.x; out.y = this.y - vector.y; @@ -253,12 +259,12 @@ export default class Vec4 extends ValueType { /** * !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. * !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 - * @method mulSelf - * @param {number} num - * @return {Vec4} returns this + * + * @param num + * @return returns this * @chainable */ - mulSelf (num) { + public mulSelf (num: number) { this.x *= num; this.y *= num; this.z *= num; @@ -269,12 +275,12 @@ export default class Vec4 extends ValueType { /** * !#en Multiplies by a number, and returns the new result. * !#zh 缩放向量,并返回新结果。 - * @method mul - * @param {number} num - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} the result + * + * @param num + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - mul (num, out) { + public mul (num: number, out?: Vec4) { out = out || new Vec4(); out.x = this.x * num; out.y = this.y * num; @@ -286,12 +292,12 @@ export default class Vec4 extends ValueType { /** * !#en Multiplies two vectors. * !#zh 分量相乘。 - * @method scaleSelf - * @param {Vec4} vector - * @return {Vec4} returns this + * + * @param vector + * @return returns this * @chainable */ - scaleSelf (vector) { + public scaleSelf (vector: Vec4) { this.x *= vector.x; this.y *= vector.y; this.z *= vector.z; @@ -302,12 +308,12 @@ export default class Vec4 extends ValueType { /** * !#en Multiplies two vectors, and returns the new result. * !#zh 分量相乘,并返回新的结果。 - * @method scale - * @param {Vec4} vector - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - scale (vector, out) { + public scale (vector: Vec4, out?: Vec4) { out = out || new Vec4(); out.x = this.x * vector.x; out.y = this.y * vector.y; @@ -319,12 +325,12 @@ export default class Vec4 extends ValueType { /** * !#en Divides by a number. If you want to save result to another vector, use div() instead. * !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 - * @method divSelf - * @param {Vec4} vector - * @return {Vec4} returns this + * + * @param vector + * @return returns this * @chainable */ - divSelf (num) { + public divSelf (num: number) { this.x /= num; this.y /= num; this.z /= num; @@ -335,12 +341,12 @@ export default class Vec4 extends ValueType { /** * !#en Divides by a number, and returns the new result. * !#zh 向量除法,并返回新的结果。 - * @method div - * @param {Vec4} vector - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} the result + * + * @param vector + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - div (num, out) { + public div (num: number, out?: Vec4) { out = out || new Vec4(); out.x = this.x / num; out.y = this.y / num; @@ -352,11 +358,11 @@ export default class Vec4 extends ValueType { /** * !#en Negates the components. If you want to save result to another vector, use neg() instead. * !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 - * @method negSelf - * @return {Vec4} returns this + * + * @return returns this * @chainable */ - negSelf () { + public negSelf () { this.x = -this.x; this.y = -this.y; this.z = -this.z; @@ -367,11 +373,11 @@ export default class Vec4 extends ValueType { /** * !#en Negates the components, and returns the new result. * !#zh 返回取反后的新向量。 - * @method neg - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} the result + * + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return the result */ - neg (out) { + public neg (out?: Vec4) { out = out || new Vec4(); out.x = -this.x; out.y = -this.y; @@ -383,67 +389,61 @@ export default class Vec4 extends ValueType { /** * !#en Dot product * !#zh 当前向量与指定向量进行点乘。 - * @method dot - * @param {Vec4} [vector] - * @return {number} the result + * + * @param [vector] + * @return the result */ - dot (vector) { + public dot (vector: Vec4) { return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w; } /** * !#en Cross product * !#zh 当前向量与指定向量进行叉乘。 - * @method cross - * @param {Vec4} vector - * @param {Vec4} [out] - * @return {Vec4} the result + * + * @param vector + * @param [out] + * @return the result */ - cross (vector, out) { + public cross (vector: Vec4, out?: Vec4) { out = out || new Vec4(); - vec4.cross(out, this, vector); + vec3.cross(out, this, vector); return out; } /** * !#en Returns the length of this vector. * !#zh 返回该向量的长度。 - * @method mag - * @return {number} the result + * + * @return the result * @example * var v = cc.v4(10, 10); * v.mag(); // return 14.142135623730951; */ - mag () { - let x = this.x, - y = this.y, - z = this.z, - w = this.w; + public mag () { + const { x, y, z, w } = this; return Math.sqrt(x * x + y * y + z * z + w * w); } /** * !#en Returns the squared length of this vector. * !#zh 返回该向量的长度平方。 - * @method magSqr - * @return {number} the result + * + * @return the result */ - magSqr () { - let x = this.x, - y = this.y, - z = this.z, - w = this.w; + public magSqr () { + const { x, y, z, w } = this; return x * x + y * y + z * z + w * w; } /** * !#en Make the length of this vector to 1. * !#zh 向量归一化,让这个向量的长度为 1。 - * @method normalizeSelf - * @return {Vec4} returns this + * + * @return returns this * @chainable */ - normalizeSelf () { + public normalizeSelf () { vec4.normalize(this, this); return this; } @@ -452,16 +452,17 @@ export default class Vec4 extends ValueType { * !#en * Returns this vector with a magnitude of 1.
*
- * Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. + * Note that the current vector is unchanged and a new normalized vector is returned. + * If you want to normalize the current vector, use normalizeSelf function. * !#zh * 返回归一化后的向量。
*
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 - * @method normalize - * @param {Vec4} [out] - optional, the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @return {Vec4} result + * + * @param [out] - The receiving vector, can be `this`; if absent, a new vector would be created. + * @return result */ - normalize (out) { + public normalize (out?: Vec4) { out = out || new Vec4(); vec4.normalize(out, this); return out; @@ -469,12 +470,12 @@ export default class Vec4 extends ValueType { /** * Transforms the vec4 with a mat4. 4th vector component is implicitly '1' - * @method transformMat4 - * @param {mat4} m matrix to transform with - * @param {vec4} [out] the receiving vector, you can pass the same vec4 to save result to itself, if not provided, a new vec4 will be created - * @returns {vec4} out + * + * @param m matrix to transform with + * @param [out] The receiving vector, can be `this`; if absent, a new vector would be created. + * @return out */ - transformMat4 (m, out) { + public transformMat4 (m: Mat4, out?: Vec4) { out = out || new Vec4(); vec4.transformMat4(out, this, m); return out; @@ -487,17 +488,36 @@ cc.Vec4 = Vec4; /** * !#en The convenience method to create a new {{#crossLink "Vec4"}}cc.Vec4{{/crossLink}}. * !#zh 通过该简便的函数进行创建 {{#crossLink "Vec4"}}cc.Vec4{{/crossLink}} 对象。 - * @method v4 - * @param {Number|Object} [x=0] - * @param {Number} [y=0] - * @param {Number} [z=0] - * @return {Vec4} + * @param v + * @return * @example * var v1 = cc.v4(); * var v2 = cc.v4(0, 0, 0); * var v3 = cc.v4(v2); * var v4 = cc.v4({x: 100, y: 100, z: 0}); */ -cc.v4 = function v4 (x, y, z, w) { - return new Vec4(x, y, z, w); -}; \ No newline at end of file +function v4 (v: Vec4): Vec4; + +/** + * !#en The convenience method to create a new {{#crossLink "Vec4"}}cc.Vec4{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Vec4"}}cc.Vec4{{/crossLink}} 对象。 + * @param [x=0] + * @param [y=0] + * @param [z=0] + * @param [w=0] + * @return + * @example + * var v1 = cc.v4(); + * var v2 = cc.v4(0, 0, 0); + * var v3 = cc.v4(v2); + * var v4 = cc.v4({x: 100, y: 100, z: 0}); + */ +function v4 (x?: number, y?: number, z?: number, w?: number): Vec4; + +function v4 (x?: number | Vec4, y?: number, z?: number, w?: number) { + return new Vec4(x as any, y, z, w); +} + +export { v4 }; + +cc.v4 = v4; diff --git a/cocos/core/vmath/color4.ts b/cocos/core/vmath/color4.ts index 957ca79df7..e177ec8714 100644 --- a/cocos/core/vmath/color4.ts +++ b/cocos/core/vmath/color4.ts @@ -1,5 +1,8 @@ import { EPSILON } from './utils'; +// tslint:disable: one-variable-per-declaration +// tslint:disable: class-name + /** * Represents a color with red(r), green(g), blue(b) component of that color and * and an extra alpha(a) component indicating how opaque this color is. @@ -25,7 +28,7 @@ class color4 { * @param a - Color to clone. * @return The newly created color. */ - public static clone (a) { + public static clone (a: color4) { return new color4(a.r, a.g, a.b, a.a); } @@ -36,7 +39,7 @@ class color4 { * @param a - The specified color. * @return out. */ - public static copy (out, a) { + public static copy (out: color4, a: color4) { out.r = a.r; out.g = a.g; out.b = a.b; @@ -54,7 +57,7 @@ class color4 { * @param a - Value assigned to a component. * @return out. */ - public static set (out, r, g, b, a) { + public static set (out: color4, r: number, g: number, b: number, a: number) { out.r = r; out.g = g; out.b = b; @@ -70,7 +73,7 @@ class color4 { * @return out. * @function */ - public static fromHex (out, hex) { + public static fromHex (out: color4, hex: number) { const r = ((hex >> 24)) / 255.0; const g = ((hex >> 16) & 0xff) / 255.0; const b = ((hex >> 8) & 0xff) / 255.0; @@ -91,7 +94,7 @@ class color4 { * @param b - The second operand. * @return out. */ - public static add (out, a, b) { + public static add (out: color4, a: color4, b: color4) { out.r = a.r + b.r; out.g = a.g + b.g; out.b = a.b + b.b; @@ -107,7 +110,7 @@ class color4 { * @param b - The b. * @return out. */ - public static subtract (out, a, b) { + public static subtract (out: color4, a: color4, b: color4) { out.r = a.r - b.r; out.g = a.g - b.g; out.b = a.b - b.b; @@ -118,7 +121,7 @@ class color4 { /** * Alias of {@link color4.subtract}. */ - public static sub (out, a, b) { + public static sub (out: color4, a: color4, b: color4) { return color4.subtract(out, a, b); } @@ -130,7 +133,7 @@ class color4 { * @param b - The second operand. * @return out. */ - public static multiply (out, a, b) { + public static multiply (out: color4, a: color4, b: color4) { out.r = a.r * b.r; out.g = a.g * b.g; out.b = a.b * b.b; @@ -141,7 +144,7 @@ class color4 { /** * Alias of {@link color4.multiply}. */ - public static mul (out, a, b) { + public static mul (out: color4, a: color4, b: color4) { return color4.multiply(out, a, b); } @@ -153,7 +156,7 @@ class color4 { * @param b - The second operand. * @return out. */ - public static divide (out, a, b) { + public static divide (out: color4, a: color4, b: color4) { out.r = a.r / b.r; out.g = a.g / b.g; out.b = a.b / b.b; @@ -164,7 +167,7 @@ class color4 { /** * Alias of {@link color4.divide}. */ - public static div (out, a, b) { + public static div (out: color4, a: color4, b: color4) { return color4.divide(out, a, b); } @@ -176,7 +179,7 @@ class color4 { * @param b - The scale number. * @return out. */ - public static scale (out, a, b) { + public static scale (out: color4, a: color4, b: number) { out.r = a.r * b; out.g = a.g * b; out.b = a.b * b; @@ -193,11 +196,8 @@ class color4 { * @param t - The interpolation coefficient. * @return out. */ - public static lerp (out, a, b, t) { - const ar = a.r, - ag = a.g, - ab = a.b, - aa = a.a; + public static lerp (out: color4, a: color4, b: color4, t: number) { + const ar = a.r, ag = a.g, ab = a.b, aa = a.a; out.r = ar + t * (b.r - ar); out.g = ag + t * (b.g - ag); out.b = ab + t * (b.b - ab); @@ -211,7 +211,7 @@ class color4 { * @param a - The color. * @return - String representation of this color. */ - public static str (a) { + public static str (a: color4) { return `color4(${a.r}, ${a.g}, ${a.b}, ${a.a})`; } @@ -222,12 +222,12 @@ class color4 { * @param a - The color. * @return out. */ - public static array (out, a) { + public static array> (out: Out, a: color4, ofs = 0) { const scale = (a instanceof cc.Color || a.a > 1) ? 1 / 255 : 1; - out[0] = a.r * scale; - out[1] = a.g * scale; - out[2] = a.b * scale; - out[3] = a.a * scale; + out[ofs + 0] = a.r * scale; + out[ofs + 1] = a.g * scale; + out[ofs + 2] = a.b * scale; + out[ofs + 3] = a.a * scale; return out; } @@ -239,7 +239,7 @@ class color4 { * @param b - The second color. * @return True if the colors are equal, false otherwise. */ - public static exactEquals (a, b) { + public static exactEquals (a: color4, b: color4) { return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; } @@ -248,9 +248,9 @@ class color4 { * * @param a - The first color. * @param b - The second color. - * @return True if the colors are approximately equal, false otherwise. + * @return True if the colors are equal, false otherwise. */ - public static equals (a, b) { + public static equals (a: color4, b: color4) { const a0 = a.r, a1 = a.g, a2 = a.b, a3 = a.a; const b0 = b.r, b1 = b.g, b2 = b.b, b3 = b.a; return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && @@ -261,44 +261,23 @@ class color4 { /** * Converts a color's rgb formal into the hexadecimal one. - * - * @param a - The color. - * @return - The color's hexadecimal formal. */ - public static hex (a) { + public static hex (a: color4) { return ((a.r * 255) << 24 | (a.g * 255) << 16 | (a.b * 255) << 8 | a.a * 255) >>> 0; } + + public r: number; + public g: number; + public b: number; + public a: number; + /** * Creates a color, with components specified separately. - * - * @param r - Value assigned to r component. - * @param g - Value assigned to g component. - * @param b - Value assigned to b component. - * @param a - Value assigned to a component. */ constructor (r = 1, g = 1, b = 1, a = 1) { - /** - * The r component. - * @type {number} - * */ this.r = r; - - /** - * The g component. - * @type {number} - * */ this.g = g; - - /** - * The b component. - * @type {number} - * */ this.b = b; - - /** - * The a component. - * @type {number} - * */ this.a = a; } } diff --git a/cocos/core/vmath/mat2.ts b/cocos/core/vmath/mat2.ts index 1637a2d533..4df9217f45 100644 --- a/cocos/core/vmath/mat2.ts +++ b/cocos/core/vmath/mat2.ts @@ -271,11 +271,11 @@ class mat2 { * @param m - The matrix. * @return out. */ - public static array(out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; + public static array(out, m, ofs = 0) { + out[ofs + 0] = m.m00; + out[ofs + 1] = m.m01; + out[ofs + 2] = m.m02; + out[ofs + 3] = m.m03; return out; } diff --git a/cocos/core/vmath/mat3.ts b/cocos/core/vmath/mat3.ts index e263029312..d2934883a4 100644 --- a/cocos/core/vmath/mat3.ts +++ b/cocos/core/vmath/mat3.ts @@ -1,5 +1,6 @@ import { EPSILON } from './utils'; import vec3 from './vec3'; +// tslint:disable: one-variable-per-declaration /** * Mathematical 3x3 matrix. @@ -15,7 +16,8 @@ import vec3 from './vec3'; * 0, 0, 1, 0, * x, y, z, 0] * - * The same matrix in the [OpenGL documentation](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml) + * The same matrix in the + * [OpenGL documentation](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml) * is written as: * * 1 0 0 x @@ -43,7 +45,7 @@ class mat3 { * @param m08 - Value assigned to element at column 2 row 2. * @return The newly created matrix. */ - public static create(m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, m06 = 0, m07 = 0, m08 = 1) { + public static create (m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, m06 = 0, m07 = 0, m08 = 1) { return new mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08); } @@ -53,7 +55,7 @@ class mat3 { * @param a - Matrix to clone. * @return The newly created matrix. */ - public static clone(a) { + public static clone (a) { return new mat3( a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, @@ -68,7 +70,7 @@ class mat3 { * @param a - The specified matrix. * @return out. */ - public static copy(out, a) { + public static copy (out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; @@ -96,7 +98,7 @@ class mat3 { * @param m22 - Value assigned to element at column 2 row 2. * @return out. */ - public static set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { + public static set (out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { out.m00 = m00; out.m01 = m01; out.m02 = m02; @@ -114,7 +116,7 @@ class mat3 { * * @return out. */ - public static identity(out) { + public static identity (out) { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -134,7 +136,7 @@ class mat3 { * @param a - Matrix to transpose. * @return out. */ - public static transpose(out, a) { + public static transpose (out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { const a01 = a.m01, a02 = a.m02, a12 = a.m05; @@ -166,7 +168,7 @@ class mat3 { * @param a - Matrix to invert. * @return out. */ - public static invert(out, a) { + public static invert (out, a) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; @@ -202,7 +204,7 @@ class mat3 { * @param a - Matrix to calculate. * @return out. */ - public static adjoint(out, a) { + public static adjoint (out, a) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; @@ -225,7 +227,7 @@ class mat3 { * @param a - Matrix to calculate. * @return Determinant of a. */ - public static determinant(a) { + public static determinant (a) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; @@ -241,7 +243,7 @@ class mat3 { * @param b - The second operand. * @return out. */ - public static multiply(out, a, b) { + public static multiply (out, a, b) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; @@ -267,7 +269,7 @@ class mat3 { /** * Alias of {@link mat3.multiply}. */ - public static mul(out, a, b) { + public static mul (out, a, b) { return mat3.multiply(out, a, b); } @@ -279,7 +281,7 @@ class mat3 { * @param v - The translation offset. * @return out. */ - public static translate(out, a, v) { + public static translate (out, a, v) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; @@ -307,7 +309,7 @@ class mat3 { * @param rad - The rotation angle. * @return out */ - public static rotate(out, a, rad) { + public static rotate (out, a, rad) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; @@ -336,8 +338,8 @@ class mat3 { * @param a - Matrix to multiply. * @param v - The scale vector. * @return out - **/ - public static scale(out, a, v) { + */ + public static scale (out, a, v) { const x = v.x, y = v.y; out.m00 = x * a.m00; @@ -361,7 +363,7 @@ class mat3 { * @param a - The 4x4 matrix. * @return out. */ - public static fromMat4(out, a) { + public static fromMat4 (out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; @@ -385,7 +387,7 @@ class mat3 { * @param v - The translation offset. * @return out. */ - public static fromTranslation(out, v) { + public static fromTranslation (out, v) { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -409,7 +411,7 @@ class mat3 { * @param rad - The rotation angle. * @return out. */ - public static fromRotation(out, rad) { + public static fromRotation (out, rad) { const s = Math.sin(rad), c = Math.cos(rad); out.m00 = c; @@ -437,7 +439,7 @@ class mat3 { * @param v - Scale vector. * @return out. */ - public static fromScaling(out, v) { + public static fromScaling (out, v) { out.m00 = v.x; out.m01 = 0; out.m02 = 0; @@ -458,8 +460,8 @@ class mat3 { * @param out - Matrix to store result. * @param a - The 2x3 matrix. * @return out. - **/ - public static fromMat2d(out, a) { + */ + public static fromMat2d (out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = 0; @@ -482,7 +484,7 @@ class mat3 { * * @return out. */ - public static fromQuat(out, q) { + public static fromQuat (out, q) { const x = q.x, y = q.y, z = q.z, w = q.w; const x2 = x + x; const y2 = y + y; @@ -522,13 +524,13 @@ class mat3 { * * @return out */ - public static fromViewUp(out, view, up) { - const _fromViewUpIIFE = (function() { + public static fromViewUp (_out, _view, _up) { + const _fromViewUpIIFE = (() => { const default_up = vec3.create(0, 1, 0); const x = vec3.create(0, 0, 0); const y = vec3.create(0, 0, 0); - return function(out, view, up) { + return (out, view, up) => { if (vec3.sqrMag(view) < EPSILON * EPSILON) { mat3.identity(out); return out; @@ -553,7 +555,7 @@ class mat3 { return out; }; })(); - return _fromViewUpIIFE(out, view, up); + return _fromViewUpIIFE(_out, _view, _up); } /** @@ -564,7 +566,7 @@ class mat3 { * * @return out. */ - public static normalFromMat4(out, a) { + public static normalFromMat4 (out, a) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, @@ -612,7 +614,7 @@ class mat3 { * @param a - The matrix. * @return String representation of this matrix. */ - public static str(a) { + public static str (a) { return `mat3(${a.m00}, ${a.m01}, ${a.m02}, ${a.m03}, ${a.m04}, ${a.m05}, ${a.m06}, ${a.m07}, ${a.m08})`; } @@ -623,16 +625,16 @@ class mat3 { * @param m - The matrix. * @return out. */ - public static array(out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - out[4] = m.m04; - out[5] = m.m05; - out[6] = m.m06; - out[7] = m.m07; - out[8] = m.m08; + public static array (out, m, ofs = 0) { + out[ofs + 0] = m.m00; + out[ofs + 1] = m.m01; + out[ofs + 2] = m.m02; + out[ofs + 3] = m.m03; + out[ofs + 4] = m.m04; + out[ofs + 5] = m.m05; + out[ofs + 6] = m.m06; + out[ofs + 7] = m.m07; + out[ofs + 8] = m.m08; return out; } @@ -643,8 +645,10 @@ class mat3 { * @param a - Matrix to calculate Frobenius norm of. * @return - The frobenius norm. */ - public static frob(a) { - return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2))); + public static frob (a) { + return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + + Math.pow(a.m07, 2) + Math.pow(a.m08, 2))); } /** @@ -655,7 +659,7 @@ class mat3 { * @param b - The second operand. * @return out. */ - public static add(out, a, b) { + public static add (out, a, b) { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; @@ -676,7 +680,7 @@ class mat3 { * @param b - The second operand. * @return out. */ - public static subtract(out, a, b) { + public static subtract (out, a, b) { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; @@ -692,7 +696,7 @@ class mat3 { /** * Alias of {@link mat3.subtract}. */ - public static sub(out, a, b) { + public static sub (out, a, b) { return mat3.subtract(out, a, b); } @@ -704,7 +708,7 @@ class mat3 { * @param b - The scale number. * @return out. */ - public static multiplyScalar(out, a, b) { + public static multiplyScalar (out, a, b) { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; @@ -726,7 +730,7 @@ class mat3 { * @param scale - The scale number. * @return out. */ - public static multiplyScalarAndAdd(out, a, b, scale) { + public static multiplyScalarAndAdd (out, a, b, scale) { out.m00 = a.m00 + (b.m00 * scale); out.m01 = a.m01 + (b.m01 * scale); out.m02 = a.m02 + (b.m02 * scale); @@ -746,7 +750,7 @@ class mat3 { * @param b - The second matrix. * @return True if the matrices are equal, false otherwise. */ - public static exactEquals(a, b) { + public static exactEquals (a, b) { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08; @@ -759,9 +763,11 @@ class mat3 { * @param b - The second matrix. * @return True if the matrices are equal, false otherwise. */ - public static equals(a, b) { + public static equals (a, b) { + // tslint:disable: max-line-length const a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, a8 = a.m08; const b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05, b6 = b.m06, b7 = b.m07, b8 = b.m08; + // tslint:enable: max-line-length return ( Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && @@ -774,6 +780,17 @@ class mat3 { Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) ); } + + public m00: number; + public m01: number; + public m02: number; + public m03: number; + public m04: number; + public m05: number; + public m06: number; + public m07: number; + public m08: number; + /** * Creates a matrix, with elements specified separately. * @@ -787,7 +804,7 @@ class mat3 { * @param m07 - Value assigned to element at column 2 row 1. * @param m08 - Value assigned to element at column 2 row 2. */ - constructor( + constructor ( m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, m06 = 0, m07 = 0, m08 = 1, @@ -795,55 +812,55 @@ class mat3 { /** * The element at column 0 row 0. * @type {number} - * */ + */ this.m00 = m00; /** * The element at column 0 row 1. * @type {number} - * */ + */ this.m01 = m01; /** * The element at column 0 row 2. * @type {number} - * */ + */ this.m02 = m02; /** * The element at column 1 row 0. * @type {number} - * */ + */ this.m03 = m03; /** * The element at column 1 row 1. * @type {number} - * */ + */ this.m04 = m04; /** * The element at column 1 row 2. * @type {number} - * */ + */ this.m05 = m05; /** * The element at column 2 row 0. * @type {number} - * */ + */ this.m06 = m06; /** * The element at column 2 row 1. * @type {number} - * */ + */ this.m07 = m07; /** * The element at column 2 row 2. * @type {number} - * */ + */ this.m08 = m08; } } diff --git a/cocos/core/vmath/mat4.ts b/cocos/core/vmath/mat4.ts index ab86e056af..3890527d26 100644 --- a/cocos/core/vmath/mat4.ts +++ b/cocos/core/vmath/mat4.ts @@ -1,5 +1,7 @@ import { EPSILON } from './utils'; +// tslint:disable: one-variable-per-declaration + /** * Mathematical 4x4 matrix. * @@ -27,7 +29,6 @@ import { EPSILON } from './utils'; * apparent lack of consistency between the memory layout and the documentation. */ class mat4 { - /** * Creates a matrix, with elements specified separately. * @@ -49,7 +50,7 @@ class mat4 { * @param m15 - Value assigned to element at column 3 row 3. * @return The newly created matrix. */ - public static create( + public static create ( m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 0, m05 = 1, m06 = 0, m07 = 0, m08 = 0, m09 = 0, m10 = 1, m11 = 0, @@ -68,7 +69,7 @@ class mat4 { * @param a - Matrix to clone. * @return The newly created matrix. */ - public static clone(a) { + public static clone (a) { return new mat4( a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, @@ -84,7 +85,7 @@ class mat4 { * @param a - The specified matrix. * @return out. */ - public static copy(out, a) { + public static copy (out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; @@ -126,7 +127,7 @@ class mat4 { * @param m33 - Value assigned to element at column 3 row 3. * @return out. */ - public static set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + public static set (out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { out.m00 = m00; out.m01 = m01; out.m02 = m02; @@ -152,7 +153,7 @@ class mat4 { * @param out - Matrix to modified. * @return out. */ - public static identity(out) { + public static identity (out) { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -179,7 +180,7 @@ class mat4 { * @param a - Matrix to transpose. * @return out. */ - public static transpose(out, a) { + public static transpose (out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { const a01 = a.m01, a02 = a.m02, a03 = a.m03, @@ -227,7 +228,7 @@ class mat4 { * @param a - Matrix to invert. * @return out. */ - public static invert(out, a) { + public static invert (out, a) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, @@ -281,7 +282,7 @@ class mat4 { * @param a - Matrix to calculate. * @return out. */ - public static adjoint(out, a) { + public static adjoint (out, a) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, @@ -312,7 +313,7 @@ class mat4 { * @param a - Matrix to calculate. * @return Determinant of a. */ - public static determinant(a) { + public static determinant (a) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, @@ -343,7 +344,7 @@ class mat4 { * @param b - The second operand. * @return out. */ - public static multiply(out, a, b) { + public static multiply (out, a, b) { const a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, @@ -379,7 +380,7 @@ class mat4 { /** * Alias of {@link mat4.multiply}. */ - public static mul(out, a, b) { + public static mul (out, a, b) { return mat4.multiply(out, a, b); } @@ -391,9 +392,9 @@ class mat4 { * @param v - The translation offset. * @return out. */ - public static translate(out, a, v) { - let x = v.x, y = v.y, z = v.z, - a00, a01, a02, a03, + public static translate (out, a, v) { + const x = v.x, y = v.y, z = v.z; + let a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23; @@ -427,8 +428,8 @@ class mat4 { * @param a - Matrix to multiply. * @param v - The scale vector. * @return out - **/ - public static scale(out, a, v) { + */ + public static scale (out, a, v) { const x = v.x, y = v.y, z = v.z; out.m00 = a.m00 * x; @@ -459,7 +460,7 @@ class mat4 { * @param axis - The rotation axis. * @return out. */ - public static rotate(out, a, rad, axis) { + public static rotate (out, a, rad, axis) { let x = axis.x, y = axis.y, z = axis.z; let s, c, t, a00, a01, a02, a03, @@ -526,7 +527,7 @@ class mat4 { * @param rad - The rotation angle. * @return out. */ - public static rotateX(out, a, rad) { + public static rotateX (out, a, rad) { const s = Math.sin(rad), c = Math.cos(rad), a10 = a.m04, @@ -570,7 +571,7 @@ class mat4 { * @param rad - The rotation angle. * @return out. */ - public static rotateY(out, a, rad) { + public static rotateY (out, a, rad) { const s = Math.sin(rad), c = Math.cos(rad), a00 = a.m00, @@ -614,7 +615,7 @@ class mat4 { * @param rad - The rotation angle. * @return out. */ - public static rotateZ(out, a, rad) { + public static rotateZ (out, a, rad) { const s = Math.sin(rad), c = Math.cos(rad), a00 = a.m00, @@ -662,7 +663,7 @@ class mat4 { * @param v - The translation offset. * @return out. */ - public static fromTranslation(out, v) { + public static fromTranslation (out, v) { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -693,7 +694,7 @@ class mat4 { * @param v - The scale vector. * @return out. */ - public static fromScaling(out, v) { + public static fromScaling (out, v) { out.m00 = v.x; out.m01 = 0; out.m02 = 0; @@ -725,7 +726,7 @@ class mat4 { * @param axis - The rotation axis. * @return out. */ - public static fromRotation(out, rad, axis) { + public static fromRotation (out, rad, axis) { let x = axis.x, y = axis.y, z = axis.z; let len = Math.sqrt(x * x + y * y + z * z); let s, c, t; @@ -774,7 +775,7 @@ class mat4 { * @param rad - The rotation angle. * @return out. */ - public static fromXRotation(out, rad) { + public static fromXRotation (out, rad) { const s = Math.sin(rad), c = Math.cos(rad); @@ -809,7 +810,7 @@ class mat4 { * @param rad - The rotation angle. * @return out. */ - public static fromYRotation(out, rad) { + public static fromYRotation (out, rad) { const s = Math.sin(rad), c = Math.cos(rad); @@ -844,7 +845,7 @@ class mat4 { * @param rad - The rotation angle. * @return out. */ - public static fromZRotation(out, rad) { + public static fromZRotation (out, rad) { const s = Math.sin(rad), c = Math.cos(rad); @@ -883,7 +884,7 @@ class mat4 { * @param v - Translation vector. * @return out. */ - public static fromRT(out, q, v) { + public static fromRT (out, q, v) { // Quaternion math const x = q.x, y = q.y, z = q.z, w = q.w; const x2 = x + x; @@ -929,7 +930,7 @@ class mat4 { * @param {mat4} mat - Matrix to be decomposed. * @return out. */ - public static getTranslation(out, mat) { + public static getTranslation (out, mat) { out.x = mat.m12; out.y = mat.m13; out.z = mat.m14; @@ -947,7 +948,7 @@ class mat4 { * @param {mat4} mat - Matrix to be decomposed. * @return out. */ - public static getScaling(out, mat) { + public static getScaling (out, mat) { const m11 = mat.m00, m12 = mat.m01, m13 = mat.m02, @@ -974,8 +975,8 @@ class mat4 { * @param mat - Matrix to be decomposed. * @return out. */ - public static getRotation(out, mat) { - // Algorithm taken from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + public static getRotation (out, mat) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm const trace = mat.m00 + mat.m05 + mat.m10; let S = 0; @@ -985,7 +986,7 @@ class mat4 { out.x = (mat.m06 - mat.m09) / S; out.y = (mat.m08 - mat.m02) / S; out.z = (mat.m01 - mat.m04) / S; - } else if ((mat.m00 > mat.m05) & (mat.m00 > mat.m10)) { + } else if ((mat.m00 > mat.m05) && (mat.m00 > mat.m10)) { S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2; out.w = (mat.m06 - mat.m09) / S; out.x = 0.25 * S; @@ -1025,7 +1026,7 @@ class mat4 { * @param s - Scale vector. * @return out. */ - public static fromRTS(out, q, v, s) { + public static fromRTS (out, q, v, s) { // Quaternion math const x = q.x, y = q.y, z = q.z, w = q.w; const x2 = x + x; @@ -1066,7 +1067,8 @@ class mat4 { } /** - * Creates a matrix from a quaternion rotation, translation offset and scale vector, rotating and scaling around the given origin. + * Creates a matrix from a quaternion rotation, translation offset and scale vector, + * rotating and scaling around the given origin. * This is equivalent to (but much faster than): * * mat4.identity(dest); @@ -1085,7 +1087,7 @@ class mat4 { * @param o The origin vector around which to scale and rotate. * @return out. */ - public static fromRTSOrigin(out, q, v, s, o) { + public static fromRTSOrigin (out, q, v, s, o) { // Quaternion math const x = q.x, y = q.y, z = q.z, w = q.w; const x2 = x + x; @@ -1138,7 +1140,7 @@ class mat4 { * * @return out. */ - public static fromQuat(out, q) { + public static fromQuat (out, q) { const x = q.x, y = q.y, z = q.z, w = q.w; const x2 = x + x; const y2 = y + y; @@ -1189,7 +1191,7 @@ class mat4 { * @param far - Far bound of the frustum. * @return out. */ - public static frustum(out, left, right, bottom, top, near, far) { + public static frustum (out, left, right, bottom, top, near, far) { const rl = 1 / (right - left); const tb = 1 / (top - bottom); const nf = 1 / (near - far); @@ -1223,7 +1225,7 @@ class mat4 { * @param far - Far bound of the frustum. * @return out. */ - public static perspective(out, fovy, aspect, near, far) { + public static perspective (out, fovy, aspect, near, far) { const f = 1.0 / Math.tan(fovy / 2); const nf = 1 / (near - far); @@ -1257,7 +1259,7 @@ class mat4 { * @param far - Far bound of the frustum. * @return out. */ - public static perspectiveFromFieldOfView(out, fov, near, far) { + public static perspectiveFromFieldOfView (out, fov, near, far) { const upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); const downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); const leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); @@ -1296,7 +1298,7 @@ class mat4 { * @param far - Far bound of the frustum. * @return out. */ - public static ortho(out, left, right, bottom, top, near, far) { + public static ortho (out, left, right, bottom, top, near, far) { const lr = 1 / (left - right); const bt = 1 / (bottom - top); const nf = 1 / (near - far); @@ -1329,7 +1331,7 @@ class mat4 { * @param up - Vector pointing up. * @return out */ - public static lookAt(out, eye, center, up) { + public static lookAt (out, eye, center, up) { let x0, x1, x2, y0, y1, y2, z0, z1, z2, len; const eyex = eye.x; const eyey = eye.y; @@ -1388,8 +1390,67 @@ class mat4 { * @param a - The matrix. * @return String representation of this matrix. */ - public static str(a) { - return `mat4(${a.m00}, ${a.m01}, ${a.m02}, ${a.m03}, ${a.m04}, ${a.m05}, ${a.m06}, ${a.m07}, ${a.m08}, ${a.m09}, ${a.m10}, ${a.m11}, ${a.m12}, ${a.m13}, ${a.m14}, ${a.m15})`; + public static str (a) { + return `mat4(${a.m00}, ${a.m01}, ${a.m02}, ${a.m03}, ${a.m04}, ${a.m05}, ${a.m06}, ${a.m07}, ` + + `${a.m08}, ${a.m09}, ${a.m10}, ${a.m11}, ${a.m12}, ${a.m13}, ${a.m14}, ${a.m15})`; + } + + /** + * Calculates normal matrix (transpose inverse). + * + * @param out - Matrix to store result. + * @param a - A 4x4 matrix to derive the normal matrix from. + * + * @return out. + */ + public static normalMatrix (out, a) { + const a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, + a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, + a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, + a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; + + const b00 = a00 * a11 - a01 * a10; + const b01 = a00 * a12 - a02 * a10; + const b02 = a00 * a13 - a03 * a10; + const b03 = a01 * a12 - a02 * a11; + const b04 = a01 * a13 - a03 * a11; + const b05 = a02 * a13 - a03 * a12; + const b06 = a20 * a31 - a21 * a30; + const b07 = a20 * a32 - a22 * a30; + const b08 = a20 * a33 - a23 * a30; + const b09 = a21 * a32 - a22 * a31; + const b10 = a21 * a33 - a23 * a31; + const b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + det = 1.0 / det; + + out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out.m03 = 0; + + out.m04 = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out.m06 = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out.m07 = 0; + + out.m08 = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out.m09 = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out.m11 = 0; + + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 1; + + return out; } /** @@ -1399,23 +1460,23 @@ class mat4 { * @param m - The matrix. * @return out. */ - public static array(out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - out[4] = m.m04; - out[5] = m.m05; - out[6] = m.m06; - out[7] = m.m07; - out[8] = m.m08; - out[9] = m.m09; - out[10] = m.m10; - out[11] = m.m11; - out[12] = m.m12; - out[13] = m.m13; - out[14] = m.m14; - out[15] = m.m15; + public static array (out, m, ofs = 0) { + out[ofs + 0] = m.m00; + out[ofs + 1] = m.m01; + out[ofs + 2] = m.m02; + out[ofs + 3] = m.m03; + out[ofs + 4] = m.m04; + out[ofs + 5] = m.m05; + out[ofs + 6] = m.m06; + out[ofs + 7] = m.m07; + out[ofs + 8] = m.m08; + out[ofs + 9] = m.m09; + out[ofs + 10] = m.m10; + out[ofs + 11] = m.m11; + out[ofs + 12] = m.m12; + out[ofs + 13] = m.m13; + out[ofs + 14] = m.m14; + out[ofs + 15] = m.m15; return out; } @@ -1426,8 +1487,11 @@ class mat4 { * @param a - Matrix to calculate Frobenius norm of. * @return - The frobenius norm. */ - public static frob(a) { - return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2) + Math.pow(a.m09, 2) + Math.pow(a.m10, 2) + Math.pow(a.m11, 2) + Math.pow(a.m12, 2) + Math.pow(a.m13, 2) + Math.pow(a.m14, 2) + Math.pow(a.m15, 2))); + public static frob (a) { + return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2) + + Math.pow(a.m09, 2) + Math.pow(a.m10, 2) + Math.pow(a.m11, 2) + Math.pow(a.m12, 2) + Math.pow(a.m13, 2) + + Math.pow(a.m14, 2) + Math.pow(a.m15, 2))); } /** @@ -1438,7 +1502,7 @@ class mat4 { * @param b - The second operand. * @return out. */ - public static add(out, a, b) { + public static add (out, a, b) { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; @@ -1466,7 +1530,7 @@ class mat4 { * @param b - The second operand. * @return out. */ - public static subtract(out, a, b) { + public static subtract (out, a, b) { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; @@ -1489,7 +1553,7 @@ class mat4 { /** * Alias of {@link mat4.subtract}. */ - public static sub(out, a, b) { + public static sub (out, a, b) { return mat4.subtract(out, a, b); } @@ -1501,7 +1565,7 @@ class mat4 { * @param b - The scale number. * @return out. */ - public static multiplyScalar(out, a, b) { + public static multiplyScalar (out, a, b) { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; @@ -1530,7 +1594,7 @@ class mat4 { * @param scale - The scale number. * @return out. */ - public static multiplyScalarAndAdd(out, a, b, scale) { + public static multiplyScalarAndAdd (out, a, b, scale) { out.m00 = a.m00 + (b.m00 * scale); out.m01 = a.m01 + (b.m01 * scale); out.m02 = a.m02 + (b.m02 * scale); @@ -1557,7 +1621,7 @@ class mat4 { * @param b - The second matrix. * @return True if the matrices are equal, false otherwise. */ - public static exactEquals(a, b) { + public static exactEquals (a, b) { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && @@ -1571,7 +1635,7 @@ class mat4 { * @param b - The second matrix. * @return True if the matrices are equal, false otherwise. */ - public static equals(a, b) { + public static equals (a, b) { const a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, a8 = a.m08, a9 = a.m09, a10 = a.m10, a11 = a.m11, @@ -1601,6 +1665,24 @@ class mat4 { Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)) ); } + + public m00: number = 1; + public m01: number = 0; + public m02: number = 0; + public m03: number = 0; + public m04: number = 0; + public m05: number = 1; + public m06: number = 0; + public m07: number = 0; + public m08: number = 0; + public m09: number = 0; + public m10: number = 1; + public m11: number = 0; + public m12: number = 0; + public m13: number = 0; + public m14: number = 0; + public m15: number = 1; + /** * Creates a matrix, with elements specified separately. * @@ -1621,7 +1703,7 @@ class mat4 { * @param m14 - Value assigned to element at column 3 row 2. * @param m15 - Value assigned to element at column 3 row 3. */ - constructor( + constructor ( m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 0, m05 = 1, m06 = 0, m07 = 0, m08 = 0, m09 = 0, m10 = 1, m11 = 0, @@ -1630,97 +1712,97 @@ class mat4 { /** * The element at column 0 row 0. * @type {number} - * */ + */ this.m00 = m00; /** * The element at column 0 row 1. * @type {number} - * */ + */ this.m01 = m01; /** * The element at column 0 row 2. * @type {number} - * */ + */ this.m02 = m02; /** * The element at column 0 row 3. * @type {number} - * */ + */ this.m03 = m03; /** * The element at column 1 row 0. * @type {number} - * */ + */ this.m04 = m04; /** * The element at column 1 row 1. * @type {number} - * */ + */ this.m05 = m05; /** * The element at column 1 row 2. * @type {number} - * */ + */ this.m06 = m06; /** * The element at column 1 row 3. * @type {number} - * */ + */ this.m07 = m07; /** * The element at column 2 row 0. * @type {number} - * */ + */ this.m08 = m08; /** * The element at column 2 row 1. * @type {number} - * */ + */ this.m09 = m09; /** * The element at column 2 row 2. * @type {number} - * */ + */ this.m10 = m10; /** * The element at column 2 row 3. * @type {number} - * */ + */ this.m11 = m11; /** * The element at column 3 row 0. * @type {number} - * */ + */ this.m12 = m12; /** * The element at column 3 row 1. * @type {number} - * */ + */ this.m13 = m13; /** * The element at column 3 row 2. * @type {number} - * */ + */ this.m14 = m14; /** * The element at column 3 row 3. * @type {number} - * */ + */ this.m15 = m15; } } diff --git a/cocos/core/vmath/quat.ts b/cocos/core/vmath/quat.ts index 0fcc1d0e0a..3bf3dce712 100644 --- a/cocos/core/vmath/quat.ts +++ b/cocos/core/vmath/quat.ts @@ -14,6 +14,7 @@ const halfToRad = 0.5 * Math.PI / 180.0; * x, y, z and w are real numbers(called here its components), and i, j, and k are the fundamental quaternion units. */ export default class quat { + public static IDENTITY = new quat(); /** * Creates a quaternion, with components specified separately. @@ -24,7 +25,7 @@ export default class quat { * @param w - Value assigned to w component. * @return The newly created quaternion. */ - public static create (x = 0, y = 0, z = 0, w = 1) { + public static create(x = 0, y = 0, z = 0, w = 1) { return new quat(x, y, z, w); } @@ -34,7 +35,7 @@ export default class quat { * @param a - Quaternion to clone. * @return The newly created quaternion. */ - public static clone (a: quat) { + public static clone(a: quat) { return new quat(a.x, a.y, a.z, a.w); } @@ -45,7 +46,7 @@ export default class quat { * @param a - The specified quaternion. * @return out. */ - public static copy (out: Out, a: quat) { + public static copy(out: Out, a: quat) { return vec4.copy(out, a); } @@ -59,7 +60,7 @@ export default class quat { * @param w - Value set to w component. * @return out. */ - public static set (out: Out, x: number, y: number, z: number, w: number) { + public static set(out: Out, x: number, y: number, z: number, w: number) { out.x = x; out.y = y; out.z = z; @@ -92,7 +93,7 @@ export default class quat { * @param b - The destination vector. * @return out. */ - public static rotationTo (out: Out, a: quat, b: quat) { + public static rotationTo(out: Out, a: vec3, b: vec3) { const dot = vec3.dot(a, b); if (dot < -0.999999) { vec3.cross(tmpVec3, tmpXUnitVec3, a); @@ -131,7 +132,7 @@ export default class quat { * @param {quat} q - Quaternion to be decomposed. * @return - Angle, in radians, of the rotation. */ - public static getAxisAngle (outAxis: Out, q: quat) { + public static getAxisAngle(outAxis: Out, q: quat) { const rad = Math.acos(q.w) * 2.0; const s = Math.sin(rad / 2.0); if (s !== 0.0) { @@ -155,7 +156,7 @@ export default class quat { * @param b - The second operand. * @return out. */ - public static multiply (out: Out, a: quat, b: quat) { + public static multiply(out: Out, a: quat, b: quat) { const { x: ax, y: ay, z: az, w: aw } = a; const { x: bx, y: by, z: bz, w: bw } = b; @@ -169,7 +170,7 @@ export default class quat { /** * Alias of {@link quat.multiply}. */ - public static mul (out: Out, a: quat, b: quat) { + public static mul(out: Out, a: quat, b: quat) { return quat.multiply(out, a, b); } @@ -181,7 +182,7 @@ export default class quat { * @param b - The scale number. * @return out. */ - public static scale (out: Out, a: quat, b: number) { + public static scale(out: Out, a: quat, b: number) { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; @@ -197,7 +198,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateX (out: Out, a: quat, rad: number) { + public static rotateX(out: Out, a: quat, rad: number) { rad *= 0.5; const { x: ax, y: ay, z: az, w: aw } = a; @@ -219,7 +220,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateY (out: Out, a: quat, rad: number) { + public static rotateY(out: Out, a: quat, rad: number) { rad *= 0.5; const { x: ax, y: ay, z: az, w: aw } = a; @@ -241,7 +242,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateZ (out: Out, a: quat, rad: number) { + public static rotateZ(out: Out, a: quat, rad: number) { rad *= 0.5; const { x: ax, y: ay, z: az, w: aw } = a; @@ -264,7 +265,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateAround (out: Out, rot: quat, axis: IVec3Like, rad: number) { + public static rotateAround(out: Out, rot: quat, axis: IVec3Like, rad: number) { // get inv-axis (local to rot) quat.invert(tmpQuat1, rot); vec3.transformQuat(tmpVec3, axis, tmpQuat1); @@ -283,7 +284,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateAroundLocal (out: Out, rot: quat, axis: IVec3Like, rad: number) { + public static rotateAroundLocal(out: Out, rot: quat, axis: IVec3Like, rad: number) { quat.fromAxisAngle(tmpQuat1, axis, rad); quat.mul(out, rot, tmpQuat1); return out; @@ -298,7 +299,7 @@ export default class quat { * @param a - Quaternion to calculate W. * @return out. */ - public static calculateW (out: Out, a: quat) { + public static calculateW(out: Out, a: quat) { const { x, y, z } = a; out.x = x; @@ -315,7 +316,7 @@ export default class quat { * @param b - The second operand. * @return - The dot product of a and b. */ - public static dot (a: quat, b: quat) { + public static dot(a: quat, b: quat) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } @@ -328,7 +329,7 @@ export default class quat { * @param t - The interpolation coefficient. * @return out. */ - public static lerp (out: Out, a: quat, b: quat, t: number) { + public static lerp(out: Out, a: quat, b: quat, t: number) { const { x: ax, y: ay, z: az, w: aw } = a; out.x = ax + t * (b.x - ax); out.y = ay + t * (b.y - ay); @@ -346,7 +347,7 @@ export default class quat { * @param t - The interpolation coefficient. * @return out. */ - public static slerp (out: Out, a: quat, b: quat, t: number) { + public static slerp(out: Out, a: quat, b: quat, t: number) { // benchmarks: // http://jsperf.com/quaternion-slerp-implementations @@ -399,7 +400,7 @@ export default class quat { * @param t - The interpolation coefficient. * @return out */ - public static sqlerp (out: Out, a: quat, b: quat, c: quat, d: quat, t: number) { + public static sqlerp(out: Out, a: quat, b: quat, c: quat, d: quat, t: number) { quat.slerp(tmpQuat1, a, d, t); quat.slerp(tmpQuat2, b, c, t); quat.slerp(out, tmpQuat1, tmpQuat2, 2 * t * (1 - t)); @@ -413,7 +414,7 @@ export default class quat { * @param a - Quaternion to calculate inverse of. * @return out. */ - public static invert (out: Out, a: quat) { + public static invert(out: Out, a: quat) { const { x: a0, y: a1, z: a2, w: a3 } = a; const dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; const invDot = dot ? 1.0 / dot : 0; @@ -435,7 +436,7 @@ export default class quat { * @param a - Quaternion to calculate conjugate of. * @return out. */ - public static conjugate (out: Out, a: quat) { + public static conjugate(out: Out, a: quat) { out.x = -a.x; out.y = -a.y; out.z = -a.z; @@ -449,7 +450,7 @@ export default class quat { * @param a - The quaternion. * @return Length of the quaternion. */ - public static magnitude (a: quat) { + public static magnitude(a: quat) { const { x, y, z, w } = a; return Math.sqrt(x * x + y * y + z * z + w * w); } @@ -457,7 +458,7 @@ export default class quat { /** * Alias of {@link quat.magnitude}. */ - public static mag (a: quat) { + public static mag(a: quat) { return quat.magnitude(a); } @@ -467,7 +468,7 @@ export default class quat { * @param a - The quaternion. * @return Squared length of the quaternion. */ - public static squaredMagnitude (a: quat) { + public static squaredMagnitude(a: quat) { const { x, y, z, w } = a; return x * x + y * y + z * z + w * w; } @@ -475,7 +476,7 @@ export default class quat { /** * Alias of {@link quat.squaredMagnitude} */ - public static sqrMag (a: quat) { + public static sqrMag(a: quat) { return quat.squaredMagnitude(a); } @@ -487,7 +488,7 @@ export default class quat { * @return out. * @function */ - public static normalize (out: Out, a: quat) { + public static normalize(out: Out, a: quat) { const { x, y, z, w } = a; let len = x * x + y * y + z * z + w * w; if (len > 0) { @@ -511,7 +512,7 @@ export default class quat { * @param zAxis - Vector representing the viewing direction. * @return out. */ - public static fromAxes (out: Out, xAxis: IVec3Like, yAxis: IVec3Like, zAxis: IVec3Like) { + public static fromAxes(out: Out, xAxis: IVec3Like, yAxis: IVec3Like, zAxis: IVec3Like) { mat3.set(tmpMat3, xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, @@ -529,7 +530,7 @@ export default class quat { * * @return out. */ - public static fromViewUp (out: Out, view: IVec3Like, up: IVec3Like) { + public static fromViewUp(out: Out, view: IVec3Like, up: IVec3Like) { mat3.fromViewUp(tmpMat3, view, up); return quat.normalize(out, quat.fromMat3(out, tmpMat3)); } @@ -543,7 +544,7 @@ export default class quat { * @param rad - The angle in radians. * @return out. */ - public static fromAxisAngle (out: Out, axis: IVec3Like, rad: number) { + public static fromAxisAngle(out: Out, axis: IVec3Like, rad: number) { rad = rad * 0.5; const s = Math.sin(rad); out.x = s * axis.x; @@ -564,7 +565,7 @@ export default class quat { * @return out. * @function */ - public static fromMat3 (out: Out, m: IMat3Like) { + public static fromMat3(out: Out, m: IMat3Like) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm const { @@ -621,7 +622,7 @@ export default class quat { * @return out. * @function */ - public static fromEuler (out: Out, x: number, y: number, z: number) { + public static fromEuler(out: Out, x: number, y: number, z: number) { x *= halfToRad; y *= halfToRad; z *= halfToRad; @@ -641,6 +642,53 @@ export default class quat { return out; } + /** + * Returns the X orthonormal axis defining the quaternion. + * + * @param out - X axis. + * @param q - The quaternion. + * @function + */ + public static toAxisX(out: vec3, q: quat) { + let fy = 2.0 * q.y; + let fz = 2.0 * q.z; + out.x = 1.0 - fy * q.y - fz * q.z; + out.y = fy * q.x + fz * q.w; + out.z = fz * q.x + fy * q.w; + } + + /** + * Returns the Y orthonormal axis defining the quaternion. + * + * @param out - Y axis. + * @param q - The quaternion. + * @function + */ + public static toAxisY(out: vec3, q: quat) { + let fx = 2.0 * q.x; + let fy = 2.0 * q.y; + let fz = 2.0 * q.z; + out.x = fy * q.x - fz * q.w; + out.y = 1.0 - fx * q.x - fz * q.z; + out.z = fz * q.y + fx * q.w; + } + + /** + * Returns the Z orthonormal axis defining the quaternion. + * + * @param out - Z axis. + * @param q - The quaternion. + * @function + */ + public static toAxisZ(out: vec3, q: quat) { + let fx = 2.0 * q.x; + let fy = 2.0 * q.y; + let fz = 2.0 * q.z; + out.x = fz * q.x - fy * q.w; + out.y = fz * q.y - fx * q.w; + out.z = 1.0 - fx * q.x - fy * q.y; + } + /** * Convert a quaternion back to euler angle (in degrees). * @@ -648,7 +696,7 @@ export default class quat { * @param q - the quaternion to be converted * @return out. */ - public static toEuler (out: Out, q: quat) { + public static toEuler(out: Out, q: quat) { const { x, y, z, w } = q; let heading: number = NaN; let attitude: number = NaN; @@ -687,7 +735,7 @@ export default class quat { * @param a - The quaternion. * @return - String representation of this quaternion. */ - public static str (a: quat) { + public static str(a: quat) { return `quat(${a.x}, ${a.y}, ${a.z}, ${a.w})`; } @@ -698,7 +746,7 @@ export default class quat { * @param q - The quaternion. * @return out. */ - public static array> (out: Out, q: quat) { + public static array>(out: Out, q: quat) { out[0] = q.x; out[1] = q.y; out[2] = q.z; @@ -714,7 +762,7 @@ export default class quat { * @param b - The second quaternion. * @return True if the quaternions are equal, false otherwise. */ - public static exactEquals (a: quat, b: quat) { + public static exactEquals(a: quat, b: quat) { return vec4.exactEquals(a, b); } @@ -725,7 +773,7 @@ export default class quat { * @param b The second quaternion. * @return True if the quaternions are approximately equal, false otherwise. */ - public static equals (a: quat, b: quat) { + public static equals(a: quat, b: quat) { return vec4.equals(a, b); } @@ -757,7 +805,7 @@ export default class quat { * @param z - Value assigned to z component. * @param w - Value assigned to w component. */ - constructor (x = 0, y = 0, z = 0, w = 1) { + constructor(x = 0, y = 0, z = 0, w = 1) { this.x = x; this.y = y; this.z = z; diff --git a/cocos/core/vmath/rect.ts b/cocos/core/vmath/rect.ts new file mode 100644 index 0000000000..1c230111e3 --- /dev/null +++ b/cocos/core/vmath/rect.ts @@ -0,0 +1,22 @@ + +export interface IRect2D { + x?: number; + y?: number; + width?: number; + height?: number; +} + +export interface INormalizedRect2D { + x: number; + y: number; + width: number; + height: number; +} + +export function normalizeRect2D (rect: IRect2D, fullWidth: number, fullHeight: number): INormalizedRect2D { + rect.x = rect.x || 0; + rect.y = rect.y || 0; + rect.width = rect.width || fullWidth; + rect.height = rect.height || fullHeight; + return rect as INormalizedRect2D; +} diff --git a/cocos/core/vmath/vec2.ts b/cocos/core/vmath/vec2.ts index 4069876766..ffe65ac5cb 100644 --- a/cocos/core/vmath/vec2.ts +++ b/cocos/core/vmath/vec2.ts @@ -8,6 +8,9 @@ import { EPSILON, random } from './utils'; * x, y is alias of the first, second component of vector, respectively. */ export default class vec2 { + public static ZERO = new vec2(0, 0); + public static ONE = new vec2(1, 1); + public static NEG_ONE = new vec2(-1, -1); /** * Creates a vector, with components specified separately. @@ -542,9 +545,9 @@ export default class vec2 { * @param v - The vector. * @return out. */ - public static array> (out: Out, v: vec2) { - out[0] = v.x; - out[1] = v.y; + public static array> (out: Out, v: vec2, ofs = 0) { + out[ofs + 0] = v.x; + out[ofs + 1] = v.y; return out; } diff --git a/cocos/core/vmath/vec3.ts b/cocos/core/vmath/vec3.ts index 83dc826ed5..4e7e320504 100644 --- a/cocos/core/vmath/vec3.ts +++ b/cocos/core/vmath/vec3.ts @@ -8,6 +8,13 @@ import { EPSILON, random } from './utils'; * x, y, z is alias of the first, second, third component of vector, respectively. */ export default class vec3 { + public static UNIT_X = new vec3(1, 0, 0); + public static UNIT_Y = new vec3(0, 1, 0); + public static UNIT_Z = new vec3(0, 0, 1); + public static ZERO = new vec3(0, 0, 0); + public static ONE = new vec3(1, 1, 1); + public static NEG_ONE = new vec3(-1, -1, -1); + /** * Creates a vector, with components specified separately. * @@ -730,10 +737,10 @@ export default class vec3 { * @param v - The vector. * @return out. */ - public static array> (out: Out, v: vec3) { - out[0] = v.x; - out[1] = v.y; - out[2] = v.z; + public static array> (out: Out, v: vec3, ofs = 0) { + out[ofs + 0] = v.x; + out[ofs + 1] = v.y; + out[ofs + 2] = v.z; return out; } diff --git a/cocos/core/vmath/vec4.ts b/cocos/core/vmath/vec4.ts index f69969bd2b..c941721d64 100644 --- a/cocos/core/vmath/vec4.ts +++ b/cocos/core/vmath/vec4.ts @@ -8,6 +8,9 @@ import { EPSILON, random } from './utils'; * x, y, z, w is alias of the first, second, third, fourth component of vector, respectively. */ export default class vec4 { + public static ZERO = new vec4(0, 0, 0, 0); + public static ONE = new vec4(1, 1, 1, 1); + public static NEG_ONE = new vec4(-1, -1, -1, -1); /** * Create a vector, with components specified separately. @@ -567,11 +570,11 @@ export default class vec4 { * @param v - The vector. * @return out. */ - public static array> (out: Out, v: vec4) { - out[0] = v.x; - out[1] = v.y; - out[2] = v.z; - out[3] = v.w; + public static array> (out: Out, v: vec4, ofs = 0) { + out[ofs + 0] = v.x; + out[ofs + 1] = v.y; + out[ofs + 2] = v.z; + out[ofs + 3] = v.w; return out; } diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts new file mode 100644 index 0000000000..d922b4fe2a --- /dev/null +++ b/cocos/gfx/binding-layout.ts @@ -0,0 +1,97 @@ +import { GFXBuffer } from './buffer'; +import { GFXBindingType, GFXObject, GFXObjectType } from './define'; +import { GFXDevice } from './device'; +import { GFXSampler } from './sampler'; +import { GFXTextureView } from './texture-view'; + +export interface IGFXBinding { + binding: number; + type: GFXBindingType; + name: string; +} + +export interface IGFXBindingLayoutInfo { + bindings: IGFXBinding[]; +} + +export class GFXBindingUnit { + public binding: number = 0; + public type: GFXBindingType = GFXBindingType.UNKNOWN; + public name: string = ''; + public buffer: GFXBuffer | null = null; + public texView: GFXTextureView | null = null; + public sampler: GFXSampler | null = null; +} + +export abstract class GFXBindingLayout extends GFXObject { + + protected _device: GFXDevice; + protected _bindingUnits: GFXBindingUnit[] = []; + protected _isDirty = false; + + constructor (device: GFXDevice) { + super(GFXObjectType.BINDING_LAYOUT); + this._device = device; + } + + public abstract initialize (info: IGFXBindingLayoutInfo): boolean; + public abstract destroy (); + public abstract update (); + + public bindBuffer (binding: number, buffer: GFXBuffer) { + for (const bindingUnit of this._bindingUnits) { + if (bindingUnit.binding === binding) { + if (bindingUnit.type === GFXBindingType.UNIFORM_BUFFER) { + if (bindingUnit.buffer !== buffer) { + bindingUnit.buffer = buffer; + this._isDirty = true; + } + } else { + console.error('Setting binding is not GFXBindingType.UNIFORM_BUFFER.'); + } + return; + } + } + } + + public bindSampler (binding: number, sampler: GFXSampler) { + for (const bindingUnit of this._bindingUnits) { + if (bindingUnit.binding === binding) { + if (bindingUnit.type === GFXBindingType.SAMPLER) { + if (bindingUnit.sampler !== sampler) { + bindingUnit.sampler = sampler; + this._isDirty = true; + } + } else { + console.error('Setting binding is not GFXBindingType.SAMPLER.'); + } + return; + } + } + } + + public bindTextureView (binding: number, texView: GFXTextureView) { + for (const bindingUnit of this._bindingUnits) { + if (bindingUnit.binding === binding) { + if (bindingUnit.type === GFXBindingType.SAMPLER) { + if (bindingUnit.texView !== texView) { + bindingUnit.texView = texView; + this._isDirty = true; + } + } else { + console.error('Setting binding is not GFXBindingType.SAMPLER.'); + } + return; + } + } + } + + public getBindingUnit (binding: number): GFXBindingUnit | null { + for (const unit of this._bindingUnits) { + if (unit.binding === binding) { + return unit; + } + } + return null; + } +} diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts new file mode 100644 index 0000000000..13fcec273b --- /dev/null +++ b/cocos/gfx/buffer.ts @@ -0,0 +1,87 @@ +import { + GFXBufferUsage, + GFXBufferUsageBit, + GFXMemoryUsage, + GFXMemoryUsageBit, + GFXObject, + GFXObjectType, + GFXType, +} from './define'; +import { GFXDevice } from './device'; + +export interface IGFXUniformInfo { + name: string; + type: GFXType; + count: number; +} + +export interface IGFXDrawInfo { + vertexCount: number; + firstVertex: number; + indexCount: number; + firstIndex: number; + vertexOffset: number; + instanceCount: number; + firstInstance: number; +} + +export const GFX_DRAW_INFO_SIZE: number = 56; + +export interface IGFXIndirectBuffer { + drawInfos: IGFXDrawInfo[]; +} + +export type GFXBufferSource = ArrayBuffer | IGFXIndirectBuffer; + +export interface IGFXBufferInfo { + usage: GFXBufferUsage; + memUsage: GFXMemoryUsage; + size: number; + stride?: number; +} + +export abstract class GFXBuffer extends GFXObject { + + public get usage (): GFXBufferUsage { + return this._usage; + } + + public get memUsage (): GFXMemoryUsage { + return this._memUsage; + } + + public get size (): number { + return this._size; + } + + public get stride (): number { + return this._stride; + } + + public get count (): number { + return this._count; + } + + public get buffer (): GFXBufferSource | null { + return this._buffer; + } + + protected _device: GFXDevice; + protected _usage: GFXBufferUsage = GFXBufferUsageBit.NONE; + protected _memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; + protected _size: number = 0; + protected _stride: number = 1; + protected _count: number = 0; + protected _buffer: GFXBufferSource | null = null; + protected _uniforms: GFXBufferSource | null = null; + + constructor (device: GFXDevice) { + super(GFXObjectType.BUFFER); + this._device = device; + } + + public abstract initialize (info: IGFXBufferInfo): boolean; + public abstract destroy (): void; + public abstract resize (size: number); + public abstract update (buffer: GFXBufferSource, offset?: number, size?: number); +} diff --git a/cocos/gfx/command-allocator.ts b/cocos/gfx/command-allocator.ts new file mode 100644 index 0000000000..6bcc133239 --- /dev/null +++ b/cocos/gfx/command-allocator.ts @@ -0,0 +1,19 @@ +import { GFXObject, GFXObjectType } from './define'; +import { GFXDevice } from './device'; + +// tslint:disable-next-line:no-empty-interface +export interface IGFXCommandAllocatorInfo { +} + +export abstract class GFXCommandAllocator extends GFXObject { + + protected _device: GFXDevice; + + constructor (device: GFXDevice) { + super(GFXObjectType.COMMAND_ALLOCATOR); + this._device = device; + } + + public abstract initialize (info: IGFXCommandAllocatorInfo): boolean; + public abstract destroy (); +} diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts new file mode 100644 index 0000000000..717941c52f --- /dev/null +++ b/cocos/gfx/command-buffer.ts @@ -0,0 +1,64 @@ +import { GFXBindingLayout } from './binding-layout'; +import { GFXBuffer } from './buffer'; +import { GFXCommandAllocator } from './command-allocator'; +import { + GFXBufferTextureCopy, + GFXCommandBufferType, + GFXObject, + GFXObjectType, + GFXStencilFace, + GFXTextureLayout, + IGFXColor, + IGFXRect, + IGFXViewport, +} from './define'; +import { GFXDevice } from './device'; +import { GFXFramebuffer } from './framebuffer'; +import { GFXInputAssembler } from './input-assembler'; +import { GFXPipelineState } from './pipeline-state'; +import { GFXTexture } from './texture'; + +export interface IGFXCommandBufferInfo { + allocator: GFXCommandAllocator; + type: GFXCommandBufferType; +} + +// tslint:disable: max-line-length +export abstract class GFXCommandBuffer extends GFXObject { + + public get type (): number { + return this._type; + } + + protected _device: GFXDevice; + protected _allocator: GFXCommandAllocator | null = null; + protected _type: GFXCommandBufferType = GFXCommandBufferType.PRIMARY; + + constructor (device: GFXDevice) { + super(GFXObjectType.COMMAND_BUFFER); + this._device = device; + } + + public abstract initialize (info: IGFXCommandBufferInfo): boolean; + public abstract destroy (); + + public abstract begin (); + public abstract end (); + public abstract beginRenderPass (framebuffer: GFXFramebuffer, renderArea: IGFXRect, clearColors: IGFXColor[], clearDepth: number, clearStencil: number); + public abstract endRenderPass (); + public abstract bindPipelineState (pipelineState: GFXPipelineState); + public abstract bindBindingLayout (bindingLayout: GFXBindingLayout); + public abstract bindInputAssembler (inputAssembler: GFXInputAssembler); + public abstract setViewport (viewport: IGFXViewport); + public abstract setScissor (scissor: IGFXRect); + public abstract setLineWidth (lineWidth: number); + public abstract setDepthBias (depthBiasConstantFacotr: number, depthBiasClamp: number, depthBiasSlopeFactor: number); + public abstract setBlendConstants (blendConstants: number[]); + public abstract setDepthBound (minDepthBounds: number, maxDepthBounds: number); + public abstract setStencilWirteMask (faceMask: GFXStencilFace, writeMask: number); + public abstract setStencilCompareMask (face: GFXStencilFace, reference: number, compareMask: number); + public abstract draw (inputAssembler: GFXInputAssembler); + public abstract updateBuffer (buffer: GFXBuffer, data: ArrayBuffer, offset?: number); + public abstract copyBufferToTexture (srcBuff: GFXBuffer, dstTex: GFXTexture, dstLayout: GFXTextureLayout, regions: GFXBufferTextureCopy[]); + public abstract execute (cmdBuffs: GFXCommandBuffer[], count: number); +} diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts new file mode 100644 index 0000000000..6b2831282b --- /dev/null +++ b/cocos/gfx/define.ts @@ -0,0 +1,793 @@ +// Extensions +export enum WebGLEXT { + COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0, + COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1, + COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2, + COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3, + + COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C, + COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8C4D, + COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8C4E, + COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8C4F, + + COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00, + COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01, + COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02, + COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03, + + COMPRESSED_RGB_ETC1_WEBGL = 0x8D64, +} + +export const GFX_MAX_VERTEX_ATTRIBUTES: number = 16; +export const GFX_MAX_TEXTURE_UNITS: number = 16; +export const GFX_MAX_ATTACHMENTS: number = 4; + +export enum GFXObjectType { + UNKNOWN, + BUFFER, + TEXTURE, + TEXTURE_VIEW, + RENDER_PASS, + FRAMEBUFFER, + SAMPLER, + SHADER, + PIPELINE_LAYOUT, + PIPELINE_STATE, + BINDING_LAYOUT, + INPUT_ASSEMBLER, + COMMAND_ALLOCATOR, + COMMAND_BUFFER, + QUEUE, + WINDOW, +} + +export enum GFXStatus { + UNREADY, + FAILED, + SUCCESS, +} + +export class GFXObject { + + public get gfxType (): GFXObjectType { + return this._gfxType; + } + + public get status (): GFXStatus { + return this._status; + } + + protected _gfxType = GFXObjectType.UNKNOWN; + protected _status = GFXStatus.UNREADY; + + constructor (gfxType: GFXObjectType) { + this._gfxType = gfxType; + } +} + +export enum GFXAttributeName { + ATTR_POSITION = 'a_position', + ATTR_NORMAL = 'a_normal', + ATTR_TANGENT = 'a_tangent', + ATTR_BITANGENT = 'a_bitangent', + ATTR_WEIGHTS = 'a_weights', + ATTR_JOINTS = 'a_joints', + ATTR_COLOR = 'a_color', + ATTR_COLOR1 = 'a_color1', + ATTR_COLOR2 = 'a_color2', + ATTR_TEX_COORD = 'a_texCoord', + ATTR_TEX_COORD1 = 'a_texCoord1', + ATTR_TEX_COORD2 = 'a_texCoord2', + ATTR_TEX_COORD3 = 'a_texCoord3', + ATTR_TEX_COORD4 = 'a_texCoord4', + ATTR_TEX_COORD5 = 'a_texCoord5', + ATTR_TEX_COORD6 = 'a_texCoord6', + ATTR_TEX_COORD7 = 'a_texCoord7', + ATTR_TEX_COORD8 = 'a_texCoord8', +} + +export enum GFXType { + UNKNOWN, + BOOL, + BOOL2, + BOOL3, + BOOL4, + INT, + INT2, + INT3, + INT4, + UINT, + UINT2, + UINT3, + UINT4, + FLOAT, + FLOAT2, + FLOAT3, + FLOAT4, + COLOR4, + MAT2, + MAT2X3, + MAT2X4, + MAT3X2, + MAT3, + MAT3X4, + MAT4X2, + MAT4X3, + MAT4, + SAMPLER1D, + SAMPLER1D_ARRAY, + SAMPLER2D, + SAMPLER2D_ARRAY, + SAMPLER3D, + SAMPLER_CUBE, + COUNT, +} + +export enum GFXFormat { + + UNKNOWN, + + A8, + L8, + LA8, + + R8, + R8SN, + R8UI, + R8I, + R16F, + R16UI, + R16I, + R32F, + R32UI, + R32I, + + RG8, + RG8SN, + RG8UI, + RG8I, + RG16F, + RG16UI, + RG16I, + RG32F, + RG32UI, + RG32I, + + RGB8, + SRGB8, + RGB8SN, + RGB8UI, + RGB8I, + RGB16F, + RGB16UI, + RGB16I, + RGB32F, + RGB32UI, + RGB32I, + + RGBA8, + SRGB8_A8, + RGBA8SN, + RGBA8UI, + RGBA8I, + RGBA16F, + RGBA16UI, + RGBA16I, + RGBA32F, + RGBA32UI, + RGBA32I, + + // Special Format + R5G6B5, + R11G11B10F, + RGB5A1, + RGBA4, + RGB10A2, + RGB10A2UI, + RGB9E5, + + // Depth-Stencil Format + D16, + D16S8, + D24, + D24S8, + D32F, + D32F_S8, + + // Compressed Format + + // Block Compression Format, DDS (DirectDraw Surface) + // DXT1: 3 channels (5:6:5), 1/8 origianl size, with 0 or 1 bit of alpha + BC1, + BC1_ALPHA, + BC1_SRGB, + BC1_SRGB_ALPHA, + // DXT3: 4 channels (5:6:5), 1/4 origianl size, with 4 bits of alpha + BC2, + BC2_SRGB, + // DXT5: 4 channels (5:6:5), 1/4 origianl size, with 8 bits of alpha + BC3, + BC3_SRGB, + // 1 channel (8), 1/4 origianl size + BC4, + BC4_SNORM, + // 2 channels (8:8), 1/2 origianl size + BC5, + BC5_SNORM, + // 3 channels (16:16:16), half-floating point, 1/6 origianl size + // UF16: unsigned float, 5 exponent bits + 11 mantissa bits + // SF16: signed float, 1 signed bit + 5 exponent bits + 10 mantissa bits + BC6H_UF16, + BC6H_SF16, + // 4 channels (4~7 bits per channel) with 0 to 8 bits of alpha, 1/3 original size + BC7, + BC7_SRGB, + + // Ericsson Texture Compression Format + ETC_RGB8, + ETC2_RGB8, + ETC2_SRGB8, + ETC2_RGB8_A1, + ETC2_SRGB8_A1, + ETC2_RGBA8, + ETC2_SRGB8_A8, + EAC_R11, + EAC_R11SN, + EAC_RG11, + EAC_RG11SN, + + // PVRTC (PowerVR) + PVRTC_RGB2, + PVRTC_RGBA2, + PVRTC_RGB4, + PVRTC_RGBA4, + PVRTC2_2BPP, + PVRTC2_4BPP, +} + +export enum GFXBufferUsageBit { + NONE = 0, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + INDEX = 0x4, + VERTEX = 0x8, + UNIFORM = 0x10, + STORAGE = 0x20, + INDIRECT = 0x40, +} + +export type GFXBufferUsage = GFXBufferUsageBit; + +export enum GFXMemoryUsageBit { + NONE = 0, + DEVICE = 0x1, + HOST = 0x2, +} + +export type GFXMemoryUsage = GFXMemoryUsageBit; + +export enum GFXBufferAccessBit { + NONE = 0, + READ = 0x1, + WRITE = 0x2, +} + +export type GFXBufferAccess = GFXBufferAccessBit; + +export enum GFXPrimitiveMode { + POINT_LIST, + LINE_LIST, + LINE_STRIP, + LINE_LOOP, + LINE_LIST_ADJACENCY, + LINE_STRIP_ADJACENCY, + ISO_LINE_LIST, + // raycast detectable: + TRIANGLE_LIST, + TRIANGLE_STRIP, + TRIANGLE_FAN, + TRIANGLE_LIST_ADJACENCY, + TRIANGLE_STRIP_ADJACENCY, + TRIANGLE_PATCH_ADJACENCY, + QUAD_PATCH_LIST, +} + +export enum GFXPolygonMode { + FILL, + POINT, + LINE, +} + +export enum GFXShadeModel { + GOURAND, + FLAT, +} + +export enum GFXCullMode { + NONE, + FRONT, + BACK, +} + +export enum GFXComparisonFunc { + NEVER, + LESS, + EQUAL, + LESS_EQUAL, + GREATER, + NOT_EQUAL, + GREATER_EQUAL, + ALWAYS, +} + +export enum GFXStencilOp { + ZERO, + KEEP, + REPLACE, + INCR, + DECR, + INVERT, + INCR_WRAP, + DECR_WRAP, +} + +export enum GFXBlendOp { + ADD, + SUB, + REV_SUB, + MIN, + MAX, +} + +export enum GFXBlendFactor { + ZERO, + ONE, + SRC_ALPHA, + DST_ALPHA, + ONE_MINUS_SRC_ALPHA, + ONE_MINUS_DST_ALPHA, + SRC_COLOR, + DST_COLOR, + ONE_MINUS_SRC_COLOR, + ONE_MINUS_DST_COLOR, + SRC_ALPHA_SATURATE, + CONSTANT_COLOR, + ONE_MINUS_CONSTANT_COLOR, + CONSTANT_ALPHA, + ONE_MINUS_CONSTANT_ALPHA, +} + +export enum GFXColorMask { + NONE = 0x0, + R = 0x1, + G = 0x2, + B = 0x4, + A = 0x8, + ALL = R | G | B | A, +} + +export enum GFXFilter { + NONE, + POINT, + LINEAR, + ANISOTROPIC, +} + +export enum GFXAddress { + WRAP, + MIRROR, + CLAMP, + BORDER, +} + +export enum GFXTextureType { + TEX1D, + TEX2D, + TEX3D, +} + +export enum GFXTextureUsageBit { + NONE = 0, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + SAMPLED = 0x4, + STORAGE = 0x8, + COLOR_ATTACHMENT = 0x10, + DEPTH_STENCIL_ATTACHMENT = 0x20, + TRANSIENT_ATTACHMENT = 0x40, + INPUT_ATTACHMENT = 0x80, +} + +export type GFXTextureUsage = GFXTextureUsageBit; + +export enum GFXTextureFlagBit { + NONE = 0, + GEN_MIPMAP = 0x1, + CUBEMAP = 0x2, + BAKUP_BUFFER = 0x4, +} + +export type GFXTextureFlags = GFXTextureFlagBit; + +export enum GFXTextureViewType { + TV1D, + TV2D, + TV3D, + CUBE, + TV1D_ARRAY, + TV2D_ARRAY, +} + +export enum GFXShaderType { + VERTEX, + HULL, + DOMAIN, + GEOMETRY, + FRAGMENT, + COMPUTE, + COUNT, +} + +export enum GFXBindingType { + UNKNOWN, + UNIFORM_BUFFER, + SAMPLER, + STORAGE_BUFFER, +} + +export enum GFXCommandBufferType { + PRIMARY, + SECONDARY, +} + +// Enumeration all possible values of operations to be performed on initially Loading a Framebuffer Object. +export enum GFXLoadOp { + LOAD, // Load the contents from the fbo from previous + CLEAR, // Clear the fbo + DISCARD, // Ignore writing to the fbo and keep old data +} + +// Enumerates all possible values of operations to be performed when Storing to a Framebuffer Object. +export enum GFXStoreOp { + STORE, // Write the source to the destination + DISCARD, // Don't write the source to the destination +} + +export enum GFXTextureLayout { + UNDEFINED, + GENERAL, + COLOR_ATTACHMENT_OPTIMAL, + DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + DEPTH_STENCIL_READONLY_OPTIMAL, + SHADER_READONLY_OPTIMAL, + TRANSFER_SRC_OPTIMAL, + TRANSFER_DST_OPTIMAL, + PREINITIALIZED, + PRESENT_SRC, +} + +export enum GFXPipelineBindPoint { + GRAPHICS, + COMPUTE, + RAY_TRACING, +} + +export enum GFXDynamicState { + VIEWPORT, + SCISSOR, + LINE_WIDTH, + DEPTH_BIAS, + BLEND_CONSTANTS, + DEPTH_BOUNDS, + STENCIL_WRITE_MASK, + STENCIL_COMPARE_MASK, +} + +export enum GFXStencilFace { + FRONT, + BACK, + ALL, +} + +export enum GFXQueueType { + GRAPHICS, + COMPUTE, + TRANSFER, +} + +// Interfaces + +export interface IGFXRect { + x: number; + y: number; + width: number; + height: number; +} + +export interface IGFXViewport { + left: number; + top: number; + width: number; + height: number; + minDepth: number; + maxDepth: number; +} + +export interface IGFXColor { + r: number; + g: number; + b: number; + a: number; +} + +export enum GFXClearFlag { + NONE = 0, + COLOR = 1, + DEPTH = 2, + STENCIL = 4, + SKYBOX = 8, +} + +export interface IGFXOffset { + x: number; + y: number; + z: number; +} + +export interface IGFXExtent { + width: number; + height: number; + depth: number; +} + +export class GFXTextureSubres { + public baseMipLevel: number = 0; + public levelCount: number = 1; + public baseArrayLayer: number = 0; + public layerCount: number = 1; +} + +export class GFXTextureCopy { + public srcSubres: GFXTextureSubres = new GFXTextureSubres(); + public srcOffset: IGFXOffset = { x: 0, y: 0, z: 0 }; + public dstSubres: GFXTextureSubres = new GFXTextureSubres(); + public dstOffset: IGFXOffset = { x: 0, y: 0, z: 0 }; + public extent: IGFXExtent = { width: 0, height: 0, depth: 0 }; +} + +export class GFXBufferTextureCopy { + public buffOffset: number = 0; + public buffStride: number = 0; + public buffTexHeight: number = 0; + public texOffset: IGFXOffset = { x: 0, y: 0, z: 0 }; + public texExtent: IGFXExtent = { width: 0, height: 0, depth: 0 }; + public texSubres: GFXTextureSubres = new GFXTextureSubres(); +} + +export interface IGFXFormatInfo { + readonly name: string; + readonly size: number; + readonly count: number; + readonly isFloating: boolean; + readonly hasAlpha: boolean; + readonly hasDepth: boolean; + readonly hasStencil: boolean; + readonly isCompressed: boolean; +} + +// tslint:disable: max-line-length +export const GFXFormatInfos: IGFXFormatInfo[] = [ + + { name: 'UNKNOWN', size: 0, count: 0, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: 'A8', size: 1, count: 1, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'L8', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'LA8', size: 1, count: 2, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: 'R8', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R8SN', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R8UI', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R8I', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R16F', size: 2, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R16UI', size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R16I', size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R32F', size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R32UI', size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R32I', size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: 'RG8', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG8SN', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG8UI', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG8I', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG16F', size: 4, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG16UI', size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG16I', size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG32F', size: 8, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG32UI', size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG32I', size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: 'RGB8', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'SRGB8', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB8SN', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB8UI', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB8I', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB16F', size: 6, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB16UI', size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB16I', size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB32F', size: 12, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB32UI', size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB32I', size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: 'RGBA8', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'SRGB8_A8', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA8SN', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA8UI', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA8I', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA16F', size: 8, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA16UI', size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA16I', size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA32F', size: 16, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA32UI', size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA32I', size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: 'R5G6B5', size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R11G11B10F', size: 4, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB5A1', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA4', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB10A2', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB10A2UI', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB9E5', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: 'D16', size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: 'D16S8', size: 3, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + { name: 'D24', size: 3, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: 'D24S8', size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + { name: 'D32F', size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: 'D32FS8', size: 5, count: 2, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + + { name: 'BC1', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC1_ALPHA', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC1_SRGB', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC1_SRGB_ALPHA', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC2', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC2_SRGB', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC3', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC3_SRGB', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC4', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC4_SNORM', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC5', size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC5_SNORM', size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC6H_UF16', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC6H_SF16', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC7', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC7_SRGB', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + + { name: 'ETC_RGB8', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_RGB8', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_SRGB8', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_RGB8_A1', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_SRGB8_A1', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_RGBA8', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_SRGB8_A8', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_R11', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_R11SN', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_RG11', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_RG11SN', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + + { name: 'PVRTC_RGB2', size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC_RGBA2', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC_RGB4', size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC_RGBA4', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC2_2BPP', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC2_4BPP', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, +]; +// tslint:enable: max-line-length + +export function GFXFormatSize (format: GFXFormat, width: number, height: number, depth: number): number { + + if (!GFXFormatInfos[format].isCompressed) { + return (width * height * depth * GFXFormatInfos[format].size); + } else { + switch (format) { + case GFXFormat.BC1: + case GFXFormat.BC1_ALPHA: + case GFXFormat.BC1_SRGB: + case GFXFormat.BC1_SRGB_ALPHA: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case GFXFormat.BC2: + case GFXFormat.BC2_SRGB: + case GFXFormat.BC3: + case GFXFormat.BC3_SRGB: + case GFXFormat.BC4: + case GFXFormat.BC4_SNORM: + case GFXFormat.BC6H_SF16: + case GFXFormat.BC6H_UF16: + case GFXFormat.BC7: + case GFXFormat.BC7_SRGB: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case GFXFormat.BC5: + case GFXFormat.BC5_SNORM: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; + + case GFXFormat.ETC_RGB8: + case GFXFormat.ETC2_RGB8: + case GFXFormat.ETC2_SRGB8: + case GFXFormat.ETC2_RGB8_A1: + case GFXFormat.ETC2_SRGB8_A1: + case GFXFormat.EAC_R11: + case GFXFormat.EAC_R11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case GFXFormat.EAC_RG11: + case GFXFormat.EAC_RG11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + + case GFXFormat.PVRTC_RGB2: + case GFXFormat.PVRTC_RGBA2: + case GFXFormat.PVRTC2_2BPP: + return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 4) * depth; + case GFXFormat.PVRTC_RGB4: + case GFXFormat.PVRTC_RGBA4: + case GFXFormat.PVRTC2_4BPP: + return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 2) * depth; + + default: { + return 0; + } + } + } +} + +export function GFXFormatSurfaceSize ( + format: GFXFormat, width: number, height: number, + depth: number, mips: number): number { + + let size = 0; + + for (let i = 0; i < mips; ++i) { + size += GFXFormatSize(format, width, height, depth); + width = Math.max(width >> 1, 1); + height = Math.max(height >> 1, 1); + depth = Math.max(depth >> 1, 1); + } + + return size; +} + +export function GFXGetTypeSize (type: GFXType): number { + switch (type) { + case GFXType.BOOL: + case GFXType.INT: + case GFXType.UINT: + case GFXType.FLOAT: return 4; + case GFXType.BOOL2: + case GFXType.INT2: + case GFXType.UINT2: + case GFXType.FLOAT2: return 8; + case GFXType.BOOL3: + case GFXType.INT3: + case GFXType.UINT3: + case GFXType.FLOAT3: return 12; + case GFXType.BOOL4: + case GFXType.INT4: + case GFXType.UINT4: + case GFXType.FLOAT4: + case GFXType.MAT2: return 16; + case GFXType.MAT2X3: return 24; + case GFXType.MAT2X4: return 32; + case GFXType.MAT3X2: return 24; + case GFXType.MAT3: return 36; + case GFXType.MAT3X4: return 48; + case GFXType.MAT4X2: return 32; + case GFXType.MAT4X2: return 32; + case GFXType.MAT4: return 64; + case GFXType.SAMPLER1D: + case GFXType.SAMPLER1D_ARRAY: + case GFXType.SAMPLER2D: + case GFXType.SAMPLER2D_ARRAY: + case GFXType.SAMPLER3D: + case GFXType.SAMPLER_CUBE: return 4; + default: { + return 0; + } + } +} diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts new file mode 100644 index 0000000000..b4d36fc1c3 --- /dev/null +++ b/cocos/gfx/device.ts @@ -0,0 +1,160 @@ +import { GFXBindingLayout, IGFXBindingLayoutInfo } from './binding-layout'; +import { GFXBuffer, IGFXBufferInfo } from './buffer'; +import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from './command-allocator'; +import { GFXCommandBuffer, IGFXCommandBufferInfo } from './command-buffer'; +import { GFXBufferTextureCopy, GFXFormat } from './define'; +import { GFXFramebuffer, IGFXFramebufferInfo } from './framebuffer'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from './input-assembler'; +import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from './pipeline-layout'; +import { GFXPipelineState, IGFXPipelineStateInfo } from './pipeline-state'; +import { GFXQueue, IGFXQueueInfo } from './queue'; +import { GFXRenderPass, IGFXRenderPassInfo } from './render-pass'; +import { GFXSampler, IGFXSamplerInfo } from './sampler'; +import { GFXShader, IGFXShaderInfo } from './shader'; +import { GFXTexture, IGFXTextureInfo } from './texture'; +import { GFXTextureView, IGFXTextureViewInfo } from './texture-view'; +import { GFXWindow, IGFXWindowInfo } from './window'; + +export enum GFXFeature { + TEXTURE_FLOAT, + TEXTURE_HALF_FLOAT, + COUNT, +} + +export interface IGFXDeviceInfo { + canvasElm: HTMLElement; + isAntialias?: boolean; + isPremultipliedAlpha?: boolean; + debug?: boolean; +} + +// tslint:disable: max-line-length +export abstract class GFXDevice { + + public get canvas (): HTMLCanvasElement { + return this._canvas as HTMLCanvasElement; + } + + public get canvas2D (): HTMLCanvasElement { + return this._canvas2D as HTMLCanvasElement; + } + + public get queue (): GFXQueue { + return this._queue as GFXQueue; + } + + public get width (): number { + return this._width; + } + + public get height (): number { + return this._height; + } + + public get mainWindow (): GFXWindow { + return this._mainWindow as GFXWindow; + } + + public get commandAllocator (): GFXCommandAllocator { + return this._cmdAllocator as GFXCommandAllocator; + } + + public get renderer (): string { + return this._renderer; + } + + public get vendor (): string { + return this._vendor; + } + + public get maxVertexAttributes (): number { + return this._maxVertexAttributes; + } + + public get maxVertexUniformVectors (): number { + return this._maxVertexUniformVectors; + } + + public get maxFragmentUniformVectors (): number { + return this._maxFragmentUniformVectors; + } + + public get maxTextureUnits (): number { + return this._maxTextureUnits; + } + + public get maxVertexTextureUnits (): number { + return this._maxVertexTextureUnits; + } + + public get depthBits (): number { + return this._depthBits; + } + + public get stencilBits (): number { + return this._stencilBits; + } + + public get colorFormat (): GFXFormat { + return this._colorFmt; + } + + public get depthStencilFormat (): GFXFormat { + return this._depthStencilFmt; + } + + protected _canvas: HTMLCanvasElement | null = null; + protected _canvas2D: HTMLCanvasElement | null = null; + protected _deviceName: string = ''; + protected _renderer: string = ''; + protected _vendor: string = ''; + protected _version: string = ''; + protected _features: boolean[] = new Array(GFXFeature.COUNT); + protected _queue: GFXQueue | null = null; + protected _width: number = 0; + protected _height: number = 0; + protected _mainWindow: GFXWindow | null = null; + protected _cmdAllocator: GFXCommandAllocator | null = null; + protected _maxVertexAttributes: number = 0; + protected _maxVertexUniformVectors: number = 0; + protected _maxFragmentUniformVectors: number = 0; + protected _maxTextureUnits: number = 0; + protected _maxVertexTextureUnits: number = 0; + protected _depthBits: number = 0; + protected _stencilBits: number = 0; + protected _colorFmt: GFXFormat = GFXFormat.UNKNOWN; + protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; + protected _shaderIdGen: number = 0; + + public abstract initialize (info: IGFXDeviceInfo): boolean; + public abstract destroy (): void; + public abstract resize (width: number, height: number); + public abstract createBuffer (info: IGFXBufferInfo): GFXBuffer; + public abstract createTexture (info: IGFXTextureInfo): GFXTexture; + public abstract createTextureView (info: IGFXTextureViewInfo): GFXTextureView; + public abstract createSampler (info: IGFXSamplerInfo): GFXSampler; + public abstract createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout; + public abstract createShader (info: IGFXShaderInfo): GFXShader; + public abstract createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler; + public abstract createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass; + public abstract createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer; + public abstract createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout; + public abstract createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState; + public abstract createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator; + public abstract createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer; + public abstract createQueue (info: IGFXQueueInfo): GFXQueue; + public abstract createWindow (info: IGFXWindowInfo): GFXWindow; + public abstract present (); + + public abstract copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyImageSourceToTexture (source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyFramebufferToBuffer (srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]); + + public hasFeature (feature: GFXFeature): boolean { + return this._features[feature]; + } + + public genShaderId (): number { + return this._shaderIdGen++; + } +} diff --git a/cocos/gfx/framebuffer.ts b/cocos/gfx/framebuffer.ts new file mode 100644 index 0000000000..f9a3729389 --- /dev/null +++ b/cocos/gfx/framebuffer.ts @@ -0,0 +1,44 @@ +import { GFXObject, GFXObjectType } from './define'; +import { GFXDevice } from './device'; +import { GFXRenderPass } from './render-pass'; +import { GFXTextureView } from './texture-view'; + +export interface IGFXFramebufferInfo { + renderPass: GFXRenderPass; + colorViews?: GFXTextureView[]; + depthStencilView?: GFXTextureView; + isOffscreen?: boolean; +} + +export abstract class GFXFramebuffer extends GFXObject { + + public get renderPass (): GFXRenderPass | null { + return this._renderPass; + } + + public get colorViews (): GFXTextureView[] { + return this._colorViews; + } + + public get depthStencilView (): GFXTextureView | null { + return this._depthStencilView; + } + + public get isOffscreen (): boolean { + return this._isOffscreen; + } + + protected _device: GFXDevice; + protected _renderPass: GFXRenderPass | null = null; + protected _colorViews: GFXTextureView[] = []; + protected _depthStencilView: GFXTextureView | null = null; + protected _isOffscreen: boolean = true; + + constructor (device: GFXDevice) { + super(GFXObjectType.FRAMEBUFFER); + this._device = device; + } + + public abstract initialize (info: IGFXFramebufferInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/index.ts b/cocos/gfx/index.ts new file mode 100644 index 0000000000..f113ba14e1 --- /dev/null +++ b/cocos/gfx/index.ts @@ -0,0 +1,32 @@ +import { GFXBuffer } from './buffer'; +import { GFXCommandBuffer } from './command-buffer'; +import * as GFXDefines from './define'; +import { GFXDevice } from './device'; +import { GFXFramebuffer } from './framebuffer'; +import { GFXInputAssembler } from './input-assembler'; +import { GFXPipelineLayout } from './pipeline-layout'; +import { GFXPipelineState } from './pipeline-state'; +import { GFXQueue } from './queue'; +import { GFXRenderPass } from './render-pass'; +import { GFXSampler } from './sampler'; +import { GFXShader } from './shader'; +import { GFXTexture } from './texture'; +import { GFXTextureView } from './texture-view'; +import { WebGLGFXDevice } from './webgl/webgl-device'; + +cc.GFXDevice = GFXDevice; +cc.GFXBuffer = GFXBuffer; +cc.GFXTexture = GFXTexture; +cc.GFXTextureView = GFXTextureView; +cc.GFXSampler = GFXSampler; +cc.GFXShader = GFXShader; +cc.GFXInputAssembler = GFXInputAssembler; +cc.GFXRenderPass = GFXRenderPass; +cc.GFXFramebuffer = GFXFramebuffer; +cc.GFXPipelineLayout = GFXPipelineLayout; +cc.GFXPipelineState = GFXPipelineState; +cc.GFXCommandBuffer = GFXCommandBuffer; +cc.GFXQueue = GFXQueue; +cc.WebGLGFXDevice = WebGLGFXDevice; + +Object.assign(cc, GFXDefines); diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts new file mode 100644 index 0000000000..be82359697 --- /dev/null +++ b/cocos/gfx/input-assembler.ts @@ -0,0 +1,168 @@ +import { GFXBuffer, IGFXDrawInfo } from './buffer'; +import { GFXFormat, GFXFormatInfos, GFXObject, GFXObjectType } from './define'; +import { GFXDevice } from './device'; + +export interface IGFXInputAttribute { + binding?: number; + name: string; + format: GFXFormat; + isNormalized?: boolean; + stream?: number; + isInstanced?: boolean; +} + +export interface IGFXInputAssemblerInfo { + attributes: IGFXInputAttribute[]; + vertexBuffers: GFXBuffer[]; + indexBuffer?: GFXBuffer; + indirectBuffer?: GFXBuffer; +} + +const isLittleEndian = cc.sys.isLittleEndian; + +export abstract class GFXInputAssembler extends GFXObject { + + public get vertexBuffers (): GFXBuffer[] { + return this._vertexBuffers; + } + + public get indexBuffer (): GFXBuffer | null { + return this._indexBuffer; + } + + public get attributes (): IGFXInputAttribute[] { + return this._attributes; + } + + public get vertexCount (): number { + return this._vertexCount; + } + + public set vertexCount (count: number) { + this._vertexCount = count; + } + + public get firstVertex (): number { + return this._firstVertex; + } + + public set firstVertex (first: number) { + this._firstVertex = first; + } + + public get indexCount (): number { + return this._indexCount; + } + + public set indexCount (count: number) { + this._indexCount = count; + } + + public get firstIndex (): number { + return this._firstIndex; + } + + public set firstIndex (first: number) { + this._firstIndex = first; + } + + public get vertexOffset (): number { + return this._vertexOffset; + } + + public set vertexOffset (offset: number) { + this._vertexOffset = offset; + } + + public get instanceCount (): number { + return this._instanceCount; + } + + public set instanceCount (count: number) { + this._instanceCount = count; + } + + public get firstInstance (): number { + return this._firstInstance; + } + + public set firstInstance (first: number) { + this._firstInstance = first; + } + + public get isIndirect (): boolean { + return this._isIndirect; + } + + public get indirectBuffer (): GFXBuffer | null { + return this._indirectBuffer; + } + + protected _device: GFXDevice; + protected _attributes: IGFXInputAttribute[] = []; + protected _vertexBuffers: GFXBuffer[] = []; + protected _indexBuffer: GFXBuffer | null = null; + protected _vertexCount: number = 0; + protected _firstVertex: number = 0; + protected _indexCount: number = 0; + protected _firstIndex: number = 0; + protected _vertexOffset: number = 0; + protected _instanceCount: number = 0; + protected _firstInstance: number = 0; + protected _isIndirect: boolean = false; + protected _indirectBuffer: GFXBuffer | null = null; + + constructor (device: GFXDevice) { + super(GFXObjectType.INPUT_ASSEMBLER); + this._device = device; + } + + public abstract initialize (info: IGFXInputAssemblerInfo): boolean; + public abstract destroy (): void; + + public getVertexBuffer (stream: number = 0): GFXBuffer | null { + if (stream < this._vertexBuffers.length) { + return this._vertexBuffers[stream]; + } else { + return null; + } + } + + public extractDrawInfo (drawInfo: IGFXDrawInfo) { + drawInfo.vertexCount = this._vertexCount; + drawInfo.firstVertex = this._firstVertex; + drawInfo.indexCount = this._indexCount; + drawInfo.firstIndex = this._firstIndex; + drawInfo.vertexOffset = this._vertexOffset; + drawInfo.instanceCount = this._instanceCount; + drawInfo.firstInstance = this._firstInstance; + } + + public updateVertexAttr (attr: string, data: number[]) { + let offset = 0; + let count = 0; + let size = 0; + let fn = ''; + for (const a of this._attributes) { + const info = GFXFormatInfos[a.format]; + if (a.name === attr) { + count = info.count; + size = info.size / count; + fn = `set${info.isFloating ? 'Float' : 'Int'}${size * 8}`; + break; + } + offset += info.size; + } + const vb = this._vertexBuffers[0]; + if (!count || !vb || !vb.buffer) { return; } + const stride = vb.stride; + const view = new DataView(vb.buffer as ArrayBuffer); + const len = data.length; + for (let idx = 0, beg = offset; idx < len; idx += count, beg += stride) { + for (let j = 0; j < count; j++) { + view[fn](beg + j * size, data[idx + j], isLittleEndian); + } + } + vb.update(vb.buffer); + } +} diff --git a/cocos/gfx/pipeline-layout.ts b/cocos/gfx/pipeline-layout.ts new file mode 100644 index 0000000000..69a4f91a69 --- /dev/null +++ b/cocos/gfx/pipeline-layout.ts @@ -0,0 +1,33 @@ +import { GFXBindingLayout } from './binding-layout'; +import { GFXObject, GFXObjectType, GFXShaderType } from './define'; +import { GFXDevice } from './device'; + +export interface IGFXPushConstantRange { + shaderType: GFXShaderType; + offset: number; + count: number; +} + +export interface IGFXPipelineLayoutInfo { + pushConstantsRanges?: IGFXPushConstantRange[]; + layouts: GFXBindingLayout[]; +} + +export abstract class GFXPipelineLayout extends GFXObject { + + public get layouts (): GFXBindingLayout[] { + return this._layouts; + } + + protected _device: GFXDevice; + protected _pushConstantsRanges: IGFXPushConstantRange[] = []; + protected _layouts: GFXBindingLayout[] = []; + + constructor (device: GFXDevice) { + super(GFXObjectType.PIPELINE_LAYOUT); + this._device = device; + } + + public abstract initialize (info: IGFXPipelineLayoutInfo): boolean; + public abstract destroy (); +} diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts new file mode 100644 index 0000000000..9fb9e94c66 --- /dev/null +++ b/cocos/gfx/pipeline-state.ts @@ -0,0 +1,190 @@ +import { + GFXBlendFactor, + GFXBlendOp, + GFXColorMask, + GFXComparisonFunc, + GFXCullMode, + GFXDynamicState, + GFXObject, + GFXObjectType, + GFXPolygonMode, + GFXPrimitiveMode, + GFXShadeModel, + GFXStencilOp, +} from './define'; +import { GFXDevice } from './device'; +import { IGFXInputAttribute } from './input-assembler'; +import { GFXPipelineLayout } from './pipeline-layout'; +import { GFXRenderPass } from './render-pass'; +import { GFXShader } from './shader'; + +export class GFXRasterizerState { + public isDiscard: boolean = false; + public polygonMode: GFXPolygonMode = GFXPolygonMode.FILL; + public shadeModel: GFXShadeModel = GFXShadeModel.GOURAND; + public cullMode: GFXCullMode = GFXCullMode.BACK; + public isFrontFaceCCW: boolean = true; + public depthBias: number = 0; + public depthBiasClamp: number = 0.0; + public depthBiasSlop: number = 0.0; + public isDepthClip: boolean = true; + public isMultisample: boolean = false; + public lineWidth: number = 1.0; + + public compare (state: GFXRasterizerState): boolean { + return (this.isDiscard === state.isDiscard) && + (this.polygonMode === state.polygonMode) && + (this.shadeModel === state.shadeModel) && + (this.cullMode === state.cullMode) && + (this.isFrontFaceCCW === state.isFrontFaceCCW) && + (this.depthBias === state.depthBias) && + (this.depthBiasClamp === state.depthBiasClamp) && + (this.depthBiasSlop === state.depthBiasSlop) && + (this.isDepthClip === state.isDepthClip) && + (this.lineWidth === state.lineWidth) && + (this.isMultisample === state.isMultisample); + } +} + +export class GFXDepthStencilState { + public depthTest: boolean = true; + public depthWrite: boolean = true; + public depthFunc: GFXComparisonFunc = GFXComparisonFunc.LESS; + public stencilTestFront: boolean = false; + public stencilFuncFront: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + public stencilReadMaskFront: number = 0xffffffff; + public stencilWriteMaskFront: number = 0xffffffff; + public stencilFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; + public stencilZFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; + public stencilPassOpFront: GFXStencilOp = GFXStencilOp.KEEP; + public stencilRefFront: number = 1; + public stencilTestBack: boolean = false; + public stencilFuncBack: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + public stencilReadMaskBack: number = 0xffffffff; + public stencilWriteMaskBack: number = 0xffffffff; + public stencilFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; + public stencilZFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; + public stencilPassOpBack: GFXStencilOp = GFXStencilOp.KEEP; + public stencilRefBack: number = 1; + + public compare (state: GFXDepthStencilState): boolean { + return (this.depthTest === state.depthTest) && + (this.depthWrite === state.depthWrite) && + (this.depthFunc === state.depthFunc) && + (this.stencilTestFront === state.stencilTestFront) && + (this.stencilFuncFront === state.stencilFuncFront) && + (this.stencilReadMaskFront === state.stencilReadMaskFront) && + (this.stencilWriteMaskFront === state.stencilWriteMaskFront) && + (this.stencilFailOpFront === state.stencilFailOpFront) && + (this.stencilZFailOpFront === state.stencilZFailOpFront) && + (this.stencilPassOpFront === state.stencilPassOpFront) && + (this.stencilRefFront === state.stencilRefFront) && + (this.stencilTestBack === state.stencilTestBack) && + (this.stencilFuncBack === state.stencilFuncBack) && + (this.stencilReadMaskBack === state.stencilReadMaskBack) && + (this.stencilWriteMaskBack === state.stencilWriteMaskBack) && + (this.stencilFailOpBack === state.stencilFailOpBack) && + (this.stencilZFailOpBack === state.stencilZFailOpBack) && + (this.stencilPassOpBack === state.stencilPassOpBack) && + (this.stencilRefBack === state.stencilRefBack); + } +} + +export class GFXBlendTarget { + public blend: boolean = false; + public blendSrc: GFXBlendFactor = GFXBlendFactor.ONE; + public blendDst: GFXBlendFactor = GFXBlendFactor.ZERO; + public blendEq: GFXBlendOp = GFXBlendOp.ADD; + public blendSrcAlpha: GFXBlendFactor = GFXBlendFactor.ONE; + public blendDstAlpha: GFXBlendFactor = GFXBlendFactor.ZERO; + public blendAlphaEq: GFXBlendOp = GFXBlendOp.ADD; + public blendColorMask: GFXColorMask = GFXColorMask.ALL; + + public compare (state: GFXBlendTarget): boolean { + return (this.blend === state.blend) && + (this.blendSrc === state.blendSrc) && + (this.blendDst === state.blendDst) && + (this.blendEq === state.blendEq) && + (this.blendSrcAlpha === state.blendSrcAlpha) && + (this.blendDstAlpha === state.blendDstAlpha) && + (this.blendAlphaEq === state.blendAlphaEq) && + (this.blendColorMask === state.blendColorMask); + } +} + +export class GFXBlendState { + public isA2C: boolean = false; + public isIndepend: boolean = false; + public blendColor: number[] = [0, 0, 0, 0]; + public targets: GFXBlendTarget[] = [new GFXBlendTarget()]; +} + +export class GFXInputState { + public attributes: IGFXInputAttribute[] = []; +} + +export interface IGFXPipelineStateInfo { + primitive: GFXPrimitiveMode; + shader: GFXShader; + is: GFXInputState; + rs: GFXRasterizerState; + dss: GFXDepthStencilState; + bs: GFXBlendState; + dynamicStates?: GFXDynamicState[]; + layout: GFXPipelineLayout; + renderPass: GFXRenderPass; +} + +export abstract class GFXPipelineState extends GFXObject { + + public get shader (): GFXShader { + return this._shader as GFXShader; + } + + public get primitive (): GFXPrimitiveMode { + return this._primitive; + } + + public get rasterizerState (): GFXRasterizerState { + return this._rs as GFXRasterizerState; + } + + public get depthStencilState (): GFXDepthStencilState { + return this._dss as GFXDepthStencilState; + } + + public get blendState (): GFXBlendState { + return this._bs as GFXBlendState; + } + + public get dynamicStates (): GFXDynamicState[] { + return this._dynamicStates; + } + + public get pipelineLayout (): GFXPipelineLayout { + return this._layout as GFXPipelineLayout; + } + + public get renderPass (): GFXRenderPass { + return this._renderPass as GFXRenderPass; + } + + protected _device: GFXDevice; + protected _shader: GFXShader | null = null; + protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + protected _is: GFXInputState | null = null; + protected _rs: GFXRasterizerState | null = null; + protected _dss: GFXDepthStencilState | null = null; + protected _bs: GFXBlendState | null = null; + protected _dynamicStates: GFXDynamicState[] = []; + protected _layout: GFXPipelineLayout | null = null; + protected _renderPass: GFXRenderPass | null = null; + + constructor (device: GFXDevice) { + super(GFXObjectType.PIPELINE_STATE); + this._device = device; + } + + public abstract initialize (info: IGFXPipelineStateInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/queue.ts b/cocos/gfx/queue.ts new file mode 100644 index 0000000000..a13c31a3cd --- /dev/null +++ b/cocos/gfx/queue.ts @@ -0,0 +1,26 @@ +import { GFXCommandBuffer } from './command-buffer'; +import { GFXObject, GFXObjectType, GFXQueueType } from './define'; +import { GFXDevice } from './device'; + +export interface IGFXQueueInfo { + type: GFXQueueType; +} + +export abstract class GFXQueue extends GFXObject { + + public get type (): number { + return this._type; + } + + protected _device: GFXDevice; + protected _type: GFXQueueType = GFXQueueType.GRAPHICS; + + constructor (device: GFXDevice) { + super(GFXObjectType.QUEUE); + this._device = device; + } + + public abstract initialize (info: IGFXQueueInfo): boolean; + public abstract destroy (); + public abstract submit (cmdBuffs: GFXCommandBuffer[], fence?); +} diff --git a/cocos/gfx/render-pass.ts b/cocos/gfx/render-pass.ts new file mode 100644 index 0000000000..dc65c285e5 --- /dev/null +++ b/cocos/gfx/render-pass.ts @@ -0,0 +1,61 @@ +import { + GFXFormat, + GFXLoadOp, + GFXObject, + GFXObjectType, + GFXPipelineBindPoint, + GFXStoreOp, + GFXTextureLayout, +} from './define'; +import { GFXDevice } from './device'; + +export class GFXColorAttachment { + public format: GFXFormat = GFXFormat.UNKNOWN; + public loadOp: GFXLoadOp = GFXLoadOp.CLEAR; + public storeOp: GFXStoreOp = GFXStoreOp.STORE; + public sampleCount: number = 1; + public beginLayout: GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; + public endLayout: GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; +} + +export class GFXDepthStencilAttachment { + public format: GFXFormat = GFXFormat.UNKNOWN; + public depthLoadOp: GFXLoadOp = GFXLoadOp.CLEAR; + public depthStoreOp: GFXStoreOp = GFXStoreOp.STORE; + public stencilLoadOp: GFXLoadOp = GFXLoadOp.CLEAR; + public stencilStoreOp: GFXStoreOp = GFXStoreOp.STORE; + public sampleCount: number = 1; + public beginLayout: GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + public endLayout: GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; +} + +export interface IGFXSubPassInfo { + bindPoint: GFXPipelineBindPoint; + inputs: number[]; + colors: number[]; + resolves: number[]; + depthStencil: number; + preserves: number[]; +} + +export interface IGFXRenderPassInfo { + colorAttachments?: GFXColorAttachment[]; + depthStencilAttachment?: GFXDepthStencilAttachment; + // subPasses? : GFXSubPassInfo[]; +} + +export abstract class GFXRenderPass extends GFXObject { + + protected _device: GFXDevice; + protected _colorInfos: GFXColorAttachment[] = []; + protected _depthStencilInfo: GFXDepthStencilAttachment | null = null; + + constructor (device: GFXDevice) { + super(GFXObjectType.RENDER_PASS); + this._device = device; + } + + public abstract initialize (info: IGFXRenderPassInfo): boolean; + public abstract destroy (): void; + // protected _subPasses : GFXSubPassInfo[] = []; +} diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts new file mode 100644 index 0000000000..d468316b49 --- /dev/null +++ b/cocos/gfx/sampler.ts @@ -0,0 +1,67 @@ +import { GFXAddress, GFXComparisonFunc, GFXFilter, GFXObject, GFXObjectType } from './define'; +import { GFXDevice } from './device'; + +export interface IGFXSamplerInfo { + name?: string; + minFilter?: GFXFilter; + magFilter?: GFXFilter; + mipFilter?: GFXFilter; + addressU?: GFXAddress; + addressV?: GFXAddress; + addressW?: GFXAddress; + maxAnisotropy?: number; + cmpFunc?: GFXComparisonFunc; + borderColor?: number[]; + minLOD?: number; + maxLOD?: number; + mipLODBias?: number; +} + +export class GFXSamplerState { + public name: string = ''; + public minFilter: GFXFilter = GFXFilter.LINEAR; + public magFilter: GFXFilter = GFXFilter.LINEAR; + public mipFilter: GFXFilter = GFXFilter.NONE; + public addressU: GFXAddress = GFXAddress.CLAMP; + public addressV: GFXAddress = GFXAddress.CLAMP; + public addressW: GFXAddress = GFXAddress.CLAMP; + public maxAnisotropy: number = 16; + public cmpFunc: GFXComparisonFunc = GFXComparisonFunc.NEVER; + public borderColor: number[] = [0.0, 0.0, 0.0, 0.0]; + public minLOD: number = 0; + public maxLOD: number = 1000; + public mipLODBias: number = 0.0; + + public compare (state: GFXSamplerState): boolean { + return (this.minFilter === state.minFilter) && + (this.magFilter === state.magFilter) && + (this.mipFilter === state.mipFilter) && + (this.addressU === state.addressU) && + (this.addressV === state.addressV) && + (this.addressW === state.addressW) && + (this.maxAnisotropy === state.maxAnisotropy) && + (this.cmpFunc === state.cmpFunc) && + (this.borderColor === state.borderColor) && + (this.minLOD === state.minLOD) && + (this.maxLOD === state.maxLOD) && + (this.mipLODBias === state.mipLODBias); + } +} + +export abstract class GFXSampler extends GFXObject { + + public get state (): GFXSamplerState { + return this._state; + } + + protected _device: GFXDevice; + protected _state: GFXSamplerState = new GFXSamplerState(); + + constructor (device: GFXDevice) { + super(GFXObjectType.SAMPLER); + this._device = device; + } + + public abstract initialize (info: IGFXSamplerInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts new file mode 100644 index 0000000000..5cae992798 --- /dev/null +++ b/cocos/gfx/shader.ts @@ -0,0 +1,67 @@ +import { GFXObject, GFXObjectType, GFXShaderType, GFXType } from './define'; +import { GFXDevice } from './device'; + +export interface IGFXShaderMacro { + macro: string; + value: string; +} + +export interface IGFXShaderStage { + type: GFXShaderType; + source: string; + macros?: IGFXShaderMacro[]; +} + +export class GFXUniform { + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public count: number = 1; +} + +export class GFXUniformBlock { + public binding: number = -1; + public name: string = ''; + // instance : string; + public members: GFXUniform[] = []; +} + +export class GFXUniformSampler { + public binding: number = -1; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public count: number = 1; +} + +export interface IGFXShaderInfo { + name: string; + stages: IGFXShaderStage[]; + // bindings: GFXBinding[]; + + blocks?: GFXUniformBlock[]; + samplers?: GFXUniformSampler[]; +} + +export abstract class GFXShader extends GFXObject { + + public get id (): number { + return this._id; + } + + protected _device: GFXDevice; + protected _id: number; + protected _name: string = ''; + protected _stages: IGFXShaderStage[] = []; + // protected _bindings: GFXBinding[] = []; + protected _blocks: GFXUniformBlock[] = []; // blocks are used for being compatible with single uniforms + protected _samplers: GFXUniformSampler[] = []; + + constructor (device: GFXDevice) { + super(GFXObjectType.SHADER); + this._device = device; + this._id = device.genShaderId(); + } + + public abstract initialize (info: IGFXShaderInfo): boolean; + public abstract destroy (); + public get name () { return this._name; } +} diff --git a/cocos/gfx/texture-view.ts b/cocos/gfx/texture-view.ts new file mode 100644 index 0000000000..6b19137200 --- /dev/null +++ b/cocos/gfx/texture-view.ts @@ -0,0 +1,61 @@ +import { GFXFormat, GFXObject, GFXObjectType, GFXTextureViewType } from './define'; +import { GFXDevice } from './device'; +import { GFXTexture } from './texture'; + +export interface IGFXTextureViewInfo { + texture: GFXTexture; + type: GFXTextureViewType; + format: GFXFormat; + baseLevel?: number; + levelCount?: number; + baseLayer?: number; + layerCount?: number; +} + +export abstract class GFXTextureView extends GFXObject { + + public get texture (): GFXTexture { + return this._texture as GFXTexture; + } + + public get type (): GFXTextureViewType { + return this._type; + } + + public get format (): GFXFormat { + return this._format; + } + + public get baseLevel (): number { + return this._baseLevel; + } + + public get levelCount (): number { + return this._levelCount; + } + + public get baseLayer (): number { + return this._baseLayer; + } + + public get layerCount (): number { + return this._layerCount; + } + + protected _device: GFXDevice; + protected _texture: GFXTexture | null = null; + protected _type: GFXTextureViewType = GFXTextureViewType.TV2D; + protected _format: GFXFormat = GFXFormat.UNKNOWN; + protected _baseLevel: number = 0; + protected _levelCount: number = 1; + protected _baseLayer: number = 0; + protected _layerCount: number = 1; + + constructor (device: GFXDevice) { + super(GFXObjectType.TEXTURE_VIEW); + this._device = device; + } + + public abstract initialize (info: IGFXTextureViewInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/texture.ts b/cocos/gfx/texture.ts new file mode 100644 index 0000000000..8e10ab1898 --- /dev/null +++ b/cocos/gfx/texture.ts @@ -0,0 +1,91 @@ +import { + GFXFormat, + GFXObject, + GFXObjectType, + GFXTextureFlagBit, + GFXTextureFlags, + GFXTextureType, + GFXTextureUsage, + GFXTextureUsageBit, +} from './define'; +import { GFXDevice } from './device'; + +export interface IGFXTextureInfo { + type: GFXTextureType; + usage: GFXTextureUsage; + format: GFXFormat; + width: number; + height: number; + depth?: number; + arrayLayer?: number; + mipLevel?: number; + flags?: GFXTextureFlags; +} + +export abstract class GFXTexture extends GFXObject { + + public get type (): GFXTextureType { + return this._type; + } + + public get usage (): GFXTextureUsage { + return this._usage; + } + + public get format (): GFXFormat { + return this._format; + } + + public get width (): number { + return this._width; + } + + public get height (): number { + return this._height; + } + + public get depth (): number { + return this._depth; + } + + public get arrayLayer (): number { + return this._arrayLayer; + } + + public get mipLevel (): number { + return this._mipLevel; + } + + public get flags (): GFXTextureFlags { + return this._flags; + } + + public get size (): number { + return this._size; + } + + public get buffer (): ArrayBuffer | null { + return this._buffer; + } + + protected _device: GFXDevice; + protected _type: GFXTextureType = GFXTextureType.TEX2D; + protected _usage: GFXTextureUsage = GFXTextureUsageBit.NONE; + protected _format: GFXFormat = GFXFormat.UNKNOWN; + protected _width: number = 0; + protected _height: number = 0; + protected _depth: number = 1; + protected _arrayLayer: number = 1; + protected _mipLevel: number = 1; + protected _flags: GFXTextureFlags = GFXTextureFlagBit.NONE; + protected _size: number = 0; + protected _buffer: ArrayBuffer | null = null; + + constructor (device: GFXDevice) { + super(GFXObjectType.TEXTURE); + this._device = device; + } + + public abstract initialize (info: IGFXTextureInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/vertex-format-sample.ts b/cocos/gfx/vertex-format-sample.ts new file mode 100644 index 0000000000..97092412b3 --- /dev/null +++ b/cocos/gfx/vertex-format-sample.ts @@ -0,0 +1,20 @@ +import { GFXAttributeName, GFXFormat } from './define'; + +const vfmt = [ + { + name: GFXAttributeName.ATTR_POSITION, + format: GFXFormat.RGB32F, + }, + { + name: GFXAttributeName.ATTR_TEX_COORD, + format: GFXFormat.RG32F, + }, + { + name: GFXAttributeName.ATTR_COLOR, + format: GFXFormat.RGBA32F, + }, +]; + +export { + vfmt, +}; diff --git a/cocos/gfx/webgl/webgl-binding-layout.ts b/cocos/gfx/webgl/webgl-binding-layout.ts new file mode 100644 index 0000000000..fad7cb8cb5 --- /dev/null +++ b/cocos/gfx/webgl/webgl-binding-layout.ts @@ -0,0 +1,59 @@ +import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUBindingLayout } from './webgl-gpu-objects'; + +export class WebGLGFXBindingLayout extends GFXBindingLayout { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuBindingLayout (): WebGLGPUBindingLayout { + return this._gpuBindingLayout as WebGLGPUBindingLayout; + } + + private _gpuBindingLayout: WebGLGPUBindingLayout | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXBindingLayoutInfo): boolean { + + this._bindingUnits = new Array(info.bindings.length); + for (let i = 0; i < info.bindings.length; ++i) { + const binding = info.bindings[i]; + this._bindingUnits[i] = { + binding: binding.binding, + type: binding.type, + name: binding.name, + buffer: null, + texView: null, + sampler: null, + }; + } + + this._gpuBindingLayout = this.webGLDevice.emitCmdCreateGPUBindingLayout(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuBindingLayout) { + this.webGLDevice.emitCmdDestroyGPUBindingLayout(this._gpuBindingLayout); + this._gpuBindingLayout = null; + } + + this._status = GFXStatus.UNREADY; + } + + public update () { + if (this._isDirty) { + this.webGLDevice.emitCmdUpdateGPUBindingLayout(this._gpuBindingLayout!, this._bindingUnits); + this._isDirty = false; + } + } +} diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts new file mode 100644 index 0000000000..4a2280a25a --- /dev/null +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -0,0 +1,91 @@ +import { GFXBuffer, GFXBufferSource, IGFXBufferInfo } from '../buffer'; +import { GFXBufferUsageBit, GFXGetTypeSize, GFXMemoryUsageBit, GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUBuffer } from './webgl-gpu-objects'; + +export class WebGLGFXBuffer extends GFXBuffer { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuBuffer (): WebGLGPUBuffer { + return this._gpuBuffer!; + } + + private _gpuBuffer: WebGLGPUBuffer | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXBufferInfo): boolean { + + this._usage = info.usage; + this._memUsage = info.memUsage; + this._size = info.size; + + if (info.stride !== undefined) { + this._stride = info.stride; + } + this._stride = Math.max(this._stride, 1); + this._count = this._size / this._stride; + + if (this._memUsage & GFXMemoryUsageBit.HOST) { + if (this._usage & GFXBufferUsageBit.INDIRECT) { + this._buffer = { drawInfos: [] }; + } else { + this._buffer = new ArrayBuffer(this._size); + } + } + + // this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; + this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuBuffer) { + this.webGLDevice.emitCmdDestroyGPUBuffer(this._gpuBuffer); + this._gpuBuffer = null; + } + + this._buffer = null; + this._status = GFXStatus.UNREADY; + } + + public resize (size: number) { + this._size = size; + this._count = this._size / this._stride; + + if (this._memUsage & GFXMemoryUsageBit.HOST) { + if ((this._usage & GFXBufferUsageBit.INDIRECT) === GFXBufferUsageBit.NONE) { + this._buffer = new ArrayBuffer(this._size); + } + } + + this.webGLDevice.emitCmdResizeGPUBuffer(this._gpuBuffer!, this._buffer); + } + + public update (buffer: GFXBufferSource, offset?: number, size?: number) { + + // const isUniformBuffer = (this._usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; + let buffSize; + if (size !== undefined ) { + buffSize = size; + } else if (this._usage & GFXBufferUsageBit.INDIRECT) { + buffSize = 0; + } else { + buffSize = (buffer as ArrayBuffer).byteLength; + } + + this.webGLDevice.emitCmdUpdateGPUBuffer( + this._gpuBuffer!, + buffer, + offset !== undefined ? offset : 0, + buffSize); + } +} diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts new file mode 100644 index 0000000000..12bdee0502 --- /dev/null +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -0,0 +1,148 @@ +import { CachedArray } from '../../core/memop/cached-array'; +import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { + WebGLCmdBeginRenderPass, + WebGLCmdBindStates, + WebGLCmdCopyBufferToTexture, + WebGLCmdDraw, + WebGLCmdObject, + WebGLCmdPackage, + WebGLCmdUpdateBuffer, +} from './webgl-commands'; + +export class WebGLGFXCommandPool { + + private _frees: Array; + private _freeIdx: number = 0; + private _freeCmds: CachedArray; + + constructor (clazz: new() => T, count: number) { + this._frees = new Array(count); + this._freeCmds = new CachedArray(count); + for (let i = 0; i < count; ++i) { + this._frees[i] = new clazz(); + } + this._freeIdx = count - 1; + } + + public alloc (clazz: new() => T): T { + return new clazz(); + } + + /* + public alloc (clazz: new() => T): T { + if (this._freeIdx < 0) { + const size = this._frees.length * 2; + const temp = this._frees; + this._frees = new Array(size); + + const increase = size - temp.length; + for (let i = 0; i < increase; ++i) { + this._frees[i] = new clazz(); + } + + for (let i = increase, j = 0; i < size; ++i, ++j) { + this._frees[i] = temp[j]; + } + + this._freeIdx += increase; + } + + const cmd = this._frees[this._freeIdx]!; + this._frees[this._freeIdx--] = null; + ++cmd.refCount; + return cmd; + } + */ + + public free (cmd: T) { + if (--cmd.refCount === 0) { + this._freeCmds.push(cmd); + } + } + + public freeCmds (cmds: CachedArray) { + return ; + for (let i = 0; i < cmds.length; ++i) { + if (--cmds.array[i].refCount === 0) { + this._freeCmds.push(cmds.array[i]); + } + } + } + + public release () { + for (let i = 0; i < this._freeCmds.length; ++i) { + const cmd = this._freeCmds.array[i]; + cmd.clear(); + this._frees[++this._freeIdx] = cmd; + } + this._freeCmds.clear(); + } +} + +export class WebGLGFXCommandAllocator extends GFXCommandAllocator { + + public beginRenderPassCmdPool: WebGLGFXCommandPool; + public bindStatesCmdPool: WebGLGFXCommandPool; + public drawCmdPool: WebGLGFXCommandPool; + public updateBufferCmdPool: WebGLGFXCommandPool; + public copyBufferToTextureCmdPool: WebGLGFXCommandPool; + + constructor (device: GFXDevice) { + super(device); + this.beginRenderPassCmdPool = new WebGLGFXCommandPool(WebGLCmdBeginRenderPass, 16); + this.bindStatesCmdPool = new WebGLGFXCommandPool(WebGLCmdBindStates, 16); + this.drawCmdPool = new WebGLGFXCommandPool(WebGLCmdDraw, 16); + this.updateBufferCmdPool = new WebGLGFXCommandPool(WebGLCmdUpdateBuffer, 16); + this.copyBufferToTextureCmdPool = new WebGLGFXCommandPool(WebGLCmdCopyBufferToTexture, 16); + } + + public initialize (info: IGFXCommandAllocatorInfo): boolean { + this._status = GFXStatus.SUCCESS; + return true; + } + + public destroy () { + this._status = GFXStatus.UNREADY; + } + + public clearCmds (cmdPackage: WebGLCmdPackage) { + + if (cmdPackage.beginRenderPassCmds.length) { + this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds); + cmdPackage.beginRenderPassCmds.clear(); + } + + if (cmdPackage.bindStatesCmds.length) { + this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds); + cmdPackage.bindStatesCmds.clear(); + } + + if (cmdPackage.drawCmds.length) { + this.drawCmdPool.freeCmds(cmdPackage.drawCmds); + cmdPackage.drawCmds.clear(); + } + + if (cmdPackage.updateBufferCmds.length) { + this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds); + cmdPackage.updateBufferCmds.clear(); + } + + if (cmdPackage.copyBufferToTextureCmds.length) { + this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds); + cmdPackage.copyBufferToTextureCmds.clear(); + } + + cmdPackage.cmds.clear(); + } + + public releaseCmds () { + this.beginRenderPassCmdPool.release(); + this.bindStatesCmdPool.release(); + this.drawCmdPool.release(); + this.updateBufferCmdPool.release(); + this.copyBufferToTextureCmdPool.release(); + } +} diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts new file mode 100644 index 0000000000..4843dd2bca --- /dev/null +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -0,0 +1,481 @@ +import { GFXBindingLayout } from '../binding-layout'; +import { GFXBuffer, GFXBufferSource } from '../buffer'; +import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; +import { + GFXBufferTextureCopy, + GFXBufferUsageBit, + GFXCommandBufferType, + GFXStatus, + GFXStencilFace, + GFXTextureLayout, + IGFXColor, + IGFXRect, + IGFXViewport, +} from '../define'; +import { GFXDevice } from '../device'; +import { GFXFramebuffer } from '../framebuffer'; +import { GFXInputAssembler } from '../input-assembler'; +import { GFXPipelineState } from '../pipeline-state'; +import { GFXTexture } from '../texture'; +import { WebGLGFXBindingLayout } from './webgl-binding-layout'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { + WebGLCmd, + WebGLCmdBeginRenderPass, + WebGLCmdBindStates, + WebGLCmdCopyBufferToTexture, + WebGLCmdDraw, + WebGLCmdPackage, + WebGLCmdUpdateBuffer, +} from './webgl-commands'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGFXFramebuffer } from './webgl-framebuffer'; +import { WebGLGPUBindingLayout, WebGLGPUInputAssembler, WebGLGPUPipelineState } from './webgl-gpu-objects'; +import { WebGLGFXInputAssembler } from './webgl-input-assembler'; +import { WebGLGFXPipelineState } from './webgl-pipeline-state'; +import { WebGLGFXTexture } from './webgl-texture'; + +export interface IGFXDepthBias { + constantFactor: number; + clamp: number; + slopeFactor: number; +} + +export interface IGFXDepthBounds { + minBounds: number; + maxBounds: number; +} + +export interface IGFXStencilWriteMask { + face: GFXStencilFace; + writeMask: number; +} + +export interface IGFXStencilCompareMask { + face: GFXStencilFace; + reference: number; + compareMask: number; +} + +export class WebGLGFXCommandBuffer extends GFXCommandBuffer { + + public cmdPackage: WebGLCmdPackage = new WebGLCmdPackage(); + private _webGLAllocator: WebGLGFXCommandAllocator | null = null; + private _isInRenderPass: boolean = false; + private _curGPUPipelineState: WebGLGPUPipelineState | null = null; + private _curGPUBindingLayout: WebGLGPUBindingLayout | null = null; + private _curGPUInputAssembler: WebGLGPUInputAssembler | null = null; + private _curViewport: IGFXViewport | null = null; + private _curScissor: IGFXRect | null = null; + private _curLineWidth: number | null = null; + private _curDepthBias: IGFXDepthBias | null = null; + private _curBlendConstants: number[] = []; + private _curDepthBounds: IGFXDepthBounds | null = null; + private _curStencilWriteMask: IGFXStencilWriteMask | null = null; + private _curStencilCompareMask: IGFXStencilCompareMask | null = null; + private _isStateInvalied: boolean = false; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXCommandBufferInfo): boolean { + + if (!info.allocator) { + return false; + } + + this._allocator = info.allocator; + this._webGLAllocator = this._allocator as WebGLGFXCommandAllocator; + this._type = info.type; + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._webGLAllocator) { + this._webGLAllocator!.clearCmds(this.cmdPackage); + this._allocator = null; + this._webGLAllocator = null; + } + this._status = GFXStatus.UNREADY; + } + + public begin () { + this._webGLAllocator!.clearCmds(this.cmdPackage); + this._curGPUPipelineState = null; + this._curGPUBindingLayout = null; + this._curGPUInputAssembler = null; + this._curViewport = null; + this._curScissor = null; + this._curLineWidth = null; + this._curDepthBias = null; + this._curBlendConstants = []; + this._curDepthBounds = null; + this._curStencilWriteMask = null; + this._curStencilCompareMask = null; + } + + public end () { + if (this._isStateInvalied) { + this.bindStates(); + } + + this._isInRenderPass = false; + } + + public beginRenderPass ( + framebuffer: GFXFramebuffer, + renderArea: IGFXRect, + clearColors: IGFXColor[], + clearDepth: number, + clearStencil: number) { + const cmd = this._webGLAllocator!.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); + cmd.gpuFramebuffer = ( framebuffer as WebGLGFXFramebuffer).gpuFramebuffer; + cmd.renderArea = renderArea; + cmd.clearColors = clearColors.slice(); + cmd.clearDepth = clearDepth; + cmd.clearStencil = clearStencil; + this.cmdPackage.beginRenderPassCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS); + + this._isInRenderPass = true; + } + + public endRenderPass () { + this._isInRenderPass = false; + } + + public bindPipelineState (pipelineState: GFXPipelineState) { + const gpuPipelineState = (pipelineState as WebGLGFXPipelineState).gpuPipelineState; + if (this._curGPUPipelineState !== gpuPipelineState) { + this._curGPUPipelineState = gpuPipelineState; + this._isStateInvalied = true; + } + } + + public bindBindingLayout (bindingLayout: GFXBindingLayout) { + const gpuBindingLayout = (bindingLayout as WebGLGFXBindingLayout).gpuBindingLayout; + if (this._curGPUBindingLayout !== gpuBindingLayout) { + this._curGPUBindingLayout = gpuBindingLayout; + this._isStateInvalied = true; + } + } + + public bindInputAssembler (inputAssembler: GFXInputAssembler) { + const gpuInputAssembler = (inputAssembler as WebGLGFXInputAssembler).gpuInputAssembler; + if (this._curGPUInputAssembler !== gpuInputAssembler) { + this._curGPUInputAssembler = gpuInputAssembler; + this._isStateInvalied = true; + } + } + + public setViewport (viewport: IGFXViewport) { + if (!this._curViewport) { + this._curViewport = { + left: viewport.left, + top: viewport.top, + width: viewport.width, + height: viewport.height, + minDepth: viewport.minDepth, + maxDepth: viewport.maxDepth, + }; + } else { + if (this._curViewport.left !== viewport.left || + this._curViewport.top !== viewport.top || + this._curViewport.width !== viewport.width || + this._curViewport.height !== viewport.height || + this._curViewport.minDepth !== viewport.minDepth || + this._curViewport.maxDepth !== viewport.maxDepth) { + + this._curViewport.left = viewport.left; + this._curViewport.top = viewport.top; + this._curViewport.width = viewport.width; + this._curViewport.height = viewport.height; + this._curViewport.minDepth = viewport.minDepth; + this._curViewport.maxDepth = viewport.maxDepth; + this._isStateInvalied = true; + } + } + + if (this._curViewport !== viewport) { + this._curViewport = viewport; + this._isStateInvalied = true; + } + } + + public setScissor (scissor: IGFXRect) { + if (!this._curScissor) { + this._curScissor = { + x: scissor.x, + y: scissor.y, + width: scissor.width, + height: scissor.height, + }; + } else { + if (this._curScissor.x !== scissor.x || + this._curScissor.y !== scissor.y || + this._curScissor.width !== scissor.width || + this._curScissor.height !== scissor.height) { + this._curScissor.x = scissor.x; + this._curScissor.y = scissor.y; + this._curScissor.width = scissor.width; + this._curScissor.height = scissor.height; + this._isStateInvalied = true; + } + } + } + + public setLineWidth (lineWidth: number) { + if (this._curLineWidth !== lineWidth) { + this._curLineWidth = lineWidth; + this._isStateInvalied = true; + } + } + + public setDepthBias (depthBiasConstantFacotr: number, depthBiasClamp: number, depthBiasSlopeFactor: number) { + if (!this._curDepthBias) { + this._curDepthBias = { + constantFactor: depthBiasConstantFacotr, + clamp: depthBiasClamp, + slopeFactor: depthBiasSlopeFactor, + }; + this._isStateInvalied = true; + } else { + if (this._curDepthBias.constantFactor !== depthBiasConstantFacotr || + this._curDepthBias.clamp !== depthBiasClamp || + this._curDepthBias.slopeFactor !== depthBiasSlopeFactor) { + + this._curDepthBias.constantFactor = depthBiasConstantFacotr; + this._curDepthBias.clamp = depthBiasClamp; + this._curDepthBias.slopeFactor = depthBiasSlopeFactor; + this._isStateInvalied = true; + } + } + } + + public setBlendConstants (blendConstants: number[]) { + if (!this._curBlendConstants && + blendConstants.length === 4) { + this._curBlendConstants = [blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]]; + this._isStateInvalied = true; + } else { + if (blendConstants.length === 4 && ( + this._curBlendConstants[0] !== blendConstants[0] || + this._curBlendConstants[1] !== blendConstants[1] || + this._curBlendConstants[2] !== blendConstants[2] || + this._curBlendConstants[3] !== blendConstants[3])) { + this._curBlendConstants = [blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]]; + this._isStateInvalied = true; + } + } + } + + public setDepthBound (minDepthBounds: number, maxDepthBounds: number) { + if (!this._curDepthBounds) { + this._curDepthBounds = { + minBounds: minDepthBounds, + maxBounds: maxDepthBounds, + }; + this._isStateInvalied = true; + } else { + if (this._curDepthBounds.minBounds !== minDepthBounds || + this._curDepthBounds.maxBounds !== maxDepthBounds) { + this._curDepthBounds = { + minBounds: minDepthBounds, + maxBounds: maxDepthBounds, + }; + this._isStateInvalied = true; + } + } + } + + public setStencilWirteMask (face: GFXStencilFace, writeMask: number) { + if (!this._curStencilWriteMask) { + this._curStencilWriteMask = { + face, + writeMask, + }; + this._isStateInvalied = true; + } else { + if (this._curStencilWriteMask.face !== face || + this._curStencilWriteMask.writeMask !== writeMask) { + + this._curStencilWriteMask.face = face; + this._curStencilWriteMask.writeMask = writeMask; + this._isStateInvalied = true; + } + } + } + + public setStencilCompareMask (face: GFXStencilFace, reference: number, compareMask: number) { + if (!this._curStencilCompareMask) { + this._curStencilCompareMask = { + face, + reference, + compareMask, + }; + this._isStateInvalied = true; + } else { + if (this._curStencilCompareMask.face !== face || + this._curStencilCompareMask.reference !== reference || + this._curStencilCompareMask.compareMask !== compareMask) { + + this._curStencilCompareMask.face = face; + this._curStencilCompareMask.reference = reference; + this._curStencilCompareMask.compareMask = compareMask; + this._isStateInvalied = true; + } + } + } + + public draw (inputAssembler: GFXInputAssembler) { + if (this._type === GFXCommandBufferType.PRIMARY && this._isInRenderPass || + this._type === GFXCommandBufferType.SECONDARY) { + if (this._isStateInvalied) { + this.bindStates(); + } + + const cmd = ( this._allocator as WebGLGFXCommandAllocator). + drawCmdPool.alloc(WebGLCmdDraw); + if (cmd) { + (inputAssembler as WebGLGFXInputAssembler).extractCmdDraw(cmd); + this.cmdPackage.drawCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.DRAW); + } + } else { + console.error('Command \'draw\' must be recorded inside a render pass.'); + } + } + + public updateBuffer (buffer: GFXBuffer, data: GFXBufferSource, offset?: number, size?: number) { + if (this._type === GFXCommandBufferType.PRIMARY && !this._isInRenderPass || + this._type === GFXCommandBufferType.SECONDARY) { + const gpuBuffer = (buffer as WebGLGFXBuffer).gpuBuffer; + if (gpuBuffer) { + const cmd = this._webGLAllocator!.updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); + if (cmd) { + + let buffSize; + if (size !== undefined ) { + buffSize = size; + } else if (buffer.usage & GFXBufferUsageBit.INDIRECT) { + buffSize = 0; + } else { + buffSize = (data as ArrayBuffer).byteLength; + } + + const buff = data as ArrayBuffer; + + cmd.gpuBuffer = gpuBuffer; + cmd.buffer = buff; + cmd.offset = (offset !== undefined ? offset : 0); + cmd.size = buffSize; + this.cmdPackage.updateBufferCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); + } + } + } else { + console.error('Command \'updateBuffer\' must be recorded outside a render pass.'); + } + } + + public copyBufferToTexture ( + srcBuff: GFXBuffer, + dstTex: GFXTexture, + dstLayout: GFXTextureLayout, + regions: GFXBufferTextureCopy[]) { + + if (this._type === GFXCommandBufferType.PRIMARY && !this._isInRenderPass || + this._type === GFXCommandBufferType.SECONDARY) { + const gpuBuffer = ( srcBuff as WebGLGFXBuffer).gpuBuffer; + const gpuTexture = ( dstTex as WebGLGFXTexture).gpuTexture; + if (gpuBuffer && gpuTexture) { + const cmd = this._webGLAllocator!.copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); + if (cmd) { + cmd.gpuBuffer = gpuBuffer; + cmd.gpuTexture = gpuTexture; + cmd.dstLayout = dstLayout; + cmd.regions = regions; + this.cmdPackage.copyBufferToTextureCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.COPY_BUFFER_TO_TEXTURE); + } + } + } else { + console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.'); + } + } + + // tslint:disable: max-line-length + public execute (cmdBuffs: GFXCommandBuffer[], count: number) { + + for (let i = 0; i < count; ++i) { + const webGLCmdBuff = cmdBuffs[i] as WebGLGFXCommandBuffer; + + for (let c = 0; c < webGLCmdBuff.cmdPackage.beginRenderPassCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.beginRenderPassCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.beginRenderPassCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.bindStatesCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.bindStatesCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.bindStatesCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.drawCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.drawCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.drawCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.updateBufferCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.updateBufferCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.updateBufferCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.copyBufferToTextureCmds.push(cmd); + } + + this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds); + } + } + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + private bindStates () { + const bindStatesCmd = this._webGLAllocator!.bindStatesCmdPool.alloc(WebGLCmdBindStates); + + if (bindStatesCmd) { + bindStatesCmd.gpuPipelineState = this._curGPUPipelineState; + bindStatesCmd.gpuBindingLayout = this._curGPUBindingLayout; + bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler; + bindStatesCmd.viewport = this._curViewport; + bindStatesCmd.scissor = this._curScissor; + bindStatesCmd.lineWidth = this._curLineWidth; + bindStatesCmd.depthBias = this._curDepthBias; + bindStatesCmd.blendConstants = this._curBlendConstants; + bindStatesCmd.depthBounds = this._curDepthBounds; + bindStatesCmd.stencilWriteMask = this._curStencilWriteMask; + bindStatesCmd.stencilCompareMask = this._curStencilCompareMask; + + this.cmdPackage.bindStatesCmds.push(bindStatesCmd); + this.cmdPackage.cmds.push(WebGLCmd.BIND_STATES); + + this._isStateInvalied = false; + } + } +} diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts new file mode 100644 index 0000000000..cc02069999 --- /dev/null +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -0,0 +1,2306 @@ +import { CachedArray } from '../../core/memop/cached-array'; +import { GFXBufferSource, IGFXDrawInfo, IGFXIndirectBuffer } from '../buffer'; +import { + GFXBindingType, + GFXBufferTextureCopy, + GFXBufferUsageBit, + GFXColorMask, + GFXCullMode, + GFXDynamicState, + GFXFormat, + GFXFormatInfos, + GFXFormatSize, + GFXLoadOp, + GFXMemoryUsageBit, + GFXShaderType, + GFXStencilFace, + GFXTextureFlagBit, + GFXTextureLayout, + GFXTextureViewType, + GFXType, + IGFXColor, + IGFXFormatInfo, + IGFXRect, + IGFXViewport, + WebGLEXT, +} from '../define'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { IGFXDepthBias, IGFXDepthBounds, IGFXStencilCompareMask, IGFXStencilWriteMask } from './webgl-command-buffer'; +import { WebGLGFXDevice } from './webgl-device'; +import { IWebGLGPUUniform, WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, + WebGLGPUFramebuffer, WebGLGPUInput, WebGLGPUInputAssembler, WebGLGPUPipelineState, + WebGLGPUShader, WebGLGPUTexture, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects'; +import { IWebGLTexUnit } from './webgl-state-cache'; + +const _uniformValues = new Array(1024 * 4); + +// tslint:disable: max-line-length + +function CmpF32NotEuqal (a: number, b: number): boolean { + const c = a - b; + return (c > 0.000001 || c < -0.000001); +} + +function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenum { + switch (format) { + case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.R8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.R8I: return WebGLRenderingContext.BYTE; + case GFXFormat.R16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; + case GFXFormat.R16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.R16I: return WebGLRenderingContext.SHORT; + case GFXFormat.R32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.R32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.R32I: return WebGLRenderingContext.INT; + + case GFXFormat.RG8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RG8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.RG8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RG8I: return WebGLRenderingContext.BYTE; + case GFXFormat.RG16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; + case GFXFormat.RG16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.RG16I: return WebGLRenderingContext.SHORT; + case GFXFormat.RG32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RG32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RG32I: return WebGLRenderingContext.INT; + + case GFXFormat.RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.SRGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGB8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.RGB8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGB8I: return WebGLRenderingContext.BYTE; + case GFXFormat.RGB16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; + case GFXFormat.RGB16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.RGB16I: return WebGLRenderingContext.SHORT; + case GFXFormat.RGB32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGB32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGB32I: return WebGLRenderingContext.INT; + + case GFXFormat.RGBA8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.SRGB8_A8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGBA8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.RGBA8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGBA8I: return WebGLRenderingContext.BYTE; + case GFXFormat.RGBA16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; + case GFXFormat.RGBA16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.RGBA16I: return WebGLRenderingContext.SHORT; + case GFXFormat.RGBA32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGBA32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGBA32I: return WebGLRenderingContext.INT; + + case GFXFormat.R5G6B5: return WebGLRenderingContext.UNSIGNED_SHORT_5_6_5; + case GFXFormat.R11G11B10F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGB5A1: return WebGLRenderingContext.UNSIGNED_SHORT_5_5_5_1; + case GFXFormat.RGBA4: return WebGLRenderingContext.UNSIGNED_SHORT_4_4_4_4; + case GFXFormat.RGB10A2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGB10A2UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGB9E5: return WebGLRenderingContext.UNSIGNED_BYTE; + + case GFXFormat.D16: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.D16S8: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.D24: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.D24S8: return device.WEBGL_depth_texture ? device.WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL : WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.D32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.D32F_S8: return WebGLRenderingContext.FLOAT; + + case GFXFormat.BC1: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC1_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC2_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC3: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC3_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC4: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC4_SNORM: return WebGLRenderingContext.BYTE; + case GFXFormat.BC5: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC5_SNORM: return WebGLRenderingContext.BYTE; + case GFXFormat.BC6H_SF16: return WebGLRenderingContext.FLOAT; + case GFXFormat.BC6H_UF16: return WebGLRenderingContext.FLOAT; + case GFXFormat.BC7: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC7_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + + case GFXFormat.ETC_RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_SRGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_RGB8_A1: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_SRGB8_A1: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_SRGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.EAC_R11: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.EAC_R11SN: return WebGLRenderingContext.BYTE; + case GFXFormat.EAC_RG11: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.EAC_RG11SN: return WebGLRenderingContext.BYTE; + + case GFXFormat.PVRTC_RGB2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC_RGBA2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC_RGB4: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC_RGBA4: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC2_2BPP: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC2_4BPP: return WebGLRenderingContext.UNSIGNED_BYTE; + + default: { + return WebGLRenderingContext.UNSIGNED_BYTE; + } + } +} + +function GFXFormatToWebGLInternalFormat (format: GFXFormat): GLenum { + switch (format) { + case GFXFormat.A8: return WebGLRenderingContext.ALPHA; + case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; + case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; + case GFXFormat.RGB8: return WebGLRenderingContext.RGB; + case GFXFormat.RGB16F: return WebGLRenderingContext.RGB; + case GFXFormat.RGB32F: return WebGLRenderingContext.RGB; + case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA16F: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA32F: return WebGLRenderingContext.RGBA; + case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB565; + case GFXFormat.RGB5A1: return WebGLRenderingContext.RGB5_A1; + case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA4; + case GFXFormat.D16: return WebGLRenderingContext.DEPTH_COMPONENT16; + case GFXFormat.D16S8: return WebGLRenderingContext.DEPTH_STENCIL; + case GFXFormat.D24: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D24S8: return WebGLRenderingContext.DEPTH_STENCIL; + case GFXFormat.D32F: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D32F_S8: return WebGLRenderingContext.DEPTH_STENCIL; + + case GFXFormat.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case GFXFormat.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case GFXFormat.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case GFXFormat.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + + case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case GFXFormat.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + + default: { + console.error('Unsupported GFXFormat, convert to WebGL internal format failed.'); + return WebGLRenderingContext.RGBA; + } + } +} + +function GFXFormatToWebGLFormat (format: GFXFormat): GLenum { + switch (format) { + case GFXFormat.A8: return WebGLRenderingContext.ALPHA; + case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; + case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; + case GFXFormat.RGB8: return WebGLRenderingContext.RGB; + case GFXFormat.RGB16F: return WebGLRenderingContext.RGB; + case GFXFormat.RGB32F: return WebGLRenderingContext.RGB; + case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA16F: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA32F: return WebGLRenderingContext.RGBA; + case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB; + case GFXFormat.RGB5A1: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA; + case GFXFormat.D16: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D16S8: return WebGLRenderingContext.DEPTH_STENCIL; + case GFXFormat.D24: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D24S8: return WebGLRenderingContext.DEPTH_STENCIL; + case GFXFormat.D32F: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D32F_S8: return WebGLRenderingContext.DEPTH_STENCIL; + + case GFXFormat.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case GFXFormat.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case GFXFormat.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case GFXFormat.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + + case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case GFXFormat.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + + default: { + console.error('Unsupported GFXFormat, convert to WebGL format failed.'); + return WebGLRenderingContext.RGBA; + } + } +} + +function GFXTypeToWebGLType (type: GFXType): GLenum { + switch (type) { + case GFXType.BOOL: return WebGLRenderingContext.BOOL; + case GFXType.BOOL2: return WebGLRenderingContext.BOOL_VEC2; + case GFXType.BOOL3: return WebGLRenderingContext.BOOL_VEC3; + case GFXType.BOOL4: return WebGLRenderingContext.BOOL_VEC4; + case GFXType.INT: return WebGLRenderingContext.INT; + case GFXType.INT2: return WebGLRenderingContext.INT_VEC2; + case GFXType.INT3: return WebGLRenderingContext.INT_VEC3; + case GFXType.INT4: return WebGLRenderingContext.INT_VEC4; + case GFXType.UINT: return WebGLRenderingContext.UNSIGNED_INT; + case GFXType.FLOAT: return WebGLRenderingContext.FLOAT; + case GFXType.FLOAT2: return WebGLRenderingContext.FLOAT_VEC2; + case GFXType.FLOAT3: return WebGLRenderingContext.FLOAT_VEC3; + case GFXType.FLOAT4: return WebGLRenderingContext.FLOAT_VEC4; + case GFXType.COLOR4: return WebGLRenderingContext.FLOAT_VEC4; + case GFXType.MAT2: return WebGLRenderingContext.FLOAT_MAT2; + case GFXType.MAT3: return WebGLRenderingContext.FLOAT_MAT3; + case GFXType.MAT4: return WebGLRenderingContext.FLOAT_MAT4; + case GFXType.SAMPLER2D: return WebGLRenderingContext.SAMPLER_2D; + case GFXType.SAMPLER_CUBE: return WebGLRenderingContext.SAMPLER_CUBE; + default: { + console.error('Unsupported GLType, convert to GL type failed.'); + return GFXType.UNKNOWN; + } + } +} + +function WebGLTypeToGFXType (glType: GLenum): GFXType { + switch (glType) { + case WebGLRenderingContext.BOOL: return GFXType.BOOL; + case WebGLRenderingContext.BOOL_VEC2: return GFXType.BOOL2; + case WebGLRenderingContext.BOOL_VEC3: return GFXType.BOOL3; + case WebGLRenderingContext.BOOL_VEC4: return GFXType.BOOL4; + case WebGLRenderingContext.INT: return GFXType.INT; + case WebGLRenderingContext.INT_VEC2: return GFXType.INT2; + case WebGLRenderingContext.INT_VEC3: return GFXType.INT3; + case WebGLRenderingContext.INT_VEC4: return GFXType.INT4; + case WebGLRenderingContext.UNSIGNED_INT: return GFXType.UINT; + case WebGLRenderingContext.FLOAT: return GFXType.FLOAT; + case WebGLRenderingContext.FLOAT_VEC2: return GFXType.FLOAT2; + case WebGLRenderingContext.FLOAT_VEC3: return GFXType.FLOAT3; + case WebGLRenderingContext.FLOAT_VEC4: return GFXType.FLOAT4; + case WebGLRenderingContext.FLOAT_MAT2: return GFXType.MAT2; + case WebGLRenderingContext.FLOAT_MAT3: return GFXType.MAT3; + case WebGLRenderingContext.FLOAT_MAT4: return GFXType.MAT4; + case WebGLRenderingContext.SAMPLER_2D: return GFXType.SAMPLER2D; + case WebGLRenderingContext.SAMPLER_CUBE: return GFXType.SAMPLER_CUBE; + default: { + console.error('Unsupported GLType, convert to GFXType failed.'); + return GFXType.UNKNOWN; + } + } +} + +function WebGLGetTypeSize (glType: GLenum): GFXType { + switch (glType) { + case WebGLRenderingContext.BOOL: return 4; + case WebGLRenderingContext.BOOL_VEC2: return 8; + case WebGLRenderingContext.BOOL_VEC3: return 12; + case WebGLRenderingContext.BOOL_VEC4: return 16; + case WebGLRenderingContext.INT: return 4; + case WebGLRenderingContext.INT_VEC2: return 8; + case WebGLRenderingContext.INT_VEC3: return 12; + case WebGLRenderingContext.INT_VEC4: return 16; + case WebGLRenderingContext.UNSIGNED_INT: return 4; + case WebGLRenderingContext.FLOAT: return 4; + case WebGLRenderingContext.FLOAT_VEC2: return 8; + case WebGLRenderingContext.FLOAT_VEC3: return 12; + case WebGLRenderingContext.FLOAT_VEC4: return 16; + case WebGLRenderingContext.FLOAT_MAT2: return 16; + case WebGLRenderingContext.FLOAT_MAT3: return 36; + case WebGLRenderingContext.FLOAT_MAT4: return 64; + case WebGLRenderingContext.SAMPLER_2D: return 4; + case WebGLRenderingContext.SAMPLER_CUBE: return 4; + default: { + console.error('Unsupported GLType, get type failed.'); + return 0; + } + } +} + +function WebGLGetComponentCount (glType: GLenum): GFXType { + switch (glType) { + case WebGLRenderingContext.FLOAT_MAT2: return 2; + case WebGLRenderingContext.FLOAT_MAT3: return 3; + case WebGLRenderingContext.FLOAT_MAT4: return 4; + default: { + return 1; + } + } +} + +const WebGLCmpFuncs: GLenum[] = [ + WebGLRenderingContext.NEVER, + WebGLRenderingContext.LESS, + WebGLRenderingContext.EQUAL, + WebGLRenderingContext.LEQUAL, + WebGLRenderingContext.GREATER, + WebGLRenderingContext.NOTEQUAL, + WebGLRenderingContext.GEQUAL, + WebGLRenderingContext.ALWAYS, +]; + +const WebGLStencilOps: GLenum[] = [ + WebGLRenderingContext.KEEP, + WebGLRenderingContext.ZERO, + WebGLRenderingContext.REPLACE, + WebGLRenderingContext.INCR, + WebGLRenderingContext.DECR, + WebGLRenderingContext.INVERT, + WebGLRenderingContext.INCR_WRAP, + WebGLRenderingContext.DECR_WRAP, +]; + +const WebGLBlendOps: GLenum[] = [ + WebGLRenderingContext.FUNC_ADD, + WebGLRenderingContext.FUNC_SUBTRACT, + WebGLRenderingContext.FUNC_REVERSE_SUBTRACT, + WebGLRenderingContext.FUNC_ADD, + WebGLRenderingContext.FUNC_ADD, +]; + +const WebGLBlendFactors: GLenum[] = [ + WebGLRenderingContext.ZERO, + WebGLRenderingContext.ONE, + WebGLRenderingContext.SRC_ALPHA, + WebGLRenderingContext.DST_ALPHA, + WebGLRenderingContext.ONE_MINUS_SRC_ALPHA, + WebGLRenderingContext.ONE_MINUS_DST_ALPHA, + WebGLRenderingContext.SRC_COLOR, + WebGLRenderingContext.DST_COLOR, + WebGLRenderingContext.SRC_ALPHA_SATURATE, + WebGLRenderingContext.CONSTANT_COLOR, + WebGLRenderingContext.ONE_MINUS_CONSTANT_COLOR, + WebGLRenderingContext.CONSTANT_ALPHA, + WebGLRenderingContext.ONE_MINUS_CONSTANT_ALPHA, +]; + +export enum WebGLCmd { + BEGIN_RENDER_PASS, + END_RENDER_PASS, + BIND_STATES, + DRAW, + UPDATE_BUFFER, + COPY_BUFFER_TO_TEXTURE, + COUNT, +} + +export abstract class WebGLCmdObject { + public cmdType: WebGLCmd; + public refCount: number = 0; + + constructor (type: WebGLCmd) { + this.cmdType = type; + } + + public abstract clear (); +} + +export class WebGLCmdBeginRenderPass extends WebGLCmdObject { + + public gpuFramebuffer: WebGLGPUFramebuffer | null = null; + public renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 }; + public clearColors: IGFXColor[] = []; + public clearDepth: number = 1.0; + public clearStencil: number = 0; + + constructor () { + super(WebGLCmd.BEGIN_RENDER_PASS); + } + + public clear () { + this.gpuFramebuffer = null; + this.clearColors = []; + } +} + +export class WebGLCmdBindStates extends WebGLCmdObject { + + public gpuPipelineState: WebGLGPUPipelineState | null = null; + public gpuBindingLayout: WebGLGPUBindingLayout | null = null; + public gpuInputAssembler: WebGLGPUInputAssembler | null = null; + public viewport: IGFXViewport | null = null; + public scissor: IGFXRect | null = null; + public lineWidth: number | null = null; + public depthBias: IGFXDepthBias | null = null; + public blendConstants: number[] | null = null; + public depthBounds: IGFXDepthBounds | null = null; + public stencilWriteMask: IGFXStencilWriteMask | null = null; + public stencilCompareMask: IGFXStencilCompareMask | null = null; + + constructor () { + super(WebGLCmd.BIND_STATES); + } + + public clear () { + this.gpuPipelineState = null; + this.gpuBindingLayout = null; + this.gpuInputAssembler = null; + this.viewport = null; + this.scissor = null; + this.lineWidth = null; + this.depthBias = null; + this.blendConstants = null; + this.depthBounds = null; + this.stencilWriteMask = null; + this.stencilCompareMask = null; + } +} + +export class WebGLCmdDraw extends WebGLCmdObject { + + public drawInfo: IGFXDrawInfo = { + vertexCount: 0, + firstVertex: 0, + indexCount: 0, + firstIndex: 0, + vertexOffset: 0, + instanceCount: 0, + firstInstance: 0, + }; + + constructor () { + super(WebGLCmd.DRAW); + } + + public clear () { + } +} + +export class WebGLCmdUpdateBuffer extends WebGLCmdObject { + + public gpuBuffer: WebGLGPUBuffer | null = null; + public buffer: GFXBufferSource | null = null; + public offset: number = 0; + public size: number = 0; + + constructor () { + super(WebGLCmd.UPDATE_BUFFER); + } + + public clear () { + this.gpuBuffer = null; + this.buffer = null; + } +} + +export class WebGLGFXTextureSubres { + public baseMipLevel: number = 0; + public levelCount: number = 1; + public baseArrayLayer: number = 0; + public layerCount: number = 1; +} + +export class WebGLGFXBufferTextureCopy { + public buffOffset: number = 0; + public buffStride: number = 0; + public buffTexHeight: number = 0; + public texOffset: number[] = [0, 0, 0]; + public texExtent: number[] = [0, 0, 0]; + public texSubres: WebGLGFXTextureSubres = new WebGLGFXTextureSubres(); +} + +export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { + + public gpuBuffer: WebGLGPUBuffer | null = null; + public gpuTexture: WebGLGPUTexture | null = null; + public dstLayout: GFXTextureLayout | null = null; + public regions: GFXBufferTextureCopy[] = []; + + constructor () { + super(WebGLCmd.COPY_BUFFER_TO_TEXTURE); + } + + public clear () { + this.gpuBuffer = null; + this.gpuTexture = null; + this.dstLayout = null; + this.regions = []; + } +} + +export class WebGLCmdPackage { + public cmds: CachedArray = new CachedArray(1); + public beginRenderPassCmds: CachedArray = new CachedArray(1); + public bindStatesCmds: CachedArray = new CachedArray(1); + public drawCmds: CachedArray = new CachedArray(1); + public updateBufferCmds: CachedArray = new CachedArray(1); + public copyBufferToTextureCmds: CachedArray = new CachedArray(1); + + public clearCmds (allocator: WebGLGFXCommandAllocator) { + + if (this.beginRenderPassCmds.length) { + allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds); + this.beginRenderPassCmds.clear(); + } + + if (this.bindStatesCmds.length) { + allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds); + this.bindStatesCmds.clear(); + } + + if (this.drawCmds.length) { + allocator.drawCmdPool.freeCmds(this.drawCmds); + this.drawCmds.clear(); + } + + if (this.updateBufferCmds.length) { + allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds); + this.updateBufferCmds.clear(); + } + + if (this.copyBufferToTextureCmds.length) { + allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds); + this.copyBufferToTextureCmds.clear(); + } + + this.cmds.clear(); + } +} + +export function WebGLCmdFuncCreateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { + + const gl = device.gl; + + if (gpuBuffer.usage & GFXBufferUsageBit.VERTEX) { + + gpuBuffer.glTarget = WebGLRenderingContext.ARRAY_BUFFER; + const glBuffer = gl.createBuffer(); + if (glBuffer) { + gpuBuffer.glBuffer = glBuffer; + + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; + } + + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); + device.stateCache.glArrayBuffer = 0; + } + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDEX) { + + gpuBuffer.glTarget = WebGLRenderingContext.ELEMENT_ARRAY_BUFFER; + const glBuffer = gl.createBuffer(); + if (glBuffer) { + gpuBuffer.glBuffer = glBuffer; + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); + device.stateCache.glElementArrayBuffer = 0; + } + } else if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { + // console.error("WebGL 1.0 doesn't support uniform buffer."); + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + + if (gpuBuffer.buffer) { + gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer as ArrayBuffer); + } + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_DST) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else { + console.error('Unsupported GFXBufferType, create buffer failed.'); + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } +} + +export function WebGLCmdFuncDestroyBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { + if (gpuBuffer.glBuffer > 0) { + device.gl.deleteBuffer(gpuBuffer.glBuffer); + gpuBuffer.glBuffer = 0; + } +} + +export function WebGLCmdFuncResizeBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { + + const gl = device.gl; + + if (gpuBuffer.usage & GFXBufferUsageBit.VERTEX) { + + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); + } + + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); + device.stateCache.glArrayBuffer = 0; + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDEX) { + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + } + + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); + device.stateCache.glElementArrayBuffer = 0; + } else if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { + // console.error("WebGL 1.0 doesn't support uniform buffer."); + if (gpuBuffer.buffer) { + gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer as ArrayBuffer); + } + } else if ((gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) || + (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_DST) || + (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC)) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else { + console.error('Unsupported GFXBufferType, create buffer failed.'); + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } +} + +export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { + + if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { + gpuBuffer.vf32!.set(buffer as Float32Array, offset); + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) { + gpuBuffer.indirects = (buffer as IGFXIndirectBuffer).drawInfos; + } else { + const buff = buffer as ArrayBuffer; + const gl = device.gl; + + switch (gpuBuffer.glTarget) { + case WebGLRenderingContext.ARRAY_BUFFER: { + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; + } + + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); + } else { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); + } + + break; + } + case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); + } else { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); + } + + break; + } + default: { + console.error('Unsupported GFXBufferType, update buffer failed.'); + } + } + } +} + +export function WebGLCmdFuncCreateTexture (device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { + + const gl = device.gl; + + gpuTexture.glInternelFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format); + gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format); + gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format, device); + + switch (gpuTexture.viewType) { + case GFXTextureViewType.TV2D: { + + gpuTexture.viewType = GFXTextureViewType.TV2D; + gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; + + const glTexture = gl.createTexture(); + if (glTexture) { + gpuTexture.glTexture = glTexture; + const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + let w = gpuTexture.width; + let h = gpuTexture.height; + + if (!GFXFormatInfos[gpuTexture.format].isCompressed) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(WebGLRenderingContext.TEXTURE_2D, i, gpuTexture.glInternelFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } else { + const view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_2D, i, gpuTexture.glInternelFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } + + break; + } + case GFXTextureViewType.CUBE: { + + gpuTexture.viewType = GFXTextureViewType.CUBE; + gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_CUBE_MAP; + + const glTexture = gl.createTexture(); + if (glTexture) { + gpuTexture.glTexture = glTexture; + const glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + if (!GFXFormatInfos[gpuTexture.format].isCompressed) { + for (let f = 0; f < 6; ++f) { + let w = gpuTexture.width; + let h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } else { + const view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; + + for (let f = 0; f < 6; ++f) { + let w = gpuTexture.width; + let h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } + } + + break; + } + default: { + console.error('Unsupported GFXTextureType, create texture failed.'); + gpuTexture.viewType = GFXTextureViewType.TV2D; + gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; + } + } +} + +export function WebGLCmdFuncDestroyTexture (device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { + if (gpuTexture.glTexture > 0) { + device.gl.deleteTexture(gpuTexture.glTexture); + gpuTexture.glTexture = 0; + } +} + +export function WebGLCmdFuncCreateFramebuffer (device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { + + if (!gpuFramebuffer.isOffscreen) { + + const gl = device.gl; + + const glFramebuffer = gl.createFramebuffer(); + if (glFramebuffer) { + gpuFramebuffer.glFramebuffer = glFramebuffer; + + if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); + device.stateCache.glFramebuffer = gpuFramebuffer.glFramebuffer; + } + + for (let i = 0; i < gpuFramebuffer.gpuColorViews.length; ++i) { + + const gpuColorView = gpuFramebuffer.gpuColorViews[i]; + if (gpuColorView) { + gl.framebufferTexture2D( + WebGLRenderingContext.FRAMEBUFFER, + WebGLRenderingContext.COLOR_ATTACHMENT0 + i, + gpuColorView.gpuTexture.glTarget, + gpuColorView.gpuTexture.glTexture, + gpuColorView.baseLevel); + } + } + + if (gpuFramebuffer.gpuDepthStencilView) { + + const glAttachment = GFXFormatInfos[gpuFramebuffer.gpuDepthStencilView.format].hasStencil ? + WebGLRenderingContext.DEPTH_STENCIL_ATTACHMENT : WebGLRenderingContext.DEPTH_ATTACHMENT; + + gl.framebufferTexture2D( + WebGLRenderingContext.FRAMEBUFFER, + glAttachment, + gpuFramebuffer.gpuDepthStencilView.gpuTexture.glTarget, + gpuFramebuffer.gpuDepthStencilView.gpuTexture.glTexture, + gpuFramebuffer.gpuDepthStencilView.baseLevel); + } + + /* + const status = gl.checkFramebufferStatus(WebGLRenderingContext.FRAMEBUFFER); + if (status !== WebGLRenderingContext.FRAMEBUFFER_COMPLETE) { + switch (status) { + case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); + break; + } + case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); + break; + } + case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); + break; + } + case WebGLRenderingContext.FRAMEBUFFER_UNSUPPORTED: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); + break; + } + default: + } + } + */ + } + } +} + +export function WebGLCmdFuncDestroyFramebuffer (device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { + if (gpuFramebuffer.glFramebuffer > 0) { + device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer); + gpuFramebuffer.glFramebuffer = 0; + } +} + +export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { + const gl = device.gl; + + for (const gpuStage of gpuShader.gpuStages) { + + let glShaderType: GLenum = 0; + let shaderTypeStr = ''; + + switch (gpuStage.type) { + case GFXShaderType.VERTEX: { + shaderTypeStr = 'VertexShader'; + glShaderType = WebGLRenderingContext.VERTEX_SHADER; + break; + } + case GFXShaderType.FRAGMENT: { + shaderTypeStr = 'FragmentShader'; + glShaderType = WebGLRenderingContext.FRAGMENT_SHADER; + break; + } + default: { + console.error('Unsupported GFXShaderType.'); + return; + } + } + + const glShader = gl.createShader(glShaderType); + if (glShader) { + gpuStage.glShader = glShader; + gl.shaderSource(gpuStage.glShader, gpuStage.source); + gl.compileShader(gpuStage.glShader); + + if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { + console.error(shaderTypeStr + ' in \'' + gpuShader.name + '\' compilation failed.'); + console.error(gpuStage.source); + console.error(gl.getShaderInfoLog(gpuStage.glShader)); + + gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = 0; + } + } + } + + const glProgram = gl.createProgram(); + if (!glProgram) { + return; + } + + gpuShader.glProgram = glProgram; + + // link program + for (const gpuStage of gpuShader.gpuStages) { + gl.attachShader(gpuShader.glProgram, gpuStage.glShader); + } + + gl.linkProgram(gpuShader.glProgram); + if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { + console.info('Shader \'' + gpuShader.name + '\' compilation successed.'); + } else { + console.error('Failed to link shader \'' + gpuShader.name + '\'.'); + console.error(gl.getProgramInfoLog(gpuShader.glProgram)); + + for (const gpuStage of gpuShader.gpuStages) { + if (gpuStage.glShader > 0) { + gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = 0; + } + } + } + + // parse inputs + const activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); + gpuShader.glInputs = new Array(activeAttribCount); + + for (let i = 0; i < activeAttribCount; ++i) { + const attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i); + if (attribInfo) { + let varName: string; + const nameOffset = attribInfo.name.indexOf('['); + if (nameOffset !== -1) { + varName = attribInfo.name.substr(0, nameOffset); + } else { + varName = attribInfo.name; + } + + const glLoc = gl.getAttribLocation(gpuShader.glProgram, varName); + const type = WebGLTypeToGFXType(attribInfo.type); + const stride = WebGLGetTypeSize(attribInfo.type); + + gpuShader.glInputs[i] = { + binding: glLoc, + name: varName, + type, + stride, + count: attribInfo.size, + size: stride * attribInfo.size, + + glType: attribInfo.type, + glLoc, + }; + } + } + + // create uniform blocks + if (gpuShader.blocks.length > 0) { + gpuShader.glBlocks = new Array(gpuShader.blocks.length); + for (let i = 0; i < gpuShader.blocks.length; ++i) { + const block = gpuShader.blocks[i]; + + const glBlock: WebGLGPUUniformBlock = { + binding: block.binding, + name: block.name, + size: 0, + glUniforms: new Array(block.members.length), + glActiveUniforms: [], + isUniformPackage: true, + }; + + gpuShader.glBlocks[i] = glBlock; + + for (let u = 0; u < block.members.length; ++u) { + const uniform = block.members[u]; + const glType = GFXTypeToWebGLType(uniform.type); + const stride = WebGLGetTypeSize(glType); + const size = stride * uniform.count; + const begin = glBlock.size / 4; + const count = size / 4; + const array = new Array(count); + array.fill(0); + + glBlock.glUniforms[u] = { + binding: -1, + name: uniform.name, + type: uniform.type, + stride, + count: uniform.count, + size, + offset: glBlock.size, + + glType, + glLoc: -1, + array, + begin, + isFirst: true, + }; + + glBlock.size += size; + } + + /* + glBlock.buffer = new ArrayBuffer(glBlock.size); + + for (const glUniform of glBlock.glUniforms) { + switch (glUniform.glType) { + case gl.BOOL: + case gl.BOOL_VEC2: + case gl.BOOL_VEC3: + case gl.BOOL_VEC4: + case gl.INT: + case gl.INT_VEC2: + case gl.INT_VEC3: + case gl.INT_VEC4: + case gl.SAMPLER_2D: + case gl.SAMPLER_CUBE: { + glUniform.vi32 = new Int32Array(glBlock.buffer); + break; + } + default: { + glUniform.vf32 = new Float32Array(glBlock.buffer); + } + } + } + */ + } + } + + // create uniform samplers + if (gpuShader.samplers.length > 0) { + gpuShader.glSamplers = new Array(gpuShader.samplers.length); + + for (let i = 0; i < gpuShader.samplers.length; ++i) { + const sampler = gpuShader.samplers[i]; + gpuShader.glSamplers[i] = { + binding: sampler.binding, + name: sampler.name, + type: sampler.type, + units: [], + glType: GFXTypeToWebGLType(sampler.type), + glLoc: -1, + }; + } + } + + // parse uniforms + const activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS); + let unitIdx = 0; + + const glActiveSamplers: WebGLGPUUniformSampler[] = []; + + for (let i = 0; i < activeUniformCount; ++i) { + const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); + if (uniformInfo) { + const glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name); + if (glLoc) { + let varName: string; + const nameOffset = uniformInfo.name.indexOf('['); + if (nameOffset !== -1) { + varName = uniformInfo.name.substr(0, nameOffset); + } else { + varName = uniformInfo.name; + } + + const isSampler = (uniformInfo.type === WebGLRenderingContext.SAMPLER_2D) || + (uniformInfo.type === WebGLRenderingContext.SAMPLER_CUBE); + + if (!isSampler) { + // let stride = WebGLGetTypeSize(info.type); + + // build uniform block mapping + for (const glBlock of gpuShader.glBlocks) { + + for (const glUniform of glBlock.glUniforms) { + if (glUniform.name === varName) { + // let varSize = stride * info.size; + + glUniform.glLoc = glLoc; + glBlock.glActiveUniforms.push(glUniform); + + break; + } + } + } // for + } else { + + for (const glSampler of gpuShader.glSamplers) { + if (glSampler.name === varName) { + // let varSize = stride * uniformInfo.size; + + for (let t = 0; t < uniformInfo.size; ++t) { + glSampler.units.push(unitIdx + t); + } + + glSampler.glLoc = glLoc; + + unitIdx += uniformInfo.size; + glActiveSamplers.push(glSampler); + + break; + } + } // for + } + } + } + } // for + + if (glActiveSamplers.length) { + if (device.stateCache.glProgram !== gpuShader.glProgram) { + gl.useProgram(gpuShader.glProgram); + device.stateCache.glProgram = gpuShader.glProgram; + } + + for (const glSampler of glActiveSamplers) { + gl.uniform1iv(glSampler.glLoc, glSampler.units); + } + } +} + +export function WebGLCmdFuncDestroyShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { + + for (const gpuStage of gpuShader.gpuStages) { + if (gpuStage.glShader > 0) { + device.gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = 0; + } + } + + if (gpuShader.glProgram > 0) { + device.gl.deleteProgram(gpuShader.glProgram); + gpuShader.glProgram = 0; + } +} + +export function WebGLCmdFuncCreateInputAssember (device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { + + gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length); + + const offsets = [0, 0, 0, 0, 0, 0, 0, 0]; + + for (let i = 0; i < gpuInputAssembler.attributes.length; ++i) { + const attrib = gpuInputAssembler.attributes[i]; + + const stream = attrib.stream !== undefined ? attrib.stream : 0; + // if (stream < gpuInputAssembler.gpuVertexBuffers.length) { + + const gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; + + const glType = GFXFormatToWebGLType(attrib.format, device); + const size = GFXFormatInfos[attrib.format].size; + + gpuInputAssembler.glAttribs[i] = { + name: attrib.name, + glBuffer: gpuBuffer.glBuffer, + glType, + size, + count: GFXFormatInfos[attrib.format].count, + stride: gpuBuffer.stride, + componentCount: WebGLGetComponentCount(glType), + isNormalized: (attrib.isNormalized !== undefined ? attrib.isNormalized : false), + isInstanced: (attrib.isInstanced !== undefined ? attrib.isInstanced : false), + offset: offsets[stream], + }; + + offsets[stream] += size; + } +} + +export function WebGLCmdFuncDestroyInputAssembler (device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { +} + +export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { + + const gl = device.gl; + const cmdIds = [0, 0, 0, 0, 0, 0]; // 6 + + let gpuPipelineState: WebGLGPUPipelineState | null = null; + let gpuShader: WebGLGPUShader | null = null; + let gpuInputAssembler: WebGLGPUInputAssembler | null = null; + let glPrimitive = WebGLRenderingContext.TRIANGLES; + + for (let i = 0; i < cmdPackage.cmds.length; ++i) { + const cmd = cmdPackage.cmds.array[i]; + const cmdId = cmdIds[cmd]++; + + switch (cmd) { + case WebGLCmd.BEGIN_RENDER_PASS: { + const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; + + let clears: GLbitfield = 0; + + if (cmd0.gpuFramebuffer) { + if (device.stateCache.glFramebuffer !== cmd0.gpuFramebuffer.glFramebuffer) { + const glFBO = (cmd0.gpuFramebuffer.glFramebuffer !== 0 ? cmd0.gpuFramebuffer.glFramebuffer : null); + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, glFBO); + device.stateCache.glFramebuffer = cmd0.gpuFramebuffer.glFramebuffer; + } + + if (device.stateCache.viewport.left !== cmd0.renderArea.x || + device.stateCache.viewport.top !== cmd0.renderArea.y || + device.stateCache.viewport.width !== cmd0.renderArea.width || + device.stateCache.viewport.height !== cmd0.renderArea.height) { + + gl.viewport(cmd0.renderArea.x, cmd0.renderArea.y, cmd0.renderArea.width, cmd0.renderArea.height); + + device.stateCache.viewport.left = cmd0.renderArea.x; + device.stateCache.viewport.top = cmd0.renderArea.y; + device.stateCache.viewport.width = cmd0.renderArea.width; + device.stateCache.viewport.height = cmd0.renderArea.height; + } + + if (device.stateCache.scissorRect.x !== cmd0.renderArea.x || + device.stateCache.scissorRect.y !== cmd0.renderArea.y || + device.stateCache.scissorRect.width !== cmd0.renderArea.width || + device.stateCache.scissorRect.height !== cmd0.renderArea.height) { + + gl.scissor(cmd0.renderArea.x, cmd0.renderArea.y, cmd0.renderArea.width, cmd0.renderArea.height); + + device.stateCache.scissorRect.x = cmd0.renderArea.x; + device.stateCache.scissorRect.y = cmd0.renderArea.y; + device.stateCache.scissorRect.width = cmd0.renderArea.width; + device.stateCache.scissorRect.height = cmd0.renderArea.height; + } + + const curGPURenderPass = cmd0.gpuFramebuffer.gpuRenderPass; + + const invalidateAttachments: GLenum[] = [0, 0, 0, 0]; + let numInvalidAttach = 0; + + if (curGPURenderPass.colorAttachments.length > 0 && cmd0.clearColors.length) { + const colorAttachment = curGPURenderPass.colorAttachments[0]; + + if (colorAttachment.format !== GFXFormat.UNKNOWN) { + switch (colorAttachment.loadOp) { + case GFXLoadOp.LOAD: break; // GL default behaviour + case GFXLoadOp.CLEAR: { + + if (device.stateCache.bs.targets[0].blendColorMask !== GFXColorMask.ALL) { + gl.colorMask(true, true, true, true); + } + + const clearColor = cmd0.clearColors[0]; + gl.clearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); + clears |= WebGLRenderingContext.COLOR_BUFFER_BIT; + + break; + } + case GFXLoadOp.DISCARD: { + // invalidate the framebuffer + invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.COLOR_ATTACHMENT0; + break; + } + default: + } + } + } // if (curGPURenderPass) + + if (curGPURenderPass.depthStencilAttachment) { + + if (curGPURenderPass.depthStencilAttachment.format !== GFXFormat.UNKNOWN) { + switch (curGPURenderPass.depthStencilAttachment.depthLoadOp) { + case GFXLoadOp.LOAD: break; // GL default behaviour + case GFXLoadOp.CLEAR: { + + if (!device.stateCache.dss.depthWrite) { + gl.depthMask(true); + } + + gl.clearDepth(cmd0.clearDepth); + + clears |= WebGLRenderingContext.DEPTH_BUFFER_BIT; + + break; + } + case GFXLoadOp.DISCARD: { + // invalidate the framebuffer + invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.DEPTH_ATTACHMENT; + break; + } + default: + } + + if (GFXFormatInfos[curGPURenderPass.depthStencilAttachment.format].hasStencil) { + switch (curGPURenderPass.depthStencilAttachment.stencilLoadOp) { + case GFXLoadOp.LOAD: break; // GL default behaviour + case GFXLoadOp.CLEAR: { + + if (!device.stateCache.dss.stencilWriteMaskFront) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0xFFFFFFFF); + } + + if (!device.stateCache.dss.stencilWriteMaskBack) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0xFFFFFFFF); + } + + gl.clearStencil(cmd0.clearStencil); + clears |= WebGLRenderingContext.STENCIL_BUFFER_BIT; + + break; + } + case GFXLoadOp.DISCARD: { + // invalidate the framebuffer + invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.STENCIL_ATTACHMENT; + break; + } + default: + } + } + } + } // if (curGPURenderPass.depthStencilAttachment) + + /* + if (numInvalidAttach) { + gl.invalidateFramebuffer(WebGLRenderingContext.FRAMEBUFFER, numInvalidAttach, invalidateAttachments); + } + */ + + if (clears) { + gl.clear(clears); + } + + // restore states + if (clears & WebGLRenderingContext.COLOR_BUFFER_BIT) { + + const colorMask = device.stateCache.bs.targets[0].blendColorMask; + if (colorMask !== GFXColorMask.ALL) { + const r = (colorMask & GFXColorMask.R) !== GFXColorMask.NONE; + const g = (colorMask & GFXColorMask.G) !== GFXColorMask.NONE; + const b = (colorMask & GFXColorMask.B) !== GFXColorMask.NONE; + const a = (colorMask & GFXColorMask.A) !== GFXColorMask.NONE; + gl.colorMask(r, g, b, a); + } + } + + if ((clears & WebGLRenderingContext.DEPTH_BUFFER_BIT) && + !device.stateCache.dss.depthWrite) { + gl.depthMask(false); + } + + if (clears & WebGLRenderingContext.STENCIL_BUFFER_BIT) { + if (!device.stateCache.dss.stencilWriteMaskFront) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0); + } + + if (!device.stateCache.dss.stencilWriteMaskBack) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0); + } + } + } // if (curGPURenderPass) + + break; + } + case WebGLCmd.END_RENDER_PASS: { + // WebGL 1.0 doesn't support store operation of attachments. + // GFXStoreOp.Store is the default GL behaviour. + break; + } + case WebGLCmd.BIND_STATES: { + + const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; + if (cmd2.gpuPipelineState) { + gpuPipelineState = cmd2.gpuPipelineState; + glPrimitive = cmd2.gpuPipelineState.glPrimitive; + + if (cmd2.gpuPipelineState.gpuShader) { + + const glProgram = cmd2.gpuPipelineState.gpuShader.glProgram; + if (device.stateCache.glProgram !== glProgram) { + gl.useProgram(glProgram); + device.stateCache.glProgram = glProgram; + } + + gpuShader = cmd2.gpuPipelineState.gpuShader; + } + + // rasterizer state + const rs = cmd2.gpuPipelineState.rs; + if (rs) { + + if (device.stateCache.rs.cullMode !== rs.cullMode) { + switch (rs.cullMode) { + case GFXCullMode.NONE: { + gl.disable(WebGLRenderingContext.CULL_FACE); + break; + } + case GFXCullMode.FRONT: { + gl.enable(WebGLRenderingContext.CULL_FACE); + gl.cullFace(WebGLRenderingContext.FRONT); + break; + } + case GFXCullMode.BACK: { + gl.enable(WebGLRenderingContext.CULL_FACE); + gl.cullFace(WebGLRenderingContext.BACK); + break; + } + default: + } + + device.stateCache.rs.cullMode = rs.cullMode; + } + + if (device.stateCache.rs.isFrontFaceCCW !== rs.isFrontFaceCCW) { + gl.frontFace(rs.isFrontFaceCCW ? WebGLRenderingContext.CCW : WebGLRenderingContext.CW); + device.stateCache.rs.isFrontFaceCCW = rs.isFrontFaceCCW; + } + + if ((device.stateCache.rs.depthBias !== rs.depthBias) || + (device.stateCache.rs.depthBiasSlop !== rs.depthBiasSlop)) { + gl.polygonOffset(rs.depthBias, rs.depthBiasSlop); + device.stateCache.rs.depthBias = rs.depthBias; + device.stateCache.rs.depthBiasSlop = rs.depthBiasSlop; + } + + if (device.stateCache.rs.lineWidth !== rs.lineWidth) { + gl.lineWidth(rs.lineWidth); + device.stateCache.rs.lineWidth = rs.lineWidth; + } + + } // rasterizater state + + // depth-stencil state + const dss = cmd2.gpuPipelineState.dss; + if (dss) { + + if (device.stateCache.dss.depthTest !== dss.depthTest) { + if (dss.depthTest) { + gl.enable(WebGLRenderingContext.DEPTH_TEST); + } else { + gl.disable(WebGLRenderingContext.DEPTH_TEST); + } + device.stateCache.dss.depthTest = dss.depthTest; + } + + if (device.stateCache.dss.depthWrite !== dss.depthWrite) { + gl.depthMask(dss.depthWrite); + device.stateCache.dss.depthWrite = dss.depthWrite; + } + + if (device.stateCache.dss.depthFunc !== dss.depthFunc) { + gl.depthFunc(WebGLCmpFuncs[dss.depthFunc]); + device.stateCache.dss.depthFunc = dss.depthFunc; + } + + // front + if ((device.stateCache.dss.stencilTestFront !== dss.stencilTestFront) || + (device.stateCache.dss.stencilTestBack !== dss.stencilTestBack)) { + if (dss.stencilTestFront || dss.stencilTestBack) { + gl.enable(WebGLRenderingContext.STENCIL_TEST); + } else { + gl.disable(WebGLRenderingContext.STENCIL_TEST); + } + device.stateCache.dss.stencilTestFront = dss.stencilTestFront; + device.stateCache.dss.stencilTestBack = dss.stencilTestBack; + } + + if ((device.stateCache.dss.stencilFuncFront !== dss.stencilFuncFront) || + (device.stateCache.dss.stencilRefFront !== dss.stencilRefFront) || + (device.stateCache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront)) { + + gl.stencilFuncSeparate( + WebGLRenderingContext.FRONT, + WebGLCmpFuncs[dss.stencilFuncFront], + dss.stencilRefFront, + dss.stencilReadMaskFront); + + device.stateCache.dss.stencilFuncFront = dss.stencilFuncFront; + device.stateCache.dss.stencilRefFront = dss.stencilRefFront; + device.stateCache.dss.stencilReadMaskFront = dss.stencilReadMaskFront; + } + + if ((device.stateCache.dss.stencilFailOpFront !== dss.stencilFailOpFront) || + (device.stateCache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront) || + (device.stateCache.dss.stencilPassOpFront !== dss.stencilPassOpFront)) { + + gl.stencilOpSeparate( + WebGLRenderingContext.FRONT, + WebGLStencilOps[dss.stencilFailOpFront], + WebGLStencilOps[dss.stencilZFailOpFront], + WebGLStencilOps[dss.stencilPassOpFront]); + + device.stateCache.dss.stencilFailOpFront = dss.stencilFailOpFront; + device.stateCache.dss.stencilZFailOpFront = dss.stencilZFailOpFront; + device.stateCache.dss.stencilPassOpFront = dss.stencilPassOpFront; + } + + if (device.stateCache.dss.stencilWriteMaskFront !== dss.stencilWriteMaskFront) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, dss.stencilWriteMaskFront); + device.stateCache.dss.stencilWriteMaskFront = dss.stencilWriteMaskFront; + } + + // back + if ((device.stateCache.dss.stencilFuncBack !== dss.stencilFuncBack) || + (device.stateCache.dss.stencilRefBack !== dss.stencilRefBack) || + (device.stateCache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack)) { + + gl.stencilFuncSeparate( + WebGLRenderingContext.BACK, + WebGLCmpFuncs[dss.stencilFuncBack], + dss.stencilRefBack, + dss.stencilReadMaskBack); + + device.stateCache.dss.stencilFuncBack = dss.stencilFuncBack; + device.stateCache.dss.stencilRefBack = dss.stencilRefBack; + device.stateCache.dss.stencilReadMaskBack = dss.stencilReadMaskBack; + } + + if ((device.stateCache.dss.stencilFailOpBack !== dss.stencilFailOpBack) || + (device.stateCache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack) || + (device.stateCache.dss.stencilPassOpBack !== dss.stencilPassOpBack)) { + + gl.stencilOpSeparate( + WebGLRenderingContext.BACK, + WebGLStencilOps[dss.stencilFailOpBack], + WebGLStencilOps[dss.stencilZFailOpBack], + WebGLStencilOps[dss.stencilPassOpBack]); + + device.stateCache.dss.stencilFailOpBack = dss.stencilFailOpBack; + device.stateCache.dss.stencilZFailOpBack = dss.stencilZFailOpBack; + device.stateCache.dss.stencilPassOpBack = dss.stencilPassOpBack; + } + + if (device.stateCache.dss.stencilWriteMaskBack !== dss.stencilWriteMaskBack) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, dss.stencilWriteMaskBack); + device.stateCache.dss.stencilWriteMaskBack = dss.stencilWriteMaskBack; + } + } // depth-stencil state + + // blend state + const bs = cmd2.gpuPipelineState.bs; + if (bs) { + + if (device.stateCache.bs.isA2C !== bs.isA2C) { + if (bs.isA2C) { + gl.enable(WebGLRenderingContext.SAMPLE_ALPHA_TO_COVERAGE); + } else { + gl.disable(WebGLRenderingContext.SAMPLE_ALPHA_TO_COVERAGE); + } + device.stateCache.bs.isA2C = bs.isA2C; + } + + if ((device.stateCache.bs.blendColor[0] !== bs.blendColor[0]) || + (device.stateCache.bs.blendColor[1] !== bs.blendColor[1]) || + (device.stateCache.bs.blendColor[2] !== bs.blendColor[2]) || + (device.stateCache.bs.blendColor[3] !== bs.blendColor[3])) { + + gl.blendColor(bs.blendColor[0], bs.blendColor[1], bs.blendColor[2], bs.blendColor[3]); + + device.stateCache.bs.blendColor[0] = bs.blendColor[0]; + device.stateCache.bs.blendColor[1] = bs.blendColor[1]; + device.stateCache.bs.blendColor[2] = bs.blendColor[2]; + device.stateCache.bs.blendColor[3] = bs.blendColor[3]; + } + + const target0 = bs.targets[0]; + const catchTarget0 = device.stateCache.bs.targets[0]; + + if (catchTarget0.blend !== target0.blend) { + if (target0.blend) { + gl.enable(WebGLRenderingContext.BLEND); + } else { + gl.disable(WebGLRenderingContext.BLEND); + } + catchTarget0.blend = target0.blend; + } + + if ((catchTarget0.blendEq !== target0.blendEq) || + (catchTarget0.blendAlphaEq !== target0.blendAlphaEq)) { + + gl.blendEquationSeparate(WebGLBlendOps[target0.blendEq], WebGLBlendOps[target0.blendAlphaEq]); + + catchTarget0.blendEq = target0.blendEq; + catchTarget0.blendAlphaEq = target0.blendAlphaEq; + } + + if ((catchTarget0.blendSrc !== target0.blendSrc) || + (catchTarget0.blendDst !== target0.blendDst) || + (catchTarget0.blendSrcAlpha !== target0.blendSrcAlpha) || + (catchTarget0.blendDstAlpha !== target0.blendDstAlpha)) { + + gl.blendFuncSeparate( + WebGLBlendFactors[target0.blendSrc], + WebGLBlendFactors[target0.blendDst], + WebGLBlendFactors[target0.blendSrcAlpha], + WebGLBlendFactors[target0.blendDstAlpha]); + + catchTarget0.blendSrc = target0.blendSrc; + catchTarget0.blendDst = target0.blendDst; + catchTarget0.blendSrcAlpha = target0.blendSrcAlpha; + catchTarget0.blendDstAlpha = target0.blendDstAlpha; + } + + if (catchTarget0.blendColorMask !== target0.blendColorMask) { + + gl.colorMask( + (target0.blendColorMask & GFXColorMask.R) !== GFXColorMask.NONE, + (target0.blendColorMask & GFXColorMask.G) !== GFXColorMask.NONE, + (target0.blendColorMask & GFXColorMask.B) !== GFXColorMask.NONE, + (target0.blendColorMask & GFXColorMask.A) !== GFXColorMask.NONE); + + catchTarget0.blendColorMask = target0.blendColorMask; + } + } // blend state + } // bind pso + + if (cmd2.gpuBindingLayout && gpuShader) { + for (const gpuBinding of cmd2.gpuBindingLayout.gpuBindings) { + + switch (gpuBinding.type) { + case GFXBindingType.UNIFORM_BUFFER: { + + if (gpuBinding.gpuBuffer && gpuBinding.gpuBuffer.buffer) { + + let glBlock: WebGLGPUUniformBlock | null = null; + + for (const block of gpuShader.glBlocks) { + if (block.binding === gpuBinding.binding) { + glBlock = block; + break; + } + } + + if (glBlock && gpuBinding.gpuBuffer.vf32) { + for (const glUniform of glBlock.glActiveUniforms) { + switch (glUniform.glType) { + case WebGLRenderingContext.BOOL: + case WebGLRenderingContext.INT: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform1iv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.BOOL_VEC2: + case WebGLRenderingContext.INT_VEC2: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform2iv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.BOOL_VEC3: + case WebGLRenderingContext.INT_VEC3: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform3iv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.BOOL_VEC4: + case WebGLRenderingContext.INT_VEC4: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform4iv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform1fv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_VEC2: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform2fv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_VEC3: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform3fv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_VEC4: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniform4fv(glUniform.glLoc, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_MAT2: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_MAT3: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_MAT4: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; + } + gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array); + break; + } + } + break; + } + default: + } + } + } + } // if + + break; + } + case GFXBindingType.SAMPLER: { + + if (gpuBinding.gpuSampler) { + + let glSampler: WebGLGPUUniformSampler | null = null; + + for (const sampler of gpuShader.glSamplers) { + if (sampler.binding === gpuBinding.binding) { + glSampler = sampler; + break; + } + } + + if (glSampler) { + for (const texUnit of glSampler.units) { + + if (device.stateCache.texUnit !== texUnit) { + gl.activeTexture(WebGLRenderingContext.TEXTURE0 + texUnit); + device.stateCache.texUnit = texUnit; + } + + let glTexUnit: IWebGLTexUnit | null = null; + let isTexParamInvalied = false; + + if (gpuBinding.gpuTexView) { + const gpuTexture = gpuBinding.gpuTexView.gpuTexture; + switch (glSampler.glType) { + case WebGLRenderingContext.SAMPLER_2D: { + glTexUnit = device.stateCache.glTex2DUnits[texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + isTexParamInvalied = true; + } + break; + } + case WebGLRenderingContext.SAMPLER_CUBE: { + glTexUnit = device.stateCache.glTexCubeUnits[texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + isTexParamInvalied = true; + } + break; + } + default: { + console.error('Unsupported GL Texture type.'); + } + } + + if (glTexUnit) { + const gpuSampler = gpuBinding.gpuSampler; + + if (glTexUnit.minFilter !== gpuSampler.glMinFilter || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuSampler.glMinFilter); + glTexUnit.minFilter = gpuSampler.glMinFilter; + } + + if (glTexUnit.magFilter !== gpuSampler.glMagFilter || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter); + glTexUnit.magFilter = gpuSampler.glMagFilter; + } + + if (glTexUnit.wrapS !== gpuSampler.glWrapS || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuSampler.glWrapS); + glTexUnit.wrapS = gpuSampler.glWrapS; + } + + if (glTexUnit.wrapT !== gpuSampler.glWrapT || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuSampler.glWrapT); + glTexUnit.wrapT = gpuSampler.glWrapT; + } + + /* + if(glTexUnit.wrapR !== gpuSampler.glWrapR || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_R, gpuSampler.glWrapR); + glTexUnit.wrapR = gpuSampler.glWrapR; + } + */ + } + } else { + console.error("Not found texture view on binding unit " + gpuBinding.binding); + } + } + } // if + } else { + console.error("Not found sampler or texture view on binding unit " + gpuBinding.binding); + } + + break; + } + } + } + } // bind binding layout + + if (cmd2.gpuInputAssembler && gpuShader) { + gpuInputAssembler = cmd2.gpuInputAssembler; + + for (let a = 0; a < device.maxVertexAttributes; ++a) { + device.stateCache.glCurrentAttribLocs[a] = false; + } + + for (const glInput of gpuShader.glInputs) { + let glAttrib: WebGLAttrib | null = null; + + for (const attrib of gpuInputAssembler.glAttribs) { + if (attrib.name === glInput.name) { + glAttrib = attrib; + break; + } + } + + if (glAttrib) { + if (device.stateCache.glArrayBuffer !== glAttrib.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, glAttrib.glBuffer); + device.stateCache.glArrayBuffer = glAttrib.glBuffer; + } + + for (let c = 0; c < glAttrib.componentCount; ++c) { + const glLoc = glInput.glLoc + c; + const attribOffset = glAttrib.offset + glAttrib.size * c; + + if (!device.stateCache.glEnabledAttribLocs[glLoc] && glLoc >= 0) { + gl.enableVertexAttribArray(glLoc); + device.stateCache.glEnabledAttribLocs[glLoc] = true; + } + device.stateCache.glCurrentAttribLocs[glLoc] = true; + + gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset); + } + } + } // for + + const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + if (gpuBuffer) { + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + } + + for (let a = 0; a < device.maxVertexAttributes; ++a) { + if (device.stateCache.glEnabledAttribLocs[a] !== device.stateCache.glCurrentAttribLocs[a]) { + gl.disableVertexAttribArray(a); + device.stateCache.glEnabledAttribLocs[a] = false; + } + } + } + + if (gpuPipelineState) { + for (const dynamicState of gpuPipelineState.dynamicStates) { + switch (dynamicState) { + case GFXDynamicState.VIEWPORT: { + if (cmd2.viewport) { + if (device.stateCache.viewport.left !== cmd2.viewport.left || + device.stateCache.viewport.top !== cmd2.viewport.top || + device.stateCache.viewport.width !== cmd2.viewport.width || + device.stateCache.viewport.height !== cmd2.viewport.height) { + + gl.viewport(cmd2.viewport.left, cmd2.viewport.top, cmd2.viewport.width, cmd2.viewport.height); + + device.stateCache.viewport.left = cmd2.viewport.left; + device.stateCache.viewport.top = cmd2.viewport.top; + device.stateCache.viewport.width = cmd2.viewport.width; + device.stateCache.viewport.height = cmd2.viewport.height; + } + } + break; + } + case GFXDynamicState.SCISSOR: { + if (cmd2.scissor) { + if (device.stateCache.scissorRect.x !== cmd2.scissor.x || + device.stateCache.scissorRect.y !== cmd2.scissor.y || + device.stateCache.scissorRect.width !== cmd2.scissor.width || + device.stateCache.scissorRect.height !== cmd2.scissor.height) { + + gl.scissor(cmd2.scissor.x, cmd2.scissor.y, cmd2.scissor.width, cmd2.scissor.height); + + device.stateCache.scissorRect.x = cmd2.scissor.x; + device.stateCache.scissorRect.y = cmd2.scissor.y; + device.stateCache.scissorRect.width = cmd2.scissor.width; + device.stateCache.scissorRect.height = cmd2.scissor.height; + } + } + break; + } + case GFXDynamicState.LINE_WIDTH: { + if (cmd2.lineWidth) { + if (device.stateCache.rs.lineWidth !== cmd2.lineWidth) { + gl.lineWidth(cmd2.lineWidth); + device.stateCache.rs.lineWidth = cmd2.lineWidth; + } + } + break; + } + case GFXDynamicState.DEPTH_BIAS: { + if (cmd2.depthBias) { + + if ((device.stateCache.rs.depthBias !== cmd2.depthBias.constantFactor) || + (device.stateCache.rs.depthBiasSlop !== cmd2.depthBias.slopeFactor)) { + gl.polygonOffset(cmd2.depthBias.constantFactor, cmd2.depthBias.slopeFactor); + device.stateCache.rs.depthBias = cmd2.depthBias.constantFactor; + device.stateCache.rs.depthBiasSlop = cmd2.depthBias.slopeFactor; + } + } + break; + } + case GFXDynamicState.BLEND_CONSTANTS: { + if (cmd2.blendConstants) { + if ((device.stateCache.bs.blendColor[0] !== cmd2.blendConstants[0]) || + (device.stateCache.bs.blendColor[1] !== cmd2.blendConstants[1]) || + (device.stateCache.bs.blendColor[2] !== cmd2.blendConstants[2]) || + (device.stateCache.bs.blendColor[3] !== cmd2.blendConstants[3])) { + + gl.blendColor(cmd2.blendConstants[0], cmd2.blendConstants[1], cmd2.blendConstants[2], cmd2.blendConstants[3]); + + device.stateCache.bs.blendColor[0] = cmd2.blendConstants[0]; + device.stateCache.bs.blendColor[1] = cmd2.blendConstants[1]; + device.stateCache.bs.blendColor[2] = cmd2.blendConstants[2]; + device.stateCache.bs.blendColor[3] = cmd2.blendConstants[3]; + } + } + break; + } + case GFXDynamicState.STENCIL_WRITE_MASK: { + if (cmd2.stencilWriteMask) { + switch (cmd2.stencilWriteMask.face) { + case GFXStencilFace.FRONT: { + if (device.stateCache.dss.stencilWriteMaskFront !== cmd2.stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, cmd2.stencilWriteMask.writeMask); + device.stateCache.dss.stencilWriteMaskFront = cmd2.stencilWriteMask.writeMask; + } + break; + } + case GFXStencilFace.BACK: { + if (device.stateCache.dss.stencilWriteMaskBack !== cmd2.stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, cmd2.stencilWriteMask.writeMask); + device.stateCache.dss.stencilWriteMaskBack = cmd2.stencilWriteMask.writeMask; + } + break; + } + case GFXStencilFace.ALL: { + if (device.stateCache.dss.stencilWriteMaskFront !== cmd2.stencilWriteMask.writeMask || + device.stateCache.dss.stencilWriteMaskBack !== cmd2.stencilWriteMask.writeMask) { + gl.stencilMask(cmd2.stencilWriteMask.writeMask); + device.stateCache.dss.stencilWriteMaskFront = cmd2.stencilWriteMask.writeMask; + device.stateCache.dss.stencilWriteMaskBack = cmd2.stencilWriteMask.writeMask; + } + break; + } + } + } + break; + } + case GFXDynamicState.STENCIL_COMPARE_MASK: { + if (cmd2.stencilCompareMask) { + switch (cmd2.stencilCompareMask.face) { + case GFXStencilFace.FRONT: { + if (device.stateCache.dss.stencilRefFront !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskFront !== cmd2.stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + WebGLRenderingContext.FRONT, + WebGLCmpFuncs[device.stateCache.dss.stencilFuncFront], + cmd2.stencilCompareMask.reference, + cmd2.stencilCompareMask.compareMask); + device.stateCache.dss.stencilRefFront = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskFront = cmd2.stencilCompareMask.compareMask; + } + break; + } + case GFXStencilFace.BACK: { + if (device.stateCache.dss.stencilRefBack !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskBack !== cmd2.stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + WebGLRenderingContext.BACK, + WebGLCmpFuncs[device.stateCache.dss.stencilFuncBack], + cmd2.stencilCompareMask.reference, + cmd2.stencilCompareMask.compareMask); + device.stateCache.dss.stencilRefBack = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskBack = cmd2.stencilCompareMask.compareMask; + } + break; + } + case GFXStencilFace.ALL: { + if (device.stateCache.dss.stencilRefFront !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskFront !== cmd2.stencilCompareMask.compareMask || + device.stateCache.dss.stencilRefBack !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskBack !== cmd2.stencilCompareMask.compareMask) { + gl.stencilFunc( + WebGLCmpFuncs[device.stateCache.dss.stencilFuncBack], + cmd2.stencilCompareMask.reference, + cmd2.stencilCompareMask.compareMask); + device.stateCache.dss.stencilRefFront = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskFront = cmd2.stencilCompareMask.compareMask; + device.stateCache.dss.stencilRefBack = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskBack = cmd2.stencilCompareMask.compareMask; + } + break; + } + } + } + break; + } + } // switch + } // for + } // if + + break; + } + case WebGLCmd.DRAW: { + const cmd3: WebGLCmdDraw = cmdPackage.drawCmds.array[cmdId]; + if (gpuInputAssembler && gpuShader) { + if (!gpuInputAssembler.gpuIndirectBuffer) { + const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + if (gpuBuffer && cmd3.drawInfo.indexCount > 0) { + const offset = cmd3.drawInfo.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, cmd3.drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); + } else { + gl.drawArrays(glPrimitive, cmd3.drawInfo.firstVertex, cmd3.drawInfo.vertexCount); + } + } else { + if (gpuInputAssembler.gpuIndirectBuffer) { + for (const drawInfo of gpuInputAssembler.gpuIndirectBuffer.indirects) { + const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + if (gpuBuffer && drawInfo.indexCount > -1) { + const offset = drawInfo.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); + } else { + gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount); + } + } + } + } + } + break; + } + case WebGLCmd.UPDATE_BUFFER: { + const cmd4 = cmdPackage.updateBufferCmds.array[cmdId]; + WebGLCmdFuncUpdateBuffer( + device, + cmd4.gpuBuffer as WebGLGPUBuffer, + cmd4.buffer as GFXBufferSource, + cmd4.offset, + cmd4.size); + + break; + } + case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { + const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; + WebGLCmdFuncCopyBufferToTexture( + device, + (cmd5.gpuBuffer as WebGLGPUBuffer).buffer as GFXBufferSource, + cmd5.gpuTexture as WebGLGPUTexture, + cmd5.regions); + + break; + } + } // switch + } // for +} + +export function WebGLCmdFuncCopyBufferToTexture ( + device: WebGLGFXDevice, + buffer: GFXBufferSource, + gpuTexture: WebGLGPUTexture, + regions: GFXBufferTextureCopy[]) { + + const gl = device.gl; + + const buff = buffer as ArrayBuffer; + const fmtInfo: IGFXFormatInfo = GFXFormatInfos[gpuTexture.format]; + + switch (gpuTexture.glTarget) { + case WebGLRenderingContext.TEXTURE_2D: { + const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; + if (!isCompressed) { + for (const region of regions) { + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); + + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } else { + for (const region of regions) { + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); + + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + break; + } + case WebGLRenderingContext.TEXTURE_CUBE_MAP: { + const glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; + if (!isCompressed) { + for (const region of regions) { + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + for (let f = 0; f < 6; ++f) { + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); + + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + } else { + for (const region of regions) { + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + for (let f = 0; f < 6; ++f) { + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); + + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + } + break; + } + default: { + console.error('Unsupported GL texture type, copy buffer to texture failed.'); + } + } + + if (gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { + gl.generateMipmap(gpuTexture.glTarget); + } +} diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts new file mode 100644 index 0000000000..262cbde641 --- /dev/null +++ b/cocos/gfx/webgl/webgl-device.ts @@ -0,0 +1,1089 @@ +import * as WebGLDeveloperTools from 'webgl-debug'; +import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; +import { GFXBuffer, GFXBufferSource, IGFXBufferInfo, IGFXIndirectBuffer } from '../buffer'; +import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; +import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; +import { + GFXBindingType, + GFXBufferTextureCopy, + GFXBufferUsageBit, + GFXFilter, + GFXFormat, + GFXFormatInfos, + GFXFormatSize, + GFXQueueType, + GFXTextureFlagBit, + GFXTextureType, + GFXTextureViewType, +} from '../define'; +import { GFXDevice, GFXFeature, IGFXDeviceInfo } from '../device'; +import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; +import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../pipeline-layout'; +import { GFXPipelineState, IGFXPipelineStateInfo } from '../pipeline-state'; +import { GFXQueue, IGFXQueueInfo } from '../queue'; +import { GFXRenderPass, IGFXRenderPassInfo } from '../render-pass'; +import { GFXSampler, IGFXSamplerInfo } from '../sampler'; +import { GFXShader, IGFXShaderInfo } from '../shader'; +import { GFXTexture, IGFXTextureInfo } from '../texture'; +import { GFXTextureView, IGFXTextureViewInfo } from '../texture-view'; +import { GFXWindow, IGFXWindowInfo } from '../window'; +import { WebGLGFXBindingLayout } from './webgl-binding-layout'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; +import { + WebGLCmdFuncCopyBufferToTexture, + WebGLCmdFuncCreateBuffer, + WebGLCmdFuncCreateFramebuffer, + WebGLCmdFuncCreateInputAssember, + WebGLCmdFuncCreateShader, + WebGLCmdFuncCreateTexture, + WebGLCmdFuncDestroyBuffer, + WebGLCmdFuncDestroyFramebuffer, + WebGLCmdFuncDestroyShader, + WebGLCmdFuncDestroyTexture, + WebGLCmdFuncResizeBuffer, + WebGLCmdFuncUpdateBuffer, +} from './webgl-commands'; +import { WebGLGFXFramebuffer } from './webgl-framebuffer'; +import { + WebGLGPUBinding, + WebGLGPUBindingLayout, + WebGLGPUBuffer, + WebGLGPUFramebuffer, + WebGLGPUInputAssembler, + WebGLGPUObjectType, + WebGLGPUPipelineLayout, + WebGLGPUPipelineState, + WebGLGPURenderPass, + WebGLGPUSampler, + WebGLGPUShader, + WebGLGPUShaderStage, + WebGLGPUTexture, + WebGLGPUTextureView, +} from './webgl-gpu-objects'; +import { WebGLGFXInputAssembler } from './webgl-input-assembler'; +import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; +import { WebGLGFXPipelineState } from './webgl-pipeline-state'; +import { WebGLGFXQueue } from './webgl-queue'; +import { WebGLGFXRenderPass } from './webgl-render-pass'; +import { WebGLGFXSampler } from './webgl-sampler'; +import { WebGLGFXShader } from './webgl-shader'; +import { WebGLStateCache } from './webgl-state-cache'; +import { WebGLGFXTexture } from './webgl-texture'; +import { WebGLGFXTextureView } from './webgl-texture-view'; +import { WebGLGFXWindow } from './webgl-window'; + +const WebGLPrimitives: GLenum[] = [ + WebGLRenderingContext.POINTS, + WebGLRenderingContext.LINES, + WebGLRenderingContext.LINE_STRIP, + WebGLRenderingContext.LINE_LOOP, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.TRIANGLES, + WebGLRenderingContext.TRIANGLE_STRIP, + WebGLRenderingContext.TRIANGLE_FAN, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, +]; + +const WebGLWraps: GLenum[] = [ + WebGLRenderingContext.REPEAT, + WebGLRenderingContext.MIRRORED_REPEAT, + WebGLRenderingContext.CLAMP_TO_EDGE, + WebGLRenderingContext.CLAMP_TO_EDGE, +]; + +export class WebGLGFXDevice extends GFXDevice { + + public get gl (): WebGLRenderingContext { + return this._webGLRC as WebGLRenderingContext; + } + + public get webGLQueue (): WebGLGFXQueue { + return this._queue as WebGLGFXQueue; + } + + public get isAntialias (): boolean { + return this._isAntialias; + } + + public get isPremultipliedAlpha (): boolean { + return this._isPremultipliedAlpha; + } + + public get EXT_texture_filter_anisotropic (): EXT_texture_filter_anisotropic | null { + return this._EXT_texture_filter_anisotropic; + } + + public get EXT_frag_depth (): EXT_frag_depth | null { + return this._EXT_frag_depth; + } + + public get EXT_shader_texture_lod (): EXT_shader_texture_lod | null { + return this._EXT_shader_texture_lod; + } + + public get EXT_sRGB (): EXT_sRGB | null { + return this._EXT_sRGB; + } + + public get OES_vertex_array_object (): OES_vertex_array_object | null { + return this._OES_vertex_array_object; + } + + public get WEBGL_color_buffer_float (): WEBGL_color_buffer_float | null { + return this._WEBGL_color_buffer_float; + } + + public get WEBGL_compressed_texture_astc (): WEBGL_compressed_texture_astc | null { + return this._WEBGL_compressed_texture_astc; + } + + public get WEBGL_compressed_texture_s3tc (): WEBGL_compressed_texture_s3tc | null { + return this._WEBGL_compressed_texture_s3tc; + } + + public get WEBGL_compressed_texture_s3tc_srgb (): WEBGL_compressed_texture_s3tc_srgb | null { + return this._WEBGL_compressed_texture_s3tc_srgb; + } + + public get WEBGL_debug_shaders (): WEBGL_debug_shaders | null { + return this._WEBGL_debug_shaders; + } + + public get WEBGL_draw_buffers (): WEBGL_draw_buffers | null { + return this._WEBGL_draw_buffers; + } + + public get WEBGL_lose_context (): WEBGL_lose_context | null { + return this._WEBGL_lose_context; + } + + public get WEBGL_depth_texture (): WEBGL_depth_texture | null { + return this._WEBGL_depth_texture; + } + + public get WEBGL_debug_renderer_info (): WEBGL_debug_renderer_info | null { + return this._WEBGL_debug_renderer_info; + } + + public get OES_texture_half_float (): OES_texture_half_float | null { + return this._OES_texture_half_float; + } + + public get OES_texture_half_float_linear (): OES_texture_half_float_linear | null { + return this._OES_texture_half_float_linear; + } + + public get OES_texture_float (): OES_texture_float | null { + return this._OES_texture_float; + } + + public get OES_standard_derivatives (): OES_standard_derivatives | null { + return this._OES_standard_derivatives; + } + + public get OES_element_index_uint (): OES_element_index_uint | null { + return this._OES_element_index_uint; + } + + public get ANGLE_instanced_arrays (): ANGLE_instanced_arrays | null { + return this._ANGLE_instanced_arrays; + } + + public stateCache: WebGLStateCache = new WebGLStateCache(); + + private _webGLRC: WebGLRenderingContext | null = null; + private _isAntialias: boolean = true; + private _isPremultipliedAlpha: boolean = true; + + private _extensions: string[] | null = null; + private _EXT_texture_filter_anisotropic: EXT_texture_filter_anisotropic | null = null; + private _EXT_frag_depth: EXT_frag_depth | null = null; + private _EXT_shader_texture_lod: EXT_shader_texture_lod | null = null; + private _EXT_sRGB: EXT_sRGB | null = null; + private _OES_vertex_array_object: OES_vertex_array_object | null = null; + private _WEBGL_color_buffer_float: WEBGL_color_buffer_float | null = null; + private _WEBGL_compressed_texture_astc: WEBGL_compressed_texture_astc | null = null; + private _WEBGL_compressed_texture_s3tc: WEBGL_compressed_texture_s3tc | null = null; + private _WEBGL_compressed_texture_s3tc_srgb: WEBGL_compressed_texture_s3tc_srgb | null = null; + private _WEBGL_debug_shaders: WEBGL_debug_shaders | null = null; + private _WEBGL_draw_buffers: WEBGL_draw_buffers | null = null; + private _WEBGL_lose_context: WEBGL_lose_context | null = null; + private _WEBGL_depth_texture: WEBGL_depth_texture | null = null; + private _WEBGL_debug_renderer_info: WEBGL_debug_renderer_info | null = null; + private _OES_texture_half_float: OES_texture_half_float | null = null; + private _OES_texture_half_float_linear: OES_texture_half_float_linear | null = null; + private _OES_texture_float: OES_texture_float | null = null; + private _OES_standard_derivatives: OES_standard_derivatives | null = null; + private _OES_element_index_uint: OES_element_index_uint | null = null; + private _ANGLE_instanced_arrays: ANGLE_instanced_arrays | null = null; + + constructor () { + super(); + } + + public initialize (info: IGFXDeviceInfo): boolean { + + this._canvas = info.canvasElm as HTMLCanvasElement; + + if (info.isAntialias) { + this._isAntialias = info.isAntialias; + } + + if (info.isPremultipliedAlpha) { + this._isPremultipliedAlpha = info.isPremultipliedAlpha; + } + + try { + const webGLCtxAttribs: WebGLContextAttributes = { + alpha: true, + antialias: this._isAntialias, + depth: true, + stencil: true, + premultipliedAlpha: this._isPremultipliedAlpha, + preserveDrawingBuffer: false, + powerPreference: 'default', + failIfMajorPerformanceCaveat: false, + }; + + this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); + /* + if (this._webGLRC && info.debug) { + this._webGLRC = WebGLDeveloperTools.makeDebugContext(this._webGLRC, this._onWebGLError.bind(this)); + } + */ + } catch (err) { + console.error(err); + return false; + } + + // No errors are thrown using try catch + // Tested through ios baidu browser 4.14.1 + if (!this._webGLRC) { + console.error('This device does not support WebGL.'); + return false; + } + + this._canvas2D = document.createElement('canvas'); + + console.info('WebGL device initialized.'); + + this._deviceName = 'WebGL'; + const gl = this._webGLRC; + + this._WEBGL_debug_renderer_info = gl.getExtension('WEBGL_debug_renderer_info'); + if (this._WEBGL_debug_renderer_info) { + this._renderer = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); + this._vendor = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); + } else { + this._renderer = gl.getParameter(WebGLRenderingContext.RENDERER); + this._vendor = gl.getParameter(WebGLRenderingContext.VENDOR); + } + + this._version = gl.getParameter(WebGLRenderingContext.VERSION); + this._maxVertexAttributes = gl.getParameter(WebGLRenderingContext.MAX_VERTEX_ATTRIBS); + this._maxVertexUniformVectors = gl.getParameter(WebGLRenderingContext.MAX_VERTEX_UNIFORM_VECTORS); + this._maxFragmentUniformVectors = gl.getParameter(WebGLRenderingContext.MAX_FRAGMENT_UNIFORM_VECTORS); + this._maxTextureUnits = gl.getParameter(WebGLRenderingContext.MAX_TEXTURE_IMAGE_UNITS); + this._maxVertexTextureUnits = gl.getParameter(WebGLRenderingContext.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + this._depthBits = gl.getParameter(WebGLRenderingContext.DEPTH_BITS); + this._stencilBits = gl.getParameter(WebGLRenderingContext.STENCIL_BITS); + + this._width = this._canvas.width; + this._height = this._canvas.height; + this._colorFmt = GFXFormat.RGBA8; + + if (this._depthBits === 24) { + if (this._stencilBits === 8) { + this._depthStencilFmt = GFXFormat.D24S8; + } else { + this._depthStencilFmt = GFXFormat.D24; + } + } else { + if (this._stencilBits === 8) { + this._depthStencilFmt = GFXFormat.D16S8; + } else { + this._depthStencilFmt = GFXFormat.D16; + } + } + + console.info('RENDERER: ' + this._renderer); + console.info('VENDOR: ' + this._vendor); + console.info('VERSION: ' + this._version); + console.info('SCREEN_SIZE: ' + this._width + ' x ' + this._height); + console.info('COLOR_FORMAT: ' + GFXFormatInfos[this._colorFmt].name); + console.info('DEPTH_STENCIL_FORMAT: ' + GFXFormatInfos[this._depthStencilFmt].name); + + console.info('MAX_VERTEX_ATTRIBS: ' + this._maxVertexAttributes); + console.info('MAX_VERTEX_UNIFORM_VECTORS: ' + this._maxVertexUniformVectors); + console.info('MAX_FRAGMENT_UNIFORM_VECTORS: ' + this._maxFragmentUniformVectors); + console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits); + console.info('MAX_VERTEX_TEXTURE_IMAGE_UNITS: ' + this._maxVertexTextureUnits); + console.info('DEPTH_BITS: ' + this._depthBits); + console.info('STENCIL_BITS: ' + this._stencilBits); + + this._extensions = gl.getSupportedExtensions(); + /* + if (this._extensions) { + for (let i = 0; i < this._extensions.length; ++i) { + console.info(this._extensions[i]); + } + } + */ + + this._EXT_texture_filter_anisotropic = gl.getExtension('EXT_texture_filter_anisotropic'); + this._EXT_frag_depth = gl.getExtension('EXT_frag_depth'); + this._EXT_shader_texture_lod = gl.getExtension('EXT_shader_texture_lod'); + this._EXT_sRGB = gl.getExtension('EXT_sRGB'); + this._OES_vertex_array_object = gl.getExtension('OES_vertex_array_object'); + this._WEBGL_color_buffer_float = gl.getExtension('WEBGL_color_buffer_float'); + this._WEBGL_compressed_texture_astc = gl.getExtension('WEBGL_compressed_texture_astc'); + this._WEBGL_compressed_texture_s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc'); + this._WEBGL_compressed_texture_s3tc_srgb = gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'); + this._WEBGL_debug_shaders = gl.getExtension('WEBGL_debug_shaders'); + this._WEBGL_draw_buffers = gl.getExtension('WEBGL_draw_buffers'); + this._WEBGL_lose_context = gl.getExtension('WEBGL_lose_context'); + this._WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture'); + this._OES_texture_half_float = gl.getExtension('OES_texture_half_float'); + this._OES_texture_half_float_linear = gl.getExtension('OES_texture_half_float_linear'); + this._OES_texture_float = gl.getExtension('OES_texture_float'); + this._OES_standard_derivatives = gl.getExtension('OES_standard_derivatives'); + this._OES_element_index_uint = gl.getExtension('OES_element_index_uint'); + this._ANGLE_instanced_arrays = gl.getExtension('ANGLE_instanced_arrays'); + + this._features.fill(false); + if (this._OES_texture_float) { + this._features[GFXFeature.TEXTURE_FLOAT] = true; + } + + if (this._OES_texture_half_float) { + this._features[GFXFeature.TEXTURE_HALF_FLOAT] = true; + } + + // init states + this.initStates(gl); + + // create queue + this._queue = this.createQueue({ type: GFXQueueType.GRAPHICS }); + + // create primary window + this._mainWindow = this.createWindow({ + title: this._webGLRC.canvas.title, + left: this._webGLRC.canvas.offsetLeft, + top: this._webGLRC.canvas.offsetTop, + width: this._webGLRC.drawingBufferWidth, + height: this._webGLRC.drawingBufferHeight, + colorFmt: this._colorFmt, + depthStencilFmt: this._depthStencilFmt, + }); + + this._cmdAllocator = this.createCommandAllocator({}); + + return true; + } + + public destroy (): void { + + if (this._mainWindow) { + this._mainWindow.destroy(); + this._mainWindow = null; + } + + if (this._cmdAllocator) { + this._cmdAllocator.destroy(); + this._cmdAllocator = null; + } + + if (this._queue) { + this._queue.destroy(); + this._queue = null; + } + + this._webGLRC = null; + } + + public resize (width: number, height: number) { + this._canvas!.width = width; + this._canvas!.height = height; + this._width = width; + this._height = height; + } + + public createBuffer (info: IGFXBufferInfo): GFXBuffer { + const buffer = new WebGLGFXBuffer(this); + buffer.initialize(info); + return buffer; + } + + public createTexture (info: IGFXTextureInfo): GFXTexture { + const texture = new WebGLGFXTexture(this); + texture.initialize(info); + return texture; + } + + public createTextureView (info: IGFXTextureViewInfo): GFXTextureView { + const texView = new WebGLGFXTextureView(this); + texView.initialize(info); + return texView; + } + + public createSampler (info: IGFXSamplerInfo): GFXSampler { + const sampler = new WebGLGFXSampler(this); + sampler.initialize(info); + return sampler; + } + + public createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout { + const bindingLayout = new WebGLGFXBindingLayout(this); + bindingLayout.initialize(info); + return bindingLayout; + } + + public createShader (info: IGFXShaderInfo): GFXShader { + const shader = new WebGLGFXShader(this); + shader.initialize(info); + return shader; + } + + public createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler { + const inputAssembler = new WebGLGFXInputAssembler(this); + inputAssembler.initialize(info); + return inputAssembler; + } + + public createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass { + const renderPass = new WebGLGFXRenderPass(this); + renderPass.initialize(info); + return renderPass; + } + + public createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer { + const framebuffer = new WebGLGFXFramebuffer(this); + framebuffer.initialize(info); + return framebuffer; + } + + public createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout { + const pipelineLayout = new WebGLGFXPipelineLayout(this); + pipelineLayout.initialize(info); + return pipelineLayout; + } + + public createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState { + const pipelineState = new WebGLGFXPipelineState(this); + pipelineState.initialize(info); + return pipelineState; + } + + public createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator { + const cmdAllocator = new WebGLGFXCommandAllocator(this); + cmdAllocator.initialize(info); + return cmdAllocator; + } + + public createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer { + const cmdBuff = new WebGLGFXCommandBuffer(this); + cmdBuff.initialize(info); + return cmdBuff; + } + + public createQueue (info: IGFXQueueInfo): GFXQueue { + const queue = new WebGLGFXQueue(this); + queue.initialize(info); + return queue; + } + + public createWindow (info: IGFXWindowInfo): GFXWindow { + const window = new WebGLGFXWindow(this); + window.initialize(info); + return window; + } + + public present () { + (this._cmdAllocator as WebGLGFXCommandAllocator).releaseCmds(); + } + + public copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { + WebGLCmdFuncCopyBufferToTexture( + this, + buffer, + (texture as WebGLGFXTexture).gpuTexture, + regions); + } + + public copyImageSourceToTexture (source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { + + if (this._canvas2D) { + const context = this._canvas2D.getContext('2d'); + + if (context) { + this._canvas2D.width = texture.width; + this._canvas2D.height = texture.height; + context.drawImage(source, 0, 0); + + const imgData = context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height); + WebGLCmdFuncCopyBufferToTexture( + this, + imgData.data, + (texture as WebGLGFXTexture).gpuTexture, + regions); + } + } + } + + public copyFramebufferToBuffer ( + srcFramebuffer: GFXFramebuffer, + dstBuffer: ArrayBuffer, + regions: GFXBufferTextureCopy[]) { + + const gl = this._webGLRC as WebGLRenderingContext; + const gpuFramebuffer = (srcFramebuffer as WebGLGFXFramebuffer).gpuFramebuffer; + + const curFBO = this.stateCache.glFramebuffer; + + if (this.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); + this.stateCache.glFramebuffer = gpuFramebuffer.glFramebuffer; + } + + const view = new Uint8Array(dstBuffer); + + for (const region of regions) { + const buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + const w = region.texExtent.width; + const h = region.texExtent.height; + + const memSize = GFXFormatSize(GFXFormat.RGBA8, w, h, 1); + const data = view.subarray(buffOffset, buffOffset + memSize); + + gl.readPixels(region.texOffset.x, region.texOffset.y, w, h, + WebGLRenderingContext.RGBA, WebGLRenderingContext.UNSIGNED_BYTE, data); + } + + if (this.stateCache.glFramebuffer !== curFBO) { + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, curFBO); + this.stateCache.glFramebuffer = curFBO; + } + } + + public emitCmdCreateGPUBuffer (info: IGFXBufferInfo, buffer: GFXBufferSource | null): WebGLGPUBuffer | null { + + const gpuBuffer: WebGLGPUBuffer = { + objType: WebGLGPUObjectType.BUFFER, + usage: info.usage, + memUsage: info.memUsage, + size: info.size, + stride: info.stride ? info.stride : 1, + buffer: null, + vf32: null, + uniforms: [], + indirects: [], + glTarget: 0, + glBuffer: 0, + }; + + if (buffer) { + if (info.usage & GFXBufferUsageBit.INDIRECT) { + gpuBuffer.indirects = (buffer as IGFXIndirectBuffer).drawInfos; + } else { + gpuBuffer.buffer = buffer as ArrayBuffer; + } + } + + // let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; + WebGLCmdFuncCreateBuffer(this as WebGLGFXDevice, gpuBuffer); + + return gpuBuffer; + } + + public emitCmdDestroyGPUBuffer (gpuBuffer: WebGLGPUBuffer) { + + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; + WebGLCmdFuncDestroyBuffer(this, gpuBuffer); + } + + public emitCmdResizeGPUBuffer (gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource | null) { + + if (buffer) { + if ((gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) === GFXBufferUsageBit.NONE) { + gpuBuffer.buffer = buffer as ArrayBuffer; + gpuBuffer.size = gpuBuffer.buffer.byteLength; + } + } + + // TODO: Async + WebGLCmdFuncResizeBuffer(this, gpuBuffer); + } + + public emitCmdUpdateGPUBuffer (gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { + // TODO: Async + const isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; + if (!isStagingBuffer) { + WebGLCmdFuncUpdateBuffer(this, gpuBuffer, buffer, offset, size); + } + } + + public emitCmdCreateGPUTexture (info: IGFXTextureInfo): WebGLGPUTexture { + + let viewType: GFXTextureViewType; + + switch (info.type) { + case GFXTextureType.TEX1D: { + + if (info.arrayLayer) { + viewType = info.arrayLayer <= 1 ? GFXTextureViewType.TV1D : GFXTextureViewType.TV1D_ARRAY; + } else { + viewType = GFXTextureViewType.TV1D; + } + + break; + } + case GFXTextureType.TEX2D: { + let flags = GFXTextureFlagBit.NONE; + if (info.flags) { + flags = info.flags; + } + + if (info.arrayLayer) { + if (info.arrayLayer <= 1) { + viewType = GFXTextureViewType.TV2D; + } else if (info.arrayLayer === 6 && (flags & GFXTextureFlagBit.CUBEMAP)) { + viewType = GFXTextureViewType.CUBE; + } else { + viewType = GFXTextureViewType.TV2D_ARRAY; + } + } else { + viewType = GFXTextureViewType.TV2D; + } + + break; + } + case GFXTextureType.TEX3D: { + viewType = GFXTextureViewType.TV3D; + break; + } + default: { + viewType = GFXTextureViewType.TV2D; + } + } + + const gpuTexture: WebGLGPUTexture = { + objType: WebGLGPUObjectType.TEXTURE, + type: info.type, + viewType, + format: info.format, + usage: info.usage, + width: info.width, + height: info.height, + depth: info.depth ? info.depth : 1, + arrayLayer: info.arrayLayer ? info.arrayLayer : 1, + mipLevel: info.mipLevel ? info.mipLevel : 1, + flags: info.flags ? info.flags : GFXTextureFlagBit.NONE, + + glTarget: 0, + glInternelFmt: 0, + glFormat: 0, + glType: 0, + glUsage: 0, + glTexture: 0, + }; + + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; + WebGLCmdFuncCreateTexture(this, gpuTexture); + + return gpuTexture; + } + + public emitCmdDestroyGPUTexture (gpuTexture: WebGLGPUTexture) { + + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; + WebGLCmdFuncDestroyTexture(this, gpuTexture); + } + + public emitCmdCreateGPUTextureView (info: IGFXTextureViewInfo): WebGLGPUTextureView { + const webGLTexture = info.texture as WebGLGFXTexture; + + const gpuTextureView: WebGLGPUTextureView = { + objType: WebGLGPUObjectType.TEXTURE_VIEW, + gpuTexture: webGLTexture.gpuTexture, + type: info.type, + format: info.format, + baseLevel: info.baseLevel ? info.baseLevel : 0, + levelCount: info.levelCount ? info.levelCount : 1, + }; + + return gpuTextureView; + } + + public emitCmdDestroyGPUTextureView (gpuTextureView: WebGLGPUTextureView) { + } + + public emitCmdCreateGPURenderPass (info: IGFXRenderPassInfo): WebGLGPURenderPass { + const gpuRenderPass: WebGLGPURenderPass = { + objType: WebGLGPUObjectType.RENDER_PASS, + colorAttachments: info.colorAttachments ? info.colorAttachments : [], + depthStencilAttachment: info.depthStencilAttachment ? info.depthStencilAttachment : null, + }; + + return gpuRenderPass; + } + + public emitCmdDestroyGPURenderPass (gpuRenderPass: WebGLGPURenderPass) { + } + + public emitCmdCreateGPUFramebuffer (info: IGFXFramebufferInfo): WebGLGPUFramebuffer { + + const renderPass = info.renderPass as WebGLGFXRenderPass; + + const isOffscreen = info.isOffscreen !== undefined ? info.isOffscreen : true; + if (isOffscreen) { + + const gpuColorViews: WebGLGPUTextureView[] = []; + + if (info.colorViews) { + for (const colorView of info.colorViews) { + const webGLColorView = colorView as WebGLGFXTextureView; + gpuColorViews.push(webGLColorView.gpuTextureView); + } + } + + let gpuDepthStencilView: WebGLGPUTextureView | null = null; + + if (info.depthStencilView) { + gpuDepthStencilView = (info.depthStencilView as WebGLGFXTextureView).gpuTextureView; + } + + const gpuFramebuffer: WebGLGPUFramebuffer = { + objType: WebGLGPUObjectType.FRAMEBUFFER, + gpuRenderPass: renderPass.gpuRenderPass, + gpuColorViews, + gpuDepthStencilView, + isOffscreen: info.isOffscreen, + glFramebuffer: 0, + }; + + // TODO: Async + WebGLCmdFuncCreateFramebuffer(this, gpuFramebuffer); + + return gpuFramebuffer; + + } else { + const gpuFramebuffer: WebGLGPUFramebuffer = { + objType: WebGLGPUObjectType.FRAMEBUFFER, + gpuRenderPass: renderPass.gpuRenderPass, + gpuColorViews: [], + gpuDepthStencilView: null, + isOffscreen: info.isOffscreen, + glFramebuffer: 0, + }; + + return gpuFramebuffer; + } + } + + public emitCmdDestroyGPUFramebuffer (gpuFramebuffer: WebGLGPUFramebuffer) { + if (gpuFramebuffer.isOffscreen) { + // TODO: Async + WebGLCmdFuncDestroyFramebuffer(this, gpuFramebuffer); + } + } + + public emitCmdCreateGPUSampler (info: IGFXSamplerInfo): WebGLGPUSampler { + + let glMinFilter = WebGLRenderingContext.NONE; + let glMagFilter = WebGLRenderingContext.NONE; + + const minFilter = (info.minFilter !== undefined ? info.minFilter : GFXFilter.LINEAR); + const magFilter = (info.magFilter !== undefined ? info.magFilter : GFXFilter.LINEAR); + const mipFilter = (info.mipFilter !== undefined ? info.mipFilter : GFXFilter.NONE); + + if (minFilter === GFXFilter.LINEAR || minFilter === GFXFilter.ANISOTROPIC) { + if (mipFilter === GFXFilter.LINEAR || mipFilter === GFXFilter.ANISOTROPIC) { + glMinFilter = WebGLRenderingContext.LINEAR_MIPMAP_LINEAR; + } else if (mipFilter === GFXFilter.POINT) { + glMinFilter = WebGLRenderingContext.LINEAR_MIPMAP_NEAREST; + } else { + glMinFilter = WebGLRenderingContext.LINEAR; + } + } else { + if (mipFilter === GFXFilter.LINEAR || mipFilter === GFXFilter.ANISOTROPIC) { + glMinFilter = WebGLRenderingContext.NEAREST_MIPMAP_LINEAR; + } else if (mipFilter === GFXFilter.POINT) { + glMinFilter = WebGLRenderingContext.NEAREST_MIPMAP_NEAREST; + } else { + glMinFilter = WebGLRenderingContext.NEAREST; + } + } + + if (magFilter === GFXFilter.LINEAR || magFilter === GFXFilter.ANISOTROPIC) { + glMagFilter = WebGLRenderingContext.LINEAR; + } else { + glMagFilter = WebGLRenderingContext.NEAREST; + } + + const glWrapS = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + const glWrapT = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + const glWrapR = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + + const gpuSampler: WebGLGPUSampler = { + objType: WebGLGPUObjectType.SAMPLER, + + glMinFilter, + glMagFilter, + glWrapS, + glWrapT, + glWrapR, + }; + + return gpuSampler; + } + + public emitCmdDestroyGPUSampler (gpuSampler: WebGLGPUSampler) { + // TODO: Async + } + + public emitCmdCreateGPUShader (info: IGFXShaderInfo): WebGLGPUShader { + + const gpuStages: WebGLGPUShaderStage[] = new Array(info.stages.length); + + for (let i = 0; i < info.stages.length; ++i) { + const stage = info.stages[i]; + gpuStages[i] = { + type: stage.type, + source: stage.source, + macros: stage.macros ? stage.macros : [], + glShader: 0, + }; + } + + const gpuShader: WebGLGPUShader = { + objType: WebGLGPUObjectType.SHADER, + name: info.name ? info.name : '', + blocks: (info.blocks !== undefined ? info.blocks : []), + samplers: (info.samplers !== undefined ? info.samplers : []), + + gpuStages, + glProgram: 0, + glInputs: [], + glUniforms: [], + glBlocks: [], + glSamplers: [], + }; + + // TODO: Async + WebGLCmdFuncCreateShader(this, gpuShader); + + return gpuShader; + } + + public emitCmdDestroyGPUShader (gpuShader: WebGLGPUShader) { + // TODO: Async + WebGLCmdFuncDestroyShader(this, gpuShader); + } + + public emitCmdCreateGPUPipelineState (info: IGFXPipelineStateInfo): WebGLGPUPipelineState { + + let gpuShader: WebGLGPUShader | null = null; + if (info.shader) { + gpuShader = (info.shader as WebGLGFXShader).gpuShader; + } + + let gpuLayout: WebGLGPUPipelineLayout | null = null; + if (info.layout) { + gpuLayout = (info.layout as WebGLGFXPipelineLayout).gpuPipelineLayout; + } + + let gpuRenderPass: WebGLGPURenderPass | null = null; + if (info.renderPass) { + gpuRenderPass = (info.renderPass as WebGLGFXRenderPass).gpuRenderPass; + } + + const gpuPipelineState: WebGLGPUPipelineState = { + objType: WebGLGPUObjectType.PIPELINE_STATE, + glPrimitive: WebGLPrimitives[info.primitive], + gpuShader, + rs: info.rs, + dss: info.dss, + bs: info.bs, + dynamicStates: (info.dynamicStates !== undefined ? info.dynamicStates : []), + gpuLayout, + gpuRenderPass, + }; + + return gpuPipelineState; + } + + public emitCmdDestroyGPUPipelineState (gpuPipelineState: WebGLGPUPipelineState) { + // TODO: Async + } + + public emitCmdCreateGPUBindingLayout (info: IGFXBindingLayoutInfo): WebGLGPUBindingLayout { + + const gpuBindings: WebGLGPUBinding[] = new Array(info.bindings.length); + for (let i = 0; i < info.bindings.length; ++i) { + const binding = info.bindings[i]; + gpuBindings[i] = { + binding: binding.binding, + type: binding.type, + name: binding.name, + gpuBuffer: null, + gpuTexView: null, + gpuSampler: null, + }; + } + + const gpuBindingLayout: WebGLGPUBindingLayout = { + objType: WebGLGPUObjectType.BINDING_LAYOUT, + gpuBindings, + }; + + return gpuBindingLayout; + } + + public emitCmdDestroyGPUBindingLayout (gpuBindingLayout: WebGLGPUBindingLayout) { + // TODO: Async + } + + public emitCmdUpdateGPUBindingLayout (gpuBindingLayout: WebGLGPUBindingLayout, bindingUnits: GFXBindingUnit[]) { + + // TODO: Async + for (let i = 0; i < bindingUnits.length; ++i) { + const bindingUnit = bindingUnits[i]; + const gpuBinding = gpuBindingLayout.gpuBindings[i]; + gpuBinding.binding = bindingUnit.binding; + gpuBinding.type = bindingUnit.type; + gpuBinding.name = bindingUnit.name; + + switch (bindingUnit.type) { + case GFXBindingType.UNIFORM_BUFFER: { + if (bindingUnit.buffer) { + gpuBinding.gpuBuffer = (bindingUnit.buffer as WebGLGFXBuffer).gpuBuffer; + } + break; + } + case GFXBindingType.SAMPLER: { + if (bindingUnit.texView) { + gpuBinding.gpuTexView = (bindingUnit.texView as WebGLGFXTextureView).gpuTextureView; + } + + if (bindingUnit.sampler) { + gpuBinding.gpuSampler = (bindingUnit.sampler as WebGLGFXSampler).gpuSampler; + } + break; + } + default: + } + } + } + + public emitCmdCreateGPUInputAssembler (info: IGFXInputAssemblerInfo): WebGLGPUInputAssembler { + + const gpuVertexBuffers: WebGLGPUBuffer[] = new Array(info.vertexBuffers.length); + + for (let i = 0; i < info.vertexBuffers.length; ++i) { + const vb = info.vertexBuffers[i] as WebGLGFXBuffer; + if (vb.gpuBuffer) { + gpuVertexBuffers[i] = vb.gpuBuffer; + } + } + + let gpuIndexBuffer: WebGLGPUBuffer | null = null; + + let glIndexType = 0; + if (info.indexBuffer) { + gpuIndexBuffer = (info.indexBuffer as WebGLGFXBuffer).gpuBuffer; + if (gpuIndexBuffer) { + switch (gpuIndexBuffer.stride) { + case 1: glIndexType = WebGLRenderingContext.UNSIGNED_BYTE; break; + case 2: glIndexType = WebGLRenderingContext.UNSIGNED_SHORT; break; + case 4: glIndexType = WebGLRenderingContext.UNSIGNED_INT; break; + default: { + console.error('Error index buffer stride.'); + } + } + } + } + + let gpuIndirectBuffer: WebGLGPUBuffer | null = null; + + if (info.indirectBuffer !== undefined) { + gpuIndirectBuffer = (info.indirectBuffer as WebGLGFXBuffer).gpuBuffer; + } + + const gpuInputAssembler: WebGLGPUInputAssembler = { + objType: WebGLGPUObjectType.INPUT_ASSEMBLER, + attributes: info.attributes, + gpuVertexBuffers, + gpuIndexBuffer, + gpuIndirectBuffer, + + glAttribs: [], + glIndexType, + glVAO: 0, + }; + + WebGLCmdFuncCreateInputAssember(this as WebGLGFXDevice, gpuInputAssembler); + + // TODO: Async + return gpuInputAssembler; + } + + public emitCmdDestroyGPUInputAssembler (gpuInputAssembler: WebGLGPUInputAssembler) { + // TODO: Async + // WebGLCmdFuncDestroyInputAssembler(this, gpuInputAssembler); + } + + private initStates (gl: WebGLRenderingContext) { + + gl.activeTexture(gl.TEXTURE0); + gl.pixelStorei(gl.PACK_ALIGNMENT, 1); + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + // rasteriazer state + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0.0, 0.0); + + // depth stencil state + gl.enable(gl.DEPTH_TEST); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + + gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffffffff); + gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP); + gl.stencilMaskSeparate(gl.FRONT, 0xffffffff); + gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffffffff); + gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP); + gl.stencilMaskSeparate(gl.BACK, 0xffffffff); + + gl.disable(gl.STENCIL_TEST); + + // blend state + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.disable(gl.BLEND); + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.colorMask(true, true, true, true); + gl.blendColor(0.0, 0.0, 0.0, 0.0); + } + + private _onWebGLError (error: GLenum, functionName: string, ...args: any[]) { + throw new Error(`${WebGLDeveloperTools.glEnumToString(error)} was caused by call to ${functionName}`); + } +} diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts new file mode 100644 index 0000000000..7e3040bafc --- /dev/null +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -0,0 +1,48 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUFramebuffer } from './webgl-gpu-objects'; + +export class WebGLGFXFramebuffer extends GFXFramebuffer { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuFramebuffer (): WebGLGPUFramebuffer { + return this._gpuFramebuffer!; + } + + private _gpuFramebuffer: WebGLGPUFramebuffer | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXFramebufferInfo): boolean { + + this._renderPass = info.renderPass; + + if (info.colorViews !== undefined) { + this._colorViews = info.colorViews; + } + + this._depthStencilView = info.depthStencilView !== undefined ? info.depthStencilView : null; + this._isOffscreen = info.isOffscreen !== undefined ? info.isOffscreen : true; + + this._gpuFramebuffer = this.webGLDevice.emitCmdCreateGPUFramebuffer(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + + if (this._gpuFramebuffer) { + this.webGLDevice.emitCmdDestroyGPUFramebuffer(this._gpuFramebuffer); + this._gpuFramebuffer = null; + } + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts new file mode 100644 index 0000000000..ea6ab2456e --- /dev/null +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -0,0 +1,286 @@ +import { IGFXDrawInfo } from '../buffer'; +import { + GFXBindingType, + GFXBufferUsage, + GFXBufferUsageBit, + GFXDynamicState, + GFXFormat, + GFXMemoryUsage, + GFXMemoryUsageBit, + GFXShaderType, + GFXTextureFlagBit, + GFXTextureFlags, + GFXTextureType, + GFXTextureUsage, + GFXTextureUsageBit, + GFXTextureViewType, + GFXType, +} from '../define'; +import { IGFXInputAttribute } from '../input-assembler'; +import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../pipeline-state'; +import { GFXColorAttachment, GFXDepthStencilAttachment } from '../render-pass'; +import { GFXUniformBlock, GFXUniformSampler, IGFXShaderMacro } from '../shader'; + +export enum WebGLGPUObjectType { + UNKNOWN, + BUFFER, + TEXTURE, + TEXTURE_VIEW, + RENDER_PASS, + FRAMEBUFFER, + SAMPLER, + SHADER, + PIPELINE_STATE, + BINDING_LAYOUT, + INPUT_ASSEMBLER, + COMMAND_BUFFER, +} + +export class WebGLGPUObject { + public objType: WebGLGPUObjectType; + + constructor (type: WebGLGPUObjectType) { + this.objType = type; + } +} + +export interface IWebGLGPUUniformInfo { + name: string; + type: GFXType; + count: number; + offset: number; + view: Float32Array | Int32Array; + isDirty: boolean; +} + +export class WebGLGPUBuffer extends WebGLGPUObject { + public usage: GFXBufferUsage = GFXBufferUsageBit.NONE; + public memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; + public size: number = 0; + public stride: number = 0; + + public glTarget: GLenum = 0; + public glBuffer: WebGLBuffer = 0; + public buffer: ArrayBuffer | null = null; + public vf32: Float32Array | null = null; + public uniforms: IWebGLGPUUniformInfo[] = []; + public indirects: IGFXDrawInfo[] = []; + + constructor () { + super(WebGLGPUObjectType.BUFFER); + } +} + +export class WebGLGPUTexture extends WebGLGPUObject { + public type: GFXTextureType = GFXTextureType.TEX2D; + public viewType: GFXTextureViewType = GFXTextureViewType.TV2D; + public format: GFXFormat = GFXFormat.UNKNOWN; + public usage: GFXTextureUsage = GFXTextureUsageBit.NONE; + public width: number = 0; + public height: number = 0; + public depth: number = 1; + public arrayLayer: number = 1; + public mipLevel: number = 1; + public flags: GFXTextureFlags = GFXTextureFlagBit.NONE; + + public glTarget: GLenum = 0; + public glInternelFmt: GLenum = 0; + public glFormat: GLenum = 0; + public glType: GLenum = 0; + public glUsage: GLenum = 0; + public glTexture: WebGLTexture = 0; + + constructor () { + super(WebGLGPUObjectType.TEXTURE); + } +} + +export class WebGLGPUTextureView extends WebGLGPUObject { + + public gpuTexture: WebGLGPUTexture; + public type: GFXTextureViewType = GFXTextureViewType.TV2D; + public format: GFXFormat = GFXFormat.UNKNOWN; + public baseLevel: number = 0; + public levelCount: number = 1; + + constructor (texture: WebGLGPUTexture) { + super(WebGLGPUObjectType.TEXTURE_VIEW); + this.gpuTexture = texture; + } +} + +export class WebGLGPURenderPass extends WebGLGPUObject { + + public colorAttachments: GFXColorAttachment[] = []; + public depthStencilAttachment: GFXDepthStencilAttachment | null = null; + + constructor () { + super(WebGLGPUObjectType.RENDER_PASS); + } +} + +export class WebGLGPUFramebuffer extends WebGLGPUObject { + + public gpuRenderPass: WebGLGPURenderPass; + public gpuColorViews: WebGLGPUTextureView[] = []; + public gpuDepthStencilView: WebGLGPUTextureView | null = null; + public isOffscreen?: boolean = false; + + public glFramebuffer: WebGLFramebuffer = 0; + + constructor (gpuRenderPass: WebGLGPURenderPass) { + super(WebGLGPUObjectType.FRAMEBUFFER); + + this.gpuRenderPass = gpuRenderPass; + } +} + +export class WebGLGPUSampler extends WebGLGPUObject { + public glMinFilter: GLenum = WebGLRenderingContext.NONE; + public glMagFilter: GLenum = WebGLRenderingContext.NONE; + public glWrapS: GLenum = WebGLRenderingContext.NONE; + public glWrapT: GLenum = WebGLRenderingContext.NONE; + public glWrapR: GLenum = WebGLRenderingContext.NONE; + + constructor () { + super(WebGLGPUObjectType.SAMPLER); + } +} + +export class WebGLGPUInput { + public binding: number = -1; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public stride: number = 0; + public count: number = 0; + public size: number = 0; + + public glType: GLenum = 0; + public glLoc: GLint = 0; +} + +export interface IWebGLGPUUniform { + binding: number; + name: string; + type: GFXType; + stride: number; + count: number; + size: number; + offset: number; + + glType: GLenum; + glLoc: WebGLUniformLocation; + array: number[]; + begin: number; + isFirst: boolean; +} + +export class WebGLGPUUniformBlock { + public binding: number = -1; + public name: string = ''; + public size: number = 0; + public glUniforms: IWebGLGPUUniform[] = []; + public glActiveUniforms: IWebGLGPUUniform[] = []; + + public isUniformPackage: boolean = false; // Is a single uniform package? +} + +export class WebGLGPUUniformSampler { + public binding: number = -1; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public units: number[] = []; + + public glType: GLenum = 0; + public glLoc: WebGLUniformLocation = -1; +} + +export class WebGLGPUShaderStage { + public type: GFXShaderType = GFXShaderType.VERTEX; + public source: string = ''; + public macros: IGFXShaderMacro[] = []; + public glShader: WebGLShader = 0; +} + +export class WebGLGPUShader extends WebGLGPUObject { + public name: string = ''; + public blocks: GFXUniformBlock[] = []; + public samplers: GFXUniformSampler[] = []; + + public gpuStages: WebGLGPUShaderStage[] = []; + public glProgram: WebGLProgram = 0; + public glInputs: WebGLGPUInput[] = []; + public glUniforms: IWebGLGPUUniform[] = []; + public glBlocks: WebGLGPUUniformBlock[] = []; + public glSamplers: WebGLGPUUniformSampler[] = []; + + constructor () { + super(WebGLGPUObjectType.SHADER); + } +} + +export class WebGLGPUPipelineLayout extends WebGLGPUObject { + +} + +export class WebGLGPUPipelineState extends WebGLGPUObject { + + public glPrimitive: GLenum = WebGLRenderingContext.TRIANGLES; + public gpuShader: WebGLGPUShader | null = null; + public rs: GFXRasterizerState = new GFXRasterizerState(); + public dss: GFXDepthStencilState = new GFXDepthStencilState(); + public bs: GFXBlendState = new GFXBlendState(); + public dynamicStates: GFXDynamicState[] = []; + public gpuLayout: WebGLGPUPipelineLayout | null = null; + public gpuRenderPass: WebGLGPURenderPass | null = null; + + constructor () { + super(WebGLGPUObjectType.PIPELINE_STATE); + } +} + +export class WebGLGPUBinding { + public binding: number = 0; + public type: GFXBindingType = GFXBindingType.UNKNOWN; + public name: string = ''; + public gpuBuffer: WebGLGPUBuffer | null = null; + public gpuTexView: WebGLGPUTextureView | null = null; + public gpuSampler: WebGLGPUSampler | null = null; +} + +export class WebGLGPUBindingLayout extends WebGLGPUObject { + + public gpuBindings: WebGLGPUBinding[] = []; + + constructor () { + super(WebGLGPUObjectType.BINDING_LAYOUT); + } +} + +export class WebGLAttrib { + public name: string = ''; + public glBuffer: WebGLBuffer = 0; + public glType: GLenum = 0; + public size: number = 0; + public count: number = 0; + public stride: number = 0; + public componentCount: number = 1; + public isNormalized: boolean = false; + public isInstanced: boolean = false; + public offset: number = 0; +} + +export class WebGLGPUInputAssembler extends WebGLGPUObject { + public attributes: IGFXInputAttribute[] = []; + public gpuVertexBuffers: WebGLGPUBuffer[] = []; + public gpuIndexBuffer: WebGLGPUBuffer | null = null; + public gpuIndirectBuffer: WebGLGPUBuffer | null = null; + + public glAttribs: WebGLAttrib[] = []; + public glIndexType: GLenum = 0; + public glVAO: WebGLVertexArrayObjectOES = 0; + + constructor () { + super(WebGLGPUObjectType.INPUT_ASSEMBLER); + } +} diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts new file mode 100644 index 0000000000..4622ab0136 --- /dev/null +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -0,0 +1,70 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { WebGLCmdDraw } from './webgl-commands'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUInputAssembler } from './webgl-gpu-objects'; + +export class WebGLGFXInputAssembler extends GFXInputAssembler { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuInputAssembler (): WebGLGPUInputAssembler { + return this._gpuInputAssembler!; + } + + private _gpuInputAssembler: WebGLGPUInputAssembler | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXInputAssemblerInfo): boolean { + + if (info.vertexBuffers.length === 0) { + console.error('GFXInputAssemblerInfo.vertexBuffers is null.'); + return false; + } + + this._attributes = info.attributes; + this._vertexBuffers = info.vertexBuffers; + + if (info.indexBuffer !== undefined) { + this._indexBuffer = info.indexBuffer; + this._indexCount = this._indexBuffer.size / this._indexBuffer.stride; + } else { + const vertBuff = this._vertexBuffers[0]; + this._vertexCount = vertBuff.size / vertBuff.stride; + } + + if (info.indirectBuffer !== undefined) { + this._indirectBuffer = info.indirectBuffer; + } + + this._gpuInputAssembler = this.webGLDevice.emitCmdCreateGPUInputAssembler(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuInputAssembler) { + this.webGLDevice.emitCmdDestroyGPUInputAssembler(this._gpuInputAssembler); + this._gpuInputAssembler = null; + } + this._status = GFXStatus.UNREADY; + } + + public extractCmdDraw (cmd: WebGLCmdDraw) { + cmd.drawInfo.vertexCount = this._vertexCount; + cmd.drawInfo.firstVertex = this._firstVertex; + cmd.drawInfo.indexCount = this._indexCount; + cmd.drawInfo.firstIndex = this._firstIndex; + cmd.drawInfo.vertexOffset = this._vertexOffset; + cmd.drawInfo.instanceCount = this._instanceCount; + cmd.drawInfo.firstInstance = this._firstInstance; + } +} diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts new file mode 100644 index 0000000000..b663db7f79 --- /dev/null +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -0,0 +1,38 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../pipeline-layout'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUPipelineLayout } from './webgl-gpu-objects'; + +export class WebGLGFXPipelineLayout extends GFXPipelineLayout { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuPipelineLayout (): WebGLGPUPipelineLayout { + return this._gpuPipelineLayout!; + } + + private _gpuPipelineLayout: WebGLGPUPipelineLayout | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXPipelineLayoutInfo): boolean { + + this._layouts = info.layouts; + + if (info.pushConstantsRanges !== undefined) { + this._pushConstantsRanges = info.pushConstantsRanges; + } + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-pipeline-state.ts b/cocos/gfx/webgl/webgl-pipeline-state.ts new file mode 100644 index 0000000000..a6cddf6b54 --- /dev/null +++ b/cocos/gfx/webgl/webgl-pipeline-state.ts @@ -0,0 +1,52 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXPipelineState, IGFXPipelineStateInfo } from '../pipeline-state'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUPipelineState } from './webgl-gpu-objects'; + +export class WebGLGFXPipelineState extends GFXPipelineState { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuPipelineState (): WebGLGPUPipelineState { + return this._gpuPipelineState!; + } + + private _gpuPipelineState: WebGLGPUPipelineState | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXPipelineStateInfo): boolean { + + this._primitive = info.primitive; + this._shader = info.shader; + this._is = info.is; + this._rs = info.rs; + this._dss = info.dss; + this._bs = info.bs; + + if (info.dynamicStates !== undefined) { + this._dynamicStates = info.dynamicStates; + } + + this._layout = info.layout; + this._renderPass = info.renderPass; + + this._gpuPipelineState = this.webGLDevice.emitCmdCreateGPUPipelineState(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuPipelineState) { + this.webGLDevice.emitCmdDestroyGPUPipelineState(this._gpuPipelineState); + this._gpuPipelineState = null; + } + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-queue.ts b/cocos/gfx/webgl/webgl-queue.ts new file mode 100644 index 0000000000..99254b0777 --- /dev/null +++ b/cocos/gfx/webgl/webgl-queue.ts @@ -0,0 +1,38 @@ +import { GFXCommandBuffer } from '../command-buffer'; +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXQueue, IGFXQueueInfo } from '../queue'; +import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; +import { WebGLCmdFuncExecuteCmds } from './webgl-commands'; +import { WebGLGFXDevice } from './webgl-device'; + +export class WebGLGFXQueue extends GFXQueue { + + private _isAsync: boolean = false; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXQueueInfo): boolean { + + this._type = info.type; + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + this._status = GFXStatus.UNREADY; + } + + public submit (cmdBuffs: GFXCommandBuffer[], fence?) { + + // TODO: Async + if (!this._isAsync) { + for (const cmdBuff of cmdBuffs) { + WebGLCmdFuncExecuteCmds( this._device as WebGLGFXDevice, (cmdBuff as WebGLGFXCommandBuffer).cmdPackage); + } + } + } +} diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts new file mode 100644 index 0000000000..da6d4d5213 --- /dev/null +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -0,0 +1,47 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXRenderPass, IGFXRenderPassInfo } from '../render-pass'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPURenderPass } from './webgl-gpu-objects'; + +export class WebGLGFXRenderPass extends GFXRenderPass { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuRenderPass (): WebGLGPURenderPass { + return this._gpuRenderPass!; + } + + private _gpuRenderPass: WebGLGPURenderPass | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXRenderPassInfo): boolean { + + if (info.colorAttachments !== undefined) { + this._colorInfos = info.colorAttachments; + } + + if (info.depthStencilAttachment !== undefined) { + this._depthStencilInfo = info.depthStencilAttachment; + } + + this._gpuRenderPass = this.webGLDevice.emitCmdCreateGPURenderPass(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + + if (this._gpuRenderPass) { + this.webGLDevice.emitCmdDestroyGPURenderPass(this._gpuRenderPass); + this._gpuRenderPass = null; + } + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts new file mode 100644 index 0000000000..cc7db9e252 --- /dev/null +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -0,0 +1,92 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXSampler, GFXSamplerState, IGFXSamplerInfo } from '../sampler'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUSampler } from './webgl-gpu-objects'; + +export class WebGLGFXSampler extends GFXSampler { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuSampler (): WebGLGPUSampler { + return this._gpuSampler!; + } + + private _gpuSampler: WebGLGPUSampler | null = null; + + constructor (device: GFXDevice) { + super(device); + + this._state = new GFXSamplerState(); + } + + public initialize (info: IGFXSamplerInfo): boolean { + + if (info.name !== undefined) { + this._state.name = info.name; + } + + if (info.minFilter !== undefined) { + this._state.minFilter = info.minFilter; + } + + if (info.magFilter !== undefined) { + this._state.magFilter = info.magFilter; + } + + if (info.mipFilter !== undefined) { + this._state.mipFilter = info.mipFilter; + } + + if (info.addressU !== undefined) { + this._state.addressU = info.addressU; + } + + if (info.addressV !== undefined) { + this._state.addressV = info.addressV; + } + + if (info.addressW !== undefined) { + this._state.addressW = info.addressW; + } + + if (info.maxAnisotropy !== undefined) { + this._state.maxAnisotropy = info.maxAnisotropy; + } + + if (info.cmpFunc !== undefined) { + this._state.cmpFunc = info.cmpFunc; + } + + if (info.borderColor !== undefined) { + this._state.borderColor = info.borderColor; + } + + if (info.minLOD !== undefined) { + this._state.minLOD = info.minLOD; + } + + if (info.maxLOD !== undefined) { + this._state.maxLOD = info.maxLOD; + } + + if (info.mipLODBias !== undefined) { + this._state.mipLODBias = info.mipLODBias; + } + + this._gpuSampler = this.webGLDevice.emitCmdCreateGPUSampler(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuSampler) { + this.webGLDevice.emitCmdDestroyGPUSampler(this._gpuSampler); + this._gpuSampler = null; + } + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/gfx/webgl/webgl-shader.ts new file mode 100644 index 0000000000..459fcb1fef --- /dev/null +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -0,0 +1,49 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXShader, IGFXShaderInfo } from '../shader'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUShader } from './webgl-gpu-objects'; + +export class WebGLGFXShader extends GFXShader { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuShader (): WebGLGPUShader { + return this._gpuShader!; + } + + private _gpuShader: WebGLGPUShader | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXShaderInfo): boolean { + + this._name = info.name; + this._stages = info.stages; + + if (info.blocks !== undefined) { + this._blocks = info.blocks; + } + + if (info.samplers !== undefined) { + this._samplers = info.samplers; + } + + this._gpuShader = this.webGLDevice.emitCmdCreateGPUShader(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuShader) { + this.webGLDevice.emitCmdDestroyGPUShader(this._gpuShader); + this._gpuShader = null; + } + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts new file mode 100644 index 0000000000..87a373bded --- /dev/null +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -0,0 +1,70 @@ +import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES, IGFXRect, IGFXViewport } from '../define'; +import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../pipeline-state'; + +export interface IWebGLTexUnit { + glTexture: WebGLTexture; + minFilter: GLenum; + magFilter: GLenum; + wrapS: GLenum; + wrapT: GLenum; + wrapR: GLenum; + baseLevel: number; + maxLevel: number; +} + +export class WebGLStateCache { + public glArrayBuffer: WebGLBuffer = 0; + public glElementArrayBuffer: WebGLBuffer = 0; + public texUnit: number = 0; + public glTex2DUnits: IWebGLTexUnit[]; + public glTexCubeUnits: IWebGLTexUnit[]; + public glFramebuffer: WebGLFramebuffer = 0; + public viewport: IGFXViewport; + public scissorRect: IGFXRect; + public rs: GFXRasterizerState; + public dss: GFXDepthStencilState; + public bs: GFXBlendState; + public glProgram: WebGLProgram = 0; + public glEnabledAttribLocs: boolean[]; + public glCurrentAttribLocs: boolean[]; + + constructor () { + this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.viewport = { left: 0.0, top: 0.0, width: 0.0, height: 0.0, minDepth: 0.0, maxDepth: 0.0 }; + this.scissorRect = { x: 0.0, y: 0.0, width: 0.0, height: 0.0 }; + this.rs = new GFXRasterizerState(); + this.dss = new GFXDepthStencilState(); + this.bs = new GFXBlendState(); + this.glEnabledAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); + this.glCurrentAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); + + for (let i = 0; i < GFX_MAX_TEXTURE_UNITS; ++i) { + this.glTex2DUnits[i] = { + glTexture: 0, + minFilter: WebGLRenderingContext.NONE, + magFilter: WebGLRenderingContext.NONE, + wrapS: WebGLRenderingContext.NONE, + wrapT: WebGLRenderingContext.NONE, + wrapR: WebGLRenderingContext.NONE, + baseLevel: 0, + maxLevel: 1000, + }; + this.glTexCubeUnits[i] = { + glTexture: 0, + minFilter: WebGLRenderingContext.NONE, + magFilter: WebGLRenderingContext.NONE, + wrapS: WebGLRenderingContext.NONE, + wrapT: WebGLRenderingContext.NONE, + wrapR: WebGLRenderingContext.NONE, + baseLevel: 0, + maxLevel: 1000, + }; + } + + for (let i = 0; i < GFX_MAX_VERTEX_ATTRIBUTES; ++i) { + this.glEnabledAttribLocs[i] = false; + this.glCurrentAttribLocs[i] = false; + } + } +} diff --git a/cocos/gfx/webgl/webgl-texture-view.ts b/cocos/gfx/webgl/webgl-texture-view.ts new file mode 100644 index 0000000000..632aa95b51 --- /dev/null +++ b/cocos/gfx/webgl/webgl-texture-view.ts @@ -0,0 +1,60 @@ +import { GFXStatus } from '../define'; +import { GFXDevice } from '../device'; +import { GFXTextureView, IGFXTextureViewInfo } from '../texture-view'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUTextureView } from './webgl-gpu-objects'; + +export class WebGLGFXTextureView extends GFXTextureView { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuTextureView (): WebGLGPUTextureView { + return this._gpuTextureView as WebGLGPUTextureView; + } + + private _gpuTextureView: WebGLGPUTextureView | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXTextureViewInfo): boolean { + + this._texture = info.texture; + this._type = info.type; + this._format = info.format; + this._format = info.format; + + if (info.baseLevel !== undefined) { + this._baseLevel = info.baseLevel; + } + + if (info.levelCount !== undefined) { + this._levelCount = info.levelCount; + } + + if (info.baseLayer !== undefined) { + this._baseLayer = info.baseLayer; + } + + if (info.layerCount !== undefined) { + this._layerCount = info.layerCount; + } + + this._gpuTextureView = this.webGLDevice.emitCmdCreateGPUTextureView(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuTextureView) { + this.webGLDevice.emitCmdDestroyGPUTextureView(this._gpuTextureView); + this._gpuTextureView = null; + } + this._texture = null; + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts new file mode 100644 index 0000000000..cdc1428166 --- /dev/null +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -0,0 +1,67 @@ +import { GFXFormatSurfaceSize, GFXStatus, GFXTextureFlagBit } from '../define'; +import { GFXDevice } from '../device'; +import { GFXTexture, IGFXTextureInfo } from '../texture'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUTexture } from './webgl-gpu-objects'; + +export class WebGLGFXTexture extends GFXTexture { + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuTexture (): WebGLGPUTexture { + return this._gpuTexture!; + } + + private _gpuTexture: WebGLGPUTexture | null = null; + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXTextureInfo): boolean { + + this._type = info.type; + this._usage = info.usage; + this._format = info.format; + this._width = info.width; + this._height = info.height; + + if (info.depth !== undefined) { + this._depth = info.depth; + } + + if (info.arrayLayer !== undefined) { + this._arrayLayer = info.arrayLayer; + } + + if (info.mipLevel !== undefined) { + this._mipLevel = info.mipLevel; + } + + if (info.flags !== undefined) { + this._flags = info.flags; + } + + this._size = GFXFormatSurfaceSize(this._format, this.width, this.height, + this.depth, this.mipLevel) * this._arrayLayer; + + if (this._flags & GFXTextureFlagBit.BAKUP_BUFFER) { + this._buffer = new ArrayBuffer(this._size); + } + + this._gpuTexture = this.webGLDevice.emitCmdCreateGPUTexture(info); + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + if (this._gpuTexture) { + this.webGLDevice.emitCmdDestroyGPUTexture(this._gpuTexture); + this._gpuTexture = null; + } + this._status = GFXStatus.UNREADY; + } +} diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts new file mode 100644 index 0000000000..4fa627b833 --- /dev/null +++ b/cocos/gfx/webgl/webgl-window.ts @@ -0,0 +1,184 @@ +import { GFXLoadOp, GFXStatus, GFXStoreOp, GFXTextureLayout } from '../define'; +import { GFXDevice } from '../device'; +import { GFXWindow, IGFXWindowInfo } from '../window'; +import { WebGLGFXDevice } from './webgl-device'; + +export class WebGLGFXWindow extends GFXWindow { + + constructor (device: GFXDevice) { + super(device); + } + + public initialize (info: IGFXWindowInfo): boolean { + + if (info.title !== undefined) { + this._title = info.title; + } + + if (info.left !== undefined) { + this._left = info.left; + } + + if (info.top !== undefined) { + this._top = info.top; + } + + this._width = info.width; + this._height = info.height; + this._colorFmt = info.colorFmt; + this._depthStencilFmt = info.depthStencilFmt; + + this._renderPass = this._device.createRenderPass({ + colorAttachments: [{ + format: this._colorFmt, + loadOp: GFXLoadOp.CLEAR, + storeOp: GFXStoreOp.STORE, + sampleCount: 1, + beginLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, + endLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, + }], + depthStencilAttachment: { + format : this._depthStencilFmt, + depthLoadOp : GFXLoadOp.CLEAR, + depthStoreOp : GFXStoreOp.STORE, + stencilLoadOp : GFXLoadOp.CLEAR, + stencilStoreOp : GFXStoreOp.STORE, + sampleCount : 1, + beginLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + endLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + }, + }); + + if (!this._renderPass) { + this.destroy(); + return false; + } + + /* + this._colorTex = this._device.createTexture({ + type : GFXTextureType.TEX2D, + usage : GFXTextureUsageBit.COLOR_ATTACHMENT, + format : this._colorFmt, + width : this._width, + height : this._height, + depth : 1, + arrayLayer : 1, + mipLevel : 1, + flags : GFXTextureFlagBit.NONE, + }); + + if(!this._colorTex) { + this.destroy(); + return false; + } + + this._colorTexView = this._device.createTextureView({ + texture : this._colorTex, + type : GFXTextureViewType.TV2D, + format : this._colorFmt, + baseLevel : 0, + levelCount : 1, + baseLayer : 0, + layerCount : 1, + }); + + if(!this._colorTexView) { + this.destroy(); + return false; + } + + this._depthStencilTex = this._device.createTexture({ + type : GFXTextureType.TEX2D, + usage : GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT, + format : this._depthStencilFmt, + width : this._width, + height : this._height, + depth : 1, + arrayLayer : 1, + mipLevel : 1, + flags : GFXTextureFlagBit.NONE, + }); + + if(!this._depthStencilTex) { + this.destroy(); + return false; + } + + this._depthStencilTexView = this._device.createTextureView({ + texture : this._depthStencilTex, + type : GFXTextureViewType.TV2D, + format : this._depthStencilFmt, + baseLevel : 0, + levelCount : 1, + baseLayer : 0, + layerCount : 1, + }); + + if(!this._depthStencilTexView) { + this.destroy(); + return false; + } + */ + + this._framebuffer = this._device.createFramebuffer({ + renderPass: this._renderPass, + // colorViews: [this._colorTexView], + // depthStencilView: this._depthStencilTexView, + isOffscreen: false, + }); + + if (!this._framebuffer) { + this.destroy(); + return false; + } + this._status = GFXStatus.SUCCESS; + + return true; + } + + public destroy () { + /* + if(this._depthStencilTexView) { + this._depthStencilTexView.destroy(); + this._depthStencilTexView = null; + } + + if(this._depthStencilTex) { + this._depthStencilTex.destroy(); + this._depthStencilTex = null; + } + + if(this._colorTexView) { + this._colorTexView.destroy(); + this._colorTexView = null; + } + + if(this._colorTex) { + this._colorTex.destroy(); + this._colorTex = null; + } + */ + + if (this._framebuffer) { + this._framebuffer.destroy(); + this._framebuffer = null; + } + + if (this._renderPass) { + this._renderPass.destroy(); + this._renderPass = null; + } + + this._status = GFXStatus.UNREADY; + } + + public resize (width: number, height: number) { + this._width = width; + this._height = height; + } + + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + +} diff --git a/cocos/gfx/window.ts b/cocos/gfx/window.ts new file mode 100644 index 0000000000..1191e16a51 --- /dev/null +++ b/cocos/gfx/window.ts @@ -0,0 +1,65 @@ +import { GFXFormat, GFXObject, GFXObjectType } from './define'; +import { GFXDevice } from './device'; +import { GFXFramebuffer } from './framebuffer'; +import { GFXRenderPass } from './render-pass'; + +export interface IGFXWindowInfo { + title?: string; + left?: number; + top?: number; + width: number; + height: number; + colorFmt: GFXFormat; + depthStencilFmt: GFXFormat; +} + +export abstract class GFXWindow extends GFXObject { + + public get width (): number { + return this._width; + } + + public get height (): number { + return this._height; + } + + public get colorFormat (): GFXFormat { + return this._colorFmt; + } + + public get detphStencilFormat (): GFXFormat { + return this._depthStencilFmt; + } + + public get renderPass (): GFXRenderPass { + return this._renderPass!; + } + + public get framebuffer (): GFXFramebuffer { + return this._framebuffer!; + } + + protected _device: GFXDevice; + protected _title: string = ''; + protected _left: number = 0; + protected _top: number = 0; + protected _width: number = 0; + protected _height: number = 0; + protected _colorFmt: GFXFormat = GFXFormat.UNKNOWN; + protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; + protected _renderPass: GFXRenderPass | null = null; + // protected _colorTex: GFXTexture | null = null; + // protected _colorTexView: GFXTextureView | null = null; + // protected _depthStencilTex: GFXTexture | null = null; + // protected _depthStencilTexView: GFXTextureView | null = null; + protected _framebuffer: GFXFramebuffer | null = null; + + constructor (device: GFXDevice) { + super(GFXObjectType.WINDOW); + this._device = device; + } + + public abstract initialize (info: IGFXWindowInfo): boolean; + public abstract destroy (); + public abstract resize (width: number, height: number); +} diff --git a/cocos/load-pipeline/CCLoader.js b/cocos/load-pipeline/CCLoader.js index a59f35dea6..d67269edd1 100644 --- a/cocos/load-pipeline/CCLoader.js +++ b/cocos/load-pipeline/CCLoader.js @@ -24,30 +24,30 @@ THE SOFTWARE. ****************************************************************************/ -import {createMap, getClassName, isChildClassOf} from '../core/utils/js'; -import {callInNextTick} from '../core/utils/misc'; +import { createMap, getClassName, isChildClassOf } from '../core/utils/js'; +import { callInNextTick } from '../core/utils/misc'; import Pipeline from './pipeline'; import LoadingItems from './loading-items'; import AssetLoader from './asset-loader'; import Downloader from './downloader'; import Loader from './loader'; import AssetTable from './asset-table'; -import {getDependsRecursively} from './auto-release-utils'; +import { getDependsRecursively } from './auto-release-utils'; import ReleasedAssetChecker from './released-asset-checker'; var assetTables = Object.create(null); assetTables.assets = new AssetTable(); assetTables.internal = new AssetTable(); -function getXMLHttpRequest () { +function getXMLHttpRequest() { return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP'); } -var _info = {url: null, raw: false}; +var _info = { url: null, raw: false }; // Convert a resources by finding its real url with uuid, otherwise we will use the uuid or raw url as its url // So we gurantee there will be url in result -function getResWithUrl (res) { +function getResWithUrl(res) { var id, result, isUuid; if (typeof res === 'object') { result = res; @@ -85,7 +85,7 @@ var _sharedList = []; * @static */ class CCLoader extends Pipeline { - constructor () { + constructor() { var assetLoader = new AssetLoader(); var downloader = new Downloader(); var loader = new Loader(); @@ -141,7 +141,7 @@ class CCLoader extends Pipeline { } } - init (director) { + init(director) { if (CC_DEBUG) { var self = this; director.on(cc.Director.EVENT_AFTER_UPDATE, function () { @@ -160,7 +160,7 @@ class CCLoader extends Pipeline { * @method addDownloadHandlers * @param {Object} extMap Custom supported types with corresponded handler */ - addDownloadHandlers (extMap) { + addDownloadHandlers(extMap) { this.downloader.addHandlers(extMap); } @@ -174,7 +174,7 @@ class CCLoader extends Pipeline { * @method addLoadHandlers * @param {Object} extMap Custom supported types with corresponded handler */ - addLoadHandlers (extMap) { + addLoadHandlers(extMap) { this.loader.addHandlers(extMap); } @@ -218,7 +218,7 @@ class CCLoader extends Pipeline { * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, completeCallback?: Function): void * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: Function|null): void */ - load (resources, progressCallback, completeCallback) { + load(resources, progressCallback, completeCallback) { if (CC_DEV && !resources) { return cc.error("[cc.loader.load] resources must be non-nil."); } @@ -235,7 +235,7 @@ class CCLoader extends Pipeline { if (resources) { singleRes = true; resources = [resources]; - } else { + } else { resources = []; } } @@ -285,11 +285,11 @@ class CCLoader extends Pipeline { _sharedResources.length = 0; } - flowInDeps (owner, urlList, callback) { + flowInDeps(owner, urlList, callback) { _sharedList.length = 0; for (var i = 0; i < urlList.length; ++i) { var res = getResWithUrl(urlList[i]); - if (!res.url && ! res.uuid) + if (!res.url && !res.uuid) continue; var item = this._cache[res.url]; if (item) { @@ -321,7 +321,7 @@ class CCLoader extends Pipeline { return accepted; } - _getResUuid (url, type, mount, quiet) { + _getResUuid(url, type, mount, quiet) { mount = mount || 'assets'; var assetTable = assetTables[mount]; if (!url || !assetTable) { @@ -332,7 +332,7 @@ class CCLoader extends Pipeline { if (index !== -1) url = url.substr(0, index); var uuid = assetTable.getUuid(url, type); - if ( !uuid ) { + if (!uuid) { var extname = cc.path.extname(url); if (extname) { // strip extname @@ -346,7 +346,7 @@ class CCLoader extends Pipeline { return uuid; } // Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url - _getReferenceKey (assetOrUrlOrUuid) { + _getReferenceKey(assetOrUrlOrUuid) { var key; if (typeof assetOrUrlOrUuid === 'object') { key = assetOrUrlOrUuid._uuid || null; @@ -362,7 +362,7 @@ class CCLoader extends Pipeline { return this._cache[_info.url] ? _info.url : key; } - _urlNotFound (url, type, completeCallback) { + _urlNotFound(url, type, completeCallback) { callInNextTick(function () { url = cc.url.normalize(url); var info = `${type ? getClassName(type) : 'Asset'} in "resources/${url}" does not exist.`; @@ -381,7 +381,7 @@ class CCLoader extends Pipeline { * @returns {Function} arguments.onProgress * @returns {Function} arguments.onComplete */ - _parseLoadResArgs (type, onProgress, onComplete) { + _parseLoadResArgs(type, onProgress, onComplete) { if (onComplete === undefined) { var isValidType = isChildClassOf(type, cc.RawAsset); if (onProgress) { @@ -451,7 +451,7 @@ class CCLoader extends Pipeline { * loadRes(url: string, completeCallback: (error: Error, resource: any) => void): void * loadRes(url: string): void */ - loadRes (url, type, mount, progressCallback, completeCallback) { + loadRes(url, type, mount, progressCallback, completeCallback) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; @@ -486,7 +486,7 @@ class CCLoader extends Pipeline { } } - _loadResUuids (uuids, progressCallback, completeCallback, urls) { + _loadResUuids(uuids, progressCallback, completeCallback, urls) { if (uuids.length > 0) { var self = this; var res = uuids.map(function (uuid) { @@ -572,7 +572,7 @@ class CCLoader extends Pipeline { * loadResArray(url: string[], completeCallback: (error: Error, resource: any[]) => void): void * loadResArray(url: string[]): void */ - loadResArray (urls, type, mount, progressCallback, completeCallback) { + loadResArray(urls, type, mount, progressCallback, completeCallback) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; @@ -650,14 +650,14 @@ class CCLoader extends Pipeline { * loadResDir(url: string, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void * loadResDir(url: string): void */ - loadResDir (url, type, mount, progressCallback, completeCallback) { + loadResDir(url, type, mount, progressCallback, completeCallback) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; mount = 'assets'; } - - if (!assetTables[mount]) return; + + if (!assetTables[mount]) return; var args = this._parseLoadResArgs(type, progressCallback, completeCallback); type = args.type; @@ -697,7 +697,7 @@ class CCLoader extends Pipeline { * @param {Function} [type] - Only asset of type will be returned if this argument is supplied. * @returns {*} */ - getRes (url, type) { + getRes(url, type) { var item = this._cache[url]; if (!item) { var uuid = this._getResUuid(url, type, null, true); @@ -719,7 +719,7 @@ class CCLoader extends Pipeline { * Get total resources count in loader. * @returns {Number} */ - getResCount () { + getResCount() { return Object.keys(this._cache).length; } @@ -752,7 +752,7 @@ class CCLoader extends Pipeline { * @param {Asset|RawAsset|String} owner - The owner asset or the resource url or the asset's uuid * @returns {Array} */ - getDependsRecursively (owner) { + getDependsRecursively(owner) { if (owner) { var key = this._getReferenceKey(owner); var assets = getDependsRecursively(key); @@ -800,7 +800,7 @@ class CCLoader extends Pipeline { * @method release * @param {Asset|RawAsset|String|Array} asset */ - release (asset) { + release(asset) { if (Array.isArray(asset)) { for (let i = 0; i < asset.length; i++) { var key = asset[i]; @@ -834,7 +834,7 @@ class CCLoader extends Pipeline { * @method releaseAsset * @param {Asset} asset */ - releaseAsset (asset) { + releaseAsset(asset) { var uuid = asset._uuid; if (uuid) { this.release(uuid); @@ -849,7 +849,7 @@ class CCLoader extends Pipeline { * @param {String} url * @param {Function} [type] - Only asset of type will be released if this argument is supplied. */ - releaseRes (url, type, mount) { + releaseRes(url, type, mount) { var uuid = this._getResUuid(url, type, mount); if (uuid) { this.release(uuid); @@ -867,10 +867,10 @@ class CCLoader extends Pipeline { * @param {String} url * @param {Function} [type] - Only asset of type will be released if this argument is supplied. */ - releaseResDir (url, type, mount) { + releaseResDir(url, type, mount) { mount = mount || 'assets'; if (!assetTables[mount]) return; - + var uuids = assetTables[mount].getUuidArray(url, type); for (var i = 0; i < uuids.length; i++) { var uuid = uuids[i]; @@ -884,7 +884,7 @@ class CCLoader extends Pipeline { * * @method releaseAll */ - releaseAll () { + releaseAll() { for (var id in this._cache) { this.release(id); } @@ -893,7 +893,7 @@ class CCLoader extends Pipeline { // AUTO RELEASE // override - removeItem (key) { + removeItem(key) { var removed = Pipeline.prototype.removeItem.call(this, key); delete this._autoReleaseSetting[key]; return removed; @@ -929,7 +929,7 @@ class CCLoader extends Pipeline { * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid * @param {Boolean} autoRelease - indicates whether should release automatically */ - setAutoRelease (assetOrUrlOrUuid, autoRelease) { + setAutoRelease(assetOrUrlOrUuid, autoRelease) { var key = this._getReferenceKey(assetOrUrlOrUuid); if (key) { this._autoReleaseSetting[key] = !!autoRelease; @@ -969,7 +969,7 @@ class CCLoader extends Pipeline { * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid * @param {Boolean} autoRelease - indicates whether should release automatically */ - setAutoReleaseRecursively (assetOrUrlOrUuid, autoRelease) { + setAutoReleaseRecursively(assetOrUrlOrUuid, autoRelease) { autoRelease = !!autoRelease; var key = this._getReferenceKey(assetOrUrlOrUuid); if (key) { @@ -1001,7 +1001,7 @@ class CCLoader extends Pipeline { * @param {Asset|String} assetOrUrl - asset object or the raw asset's url * @returns {Boolean} */ - isAutoRelease (assetOrUrl) { + isAutoRelease(assetOrUrl) { var key = this._getReferenceKey(assetOrUrl); if (key) { return !!this._autoReleaseSetting[key]; diff --git a/cocos/load-pipeline/audio-downloader.js b/cocos/load-pipeline/audio-downloader.js index 2852de7e41..a34643c3b2 100644 --- a/cocos/load-pipeline/audio-downloader.js +++ b/cocos/load-pipeline/audio-downloader.js @@ -29,7 +29,6 @@ import debug from '../core/platform/CCDebug'; var __audioSupport = sys.__audioSupport; var formatSupport = __audioSupport.format; -var context = __audioSupport.context; function loadDomAudio (item, callback) { var dom = document.createElement('audio'); @@ -70,6 +69,7 @@ function loadDomAudio (item, callback) { } function loadWebAudio (item, callback) { + const context = __audioSupport.context; if (!context) callback(new Error(debug.getError(4926))); @@ -115,4 +115,4 @@ export default function downloadAudio (item, callback) { } } loader(item, callback); -} \ No newline at end of file +} diff --git a/cocos/load-pipeline/loader.js b/cocos/load-pipeline/loader.js index 32ef57c48b..20ebe40f51 100644 --- a/cocos/load-pipeline/loader.js +++ b/cocos/load-pipeline/loader.js @@ -25,7 +25,7 @@ ****************************************************************************/ import {mixin} from '../core/utils/js'; -import ImageAsset from '../assets/image-asset'; +import {ImageAsset} from '../assets/image-asset'; import plistParser from './plist-parser'; import Pipeline from './pipeline'; import {loadUuid} from './uuid-loader'; @@ -59,7 +59,7 @@ function loadImage (item) { var image = item.content; if (!CC_WECHATGAME && !CC_QQPLAY && !(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); - } + } // load cc.ImageAsset var rawUrl = item.rawUrl; diff --git a/cocos/load-pipeline/unpackers.js b/cocos/load-pipeline/unpackers.js index 043faa9feb..c772b83b16 100644 --- a/cocos/load-pipeline/unpackers.js +++ b/cocos/load-pipeline/unpackers.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Texture2D from '../assets/texture-2d'; +import {Texture2D} from '../assets/texture-2d'; import {_getClassId} from '../core/utils/js'; export class JsonUnpacker { diff --git a/cocos/pipeline/define.ts b/cocos/pipeline/define.ts new file mode 100644 index 0000000000..ae5cbdb2fb --- /dev/null +++ b/cocos/pipeline/define.ts @@ -0,0 +1,10 @@ + +export enum RenderPassStage { + DEFAULT = 100, +} + +export enum RenderPriority { + MIN = 0, + MAX = 0xff, + DEFAULT = 0x80, +} diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts new file mode 100644 index 0000000000..fff7ab07d8 --- /dev/null +++ b/cocos/pipeline/forward/forward-flow.ts @@ -0,0 +1,58 @@ +import { IRenderFlowInfo, RenderFlow } from '../render-flow'; +import { RenderPipeline } from '../render-pipeline'; +// import { TestStage } from "./test-stage"; +import { TestModelStage } from '../testcase/test-model-stage'; +import { ForwardStage } from './forward-stage'; + +export enum ForwardStagePriority { + FORWARD = 0, +} + +export class ForwardFlow extends RenderFlow { + + constructor (pipeline: RenderPipeline) { + super(pipeline); + } + + public initialize (info: IRenderFlowInfo): boolean { + + if (info.name !== undefined) { + this._name = info.name; + } + + this._priority = info.priority; + + const mainWindow = this._pipeline.root.mainWindow; + if (!mainWindow || !mainWindow.framebuffer) { + return false; + } + + this.createStage(ForwardStage, { + name: 'ForwardStage', + priority: ForwardStagePriority.FORWARD, + framebuffer: mainWindow.framebuffer, + }); + + /* + this.createStage(TestModelStage, { + name: 'TestModelStage', + priority: ForwardStagePriority.FORWARD, + framebuffer: mainWindow.framebuffer, + }); + */ + + /* + this.createStage(TestStage, { + name: 'TestStage', + priority: ForwardStagePriority.FORWARD, + framebuffer: mainWindow.framebuffer, + }); + */ + + return true; + } + + public destroy (): void { + this.destroyStages(); + } +} diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts new file mode 100644 index 0000000000..af8351d9a4 --- /dev/null +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -0,0 +1,65 @@ +import { Root } from '../../core/root'; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXRenderPass } from '../../gfx/render-pass'; +import { RenderPassStage } from '../define'; +import { RenderPipeline, UBOGlobal } from '../render-pipeline'; +import { ForwardFlow } from './forward-flow'; + +export enum ForwardFlowPriority { + FORWARD = 0, +} + +export class ForwardPipeline extends RenderPipeline { + + constructor (root: Root) { + super(root); + } + + public initialize (): boolean { + + if (!this.createQuadInputAssembler()) { + return false; + } + + if (!this.createUBOs()) { + return false; + } + + const mainWindow = this._root.mainWindow; + let windowPass: GFXRenderPass | null = null; + + if (mainWindow) { + windowPass = mainWindow.renderPass; + } + + if (!windowPass) { + console.error('RenderPass of main window is null.'); + return false; + } + + this.addRenderPass(RenderPassStage.DEFAULT, windowPass); + + // create UBOs + this._globalUBO = this._root.device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: UBOGlobal.SIZE, + }); + + // create flows + this.createFlow(ForwardFlow, { + name: 'ForwardFlow', + priority: ForwardFlowPriority.FORWARD, + }); + + return true; + } + + public destroy () { + this.destroyFlows(); + this.clearRenderPasses(); + this.destroyUBOs(); + this.destroyQuadInputAssembler(); + } + +} diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts new file mode 100644 index 0000000000..28d57a5681 --- /dev/null +++ b/cocos/pipeline/forward/forward-stage.ts @@ -0,0 +1,66 @@ +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXCommandBufferType } from '../../gfx/define'; +import { GFXFramebuffer } from '../../gfx/framebuffer'; +import { Camera } from '../../renderer/scene/camera'; +import { RenderFlow } from '../render-flow'; +import { IRenderStageInfo, RenderStage } from '../render-stage'; +import { RenderView } from '../render-view'; + +export class ForwardStage extends RenderStage { + + constructor (flow: RenderFlow) { + super(flow); + } + + public initialize (info: IRenderStageInfo): boolean { + + if (info.name !== undefined) { + this._name = info.name; + } + + this._priority = info.priority; + this._framebuffer = info.framebuffer; + + this._cmdBuff = this._device.createCommandBuffer({ + allocator: this._device.commandAllocator, + type: GFXCommandBufferType.PRIMARY, + }); + + return true; + } + + public destroy () { + + if (this._cmdBuff) { + this._cmdBuff.destroy(); + this._cmdBuff = null; + } + } + + public resize (width: number, height: number) { + } + + public render (view: RenderView) { + + const framebuffer = view.window!.framebuffer; + + const cmdBuff = this._cmdBuff!; + const queue = this._pipeline.queue; + + const camera = view.camera!; + + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; + + cmdBuff.begin(); + cmdBuff.beginRenderPass(framebuffer, this._renderArea, + [camera.clearColor], camera.clearDepth, camera.clearStencil); + + cmdBuff.execute(queue.cmdBuffs.array, queue.cmdBuffCount); + + cmdBuff.endRenderPass(); + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); + } +} diff --git a/cocos/pipeline/index.ts b/cocos/pipeline/index.ts new file mode 100644 index 0000000000..7c6da1eb92 --- /dev/null +++ b/cocos/pipeline/index.ts @@ -0,0 +1,2 @@ +import './define'; +import './render-view'; diff --git a/cocos/pipeline/render-flow.ts b/cocos/pipeline/render-flow.ts new file mode 100644 index 0000000000..4d21aeb177 --- /dev/null +++ b/cocos/pipeline/render-flow.ts @@ -0,0 +1,76 @@ +import { GFXDevice } from '../gfx/device'; +import { Camera } from '../renderer/scene/camera'; +import { RenderPipeline } from './render-pipeline'; +import { IRenderStageInfo, RenderStage } from './render-stage'; +import { RenderView } from './render-view'; + +export interface IRenderFlowInfo { + name?: string; + priority: number; +} + +export abstract class RenderFlow { + + public get device (): GFXDevice { + return this._device; + } + + public get pipeline (): RenderPipeline { + return this._pipeline; + } + + public get priority (): number { + return this._priority; + } + + protected _device: GFXDevice; + protected _pipeline: RenderPipeline; + protected _name: string = ''; + protected _priority: number = 0; + protected _stages: RenderStage[] = []; + protected _material: null = null; // TODO + + constructor (pipeline: RenderPipeline) { + this._device = pipeline.device; + this._pipeline = pipeline; + } + + public abstract initialize (info: IRenderFlowInfo): boolean; + public abstract destroy (); + + public resize (width: number, height: number) { + for (const stage of this._stages) { + stage.resize(width, height); + } + } + + public render (view: RenderView) { + for (const stage of this._stages) { + stage.render(view); + } + } + + public createStage ( + clazz: new(flow: RenderFlow) => T, + info: IRenderStageInfo): RenderStage | null { + + const stage: RenderStage = new clazz(this); + if (stage.initialize(info)) { + this._stages.push(stage); + this._stages.sort((a, b) => { + return a.priority - b.priority; + }); + + return stage; + } else { + return null; + } + } + + public destroyStages () { + for (const stage of this._stages) { + stage.destroy(); + } + this._stages = []; + } +} diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts new file mode 100644 index 0000000000..369f8dad4a --- /dev/null +++ b/cocos/pipeline/render-pipeline.ts @@ -0,0 +1,434 @@ +import { intersect } from '../3d/geom-utils'; +import { Root } from '../core/root'; +import { Mat4 } from '../core/value-types'; +import { mat4, vec3 } from '../core/vmath'; +import { GFXBuffer } from '../gfx/buffer'; +import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXType } from '../gfx/define'; +import { GFXDevice } from '../gfx/device'; +import { GFXInputAssembler, IGFXInputAttribute } from '../gfx/input-assembler'; +import { GFXRenderPass } from '../gfx/render-pass'; +import { GFXUniformBlock } from '../gfx/shader'; +import { GFXTexture } from '../gfx/texture'; +import { GFXTextureView } from '../gfx/texture-view'; +import { IRenderFlowInfo, RenderFlow } from './render-flow'; +import { RenderQueue } from './render-queue'; +import { RenderView } from './render-view'; + +export class UBOGlobal { + public static MAX_DIR_LIGHTS = 4; + public static MAX_POINT_LIGHTS = 4; + public static MAX_SPOT_LIGHTS = 4; + + public static TIME_OFFSET: number = 0; + public static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; + public static SCREEN_SCALE_OFFSET: number = UBOGlobal.SCREEN_SIZE_OFFSET + 4; + public static MAT_VIEW_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4; + public static MAT_VIEW_INV_OFFSET: number = UBOGlobal.MAT_VIEW_OFFSET + 16; + public static MAT_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; + public static MAT_PROJ_INV_OFFSET: number = UBOGlobal.MAT_PROJ_OFFSET + 16; + public static MAT_VIEW_PROJ_OFFSET: number = UBOGlobal.MAT_PROJ_INV_OFFSET + 16; + public static MAT_VIEW_PROJ_INV_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_OFFSET + 16; + public static CAMERA_POS_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET + 16; + public static DIR_LIGHT_DIR_OFFSET: number = UBOGlobal.CAMERA_POS_OFFSET + 4; + public static DIR_LIGHT_COLOR_OFFSET: number = UBOGlobal.DIR_LIGHT_DIR_OFFSET + UBOGlobal.MAX_DIR_LIGHTS * 4; + public static POINT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.DIR_LIGHT_COLOR_OFFSET + UBOGlobal.MAX_DIR_LIGHTS * 4; + public static POINT_LIGHT_COLOR_OFFSET: number = UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + UBOGlobal.MAX_POINT_LIGHTS * 4; + public static SPOT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.POINT_LIGHT_COLOR_OFFSET + UBOGlobal.MAX_POINT_LIGHTS * 4; + public static SPOT_LIGHT_DIR_OFFSET: number = UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + UBOGlobal.MAX_SPOT_LIGHTS * 4; + public static SPOT_LIGHT_COLOR_OFFSET: number = UBOGlobal.SPOT_LIGHT_DIR_OFFSET + UBOGlobal.MAX_SPOT_LIGHTS * 4; + public static COUNT: number = UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + UBOGlobal.MAX_SPOT_LIGHTS * 4; + public static SIZE: number = UBOGlobal.COUNT * 4; + + public static BLOCK: GFXUniformBlock = { + binding: 30, name: 'CCGlobal', members: [ + // constants + { name: 'cc_time', type: GFXType.FLOAT4, count: 1 }, + { name: 'cc_screenSize', type: GFXType.FLOAT4, count: 1 }, + { name: 'cc_screenScale', type: GFXType.FLOAT4, count: 1 }, + // transform + { name: 'cc_matView', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matViewInv', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matProj', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matProjInv', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matViewProj', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matViewProjInv', type: GFXType.MAT4, count: 1 }, + { name: 'cc_cameraPos', type: GFXType.FLOAT4, count: 1 }, + // lights + { name: 'cc_dirLightDirection', type: GFXType.FLOAT4, count: UBOGlobal.MAX_DIR_LIGHTS }, + { name: 'cc_dirLightColor', type: GFXType.FLOAT4, count: UBOGlobal.MAX_DIR_LIGHTS }, + { name: 'cc_pointLightPositionAndRange', type: GFXType.FLOAT4, count: UBOGlobal.MAX_POINT_LIGHTS }, + { name: 'cc_pointLightColor', type: GFXType.FLOAT4, count: UBOGlobal.MAX_POINT_LIGHTS }, + { name: 'cc_spotLightPositionAndRange', type: GFXType.FLOAT4, count: UBOGlobal.MAX_SPOT_LIGHTS }, + { name: 'cc_spotLightDirection', type: GFXType.FLOAT4, count: UBOGlobal.MAX_SPOT_LIGHTS }, + { name: 'cc_spotLightColor', type: GFXType.FLOAT4, count: UBOGlobal.MAX_SPOT_LIGHTS }, + ], + }; + + public view: Float32Array = new Float32Array(UBOGlobal.COUNT); +} + +export class UBOLocal { + public static MAT_WORLD_OFFSET: number = 0; + public static MAT_WORLD_IT_OFFSET: number = UBOLocal.MAT_WORLD_OFFSET + 16; + public static COUNT: number = UBOLocal.MAT_WORLD_IT_OFFSET + 16; + public static SIZE: number = UBOLocal.COUNT * 4; + + public static BLOCK: GFXUniformBlock = { + binding: 31, name: 'CCLocal', members: [ + { name: 'cc_matWorld', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matWorldIT', type: GFXType.MAT4, count: 1 }, + ], + }; + + public view: Float32Array = new Float32Array(UBOLocal.COUNT); +} + +const _idVec4Array = Float32Array.from([0, 0, 0, 1]); +const _vec4Array = new Float32Array(4); +const _mat4Array = new Float32Array(16); +const _outMat = new Mat4(); + +export abstract class RenderPipeline { + + public get root (): Root { + return this._root; + } + + public get device (): GFXDevice { + return this._device; + } + + public get queue (): RenderQueue { + return this._queue; + } + + public get flows (): RenderFlow[] { + return this._flows; + } + + public get quadIA (): GFXInputAssembler { + return this._quadIA!; + } + + public get uboGlobal (): UBOGlobal { + return this._uboGlobal; + } + + public get globalUBO (): GFXBuffer { + return this._globalUBO!; + } + + public get defaultTexture (): GFXTexture { + return this._defaultTex!; + } + + protected _root: Root; + protected _device: GFXDevice; + protected _queue: RenderQueue = new RenderQueue(); + protected _renderPasses: Map = new Map(); + protected _flows: RenderFlow[] = []; + protected _quadVB: GFXBuffer | null = null; + protected _quadIB: GFXBuffer | null = null; + protected _quadIA: GFXInputAssembler | null = null; + protected _uboGlobal: UBOGlobal = new UBOGlobal(); + protected _globalUBO: GFXBuffer | null = null; + protected _defaultTex: GFXTexture | null = null; + protected _defaultTexView: GFXTextureView | null = null; + + constructor (root: Root) { + this._root = root; + this._device = root.device; + } + + public abstract initialize (): boolean; + public abstract destroy (); + + public resize (width: number, height: number) { + for (const flow of this._flows) { + flow.resize(width, height); + } + } + + public render (view: RenderView) { + + view.camera.update(); + + this.sceneCulling(view); + + this.updateUBOs(view); + + for (const flow of this._flows) { + flow.render(view); + } + } + + public addRenderPass (stage: number, renderPass: GFXRenderPass) { + if (renderPass) { + this._renderPasses.set(stage, renderPass); + } + } + + public getRenderPass (stage: number): GFXRenderPass | null { + const renderPass = this._renderPasses.get(stage); + if (renderPass) { + return renderPass; + } else { + return null; + } + } + + public removeRenderPass (stage: number) { + this._renderPasses.delete(stage); + } + + public clearRenderPasses () { + this._renderPasses.clear(); + } + + public createFlow ( + clazz: new (pipeline: RenderPipeline) => T, + info: IRenderFlowInfo, + ): RenderFlow | null { + const flow: RenderFlow = new clazz(this); + if (flow.initialize(info)) { + this._flows.push(flow); + this._flows.sort((a: RenderFlow, b: RenderFlow) => { + return a.priority - b.priority; + }); + + return flow; + } else { + return null; + } + } + + public destroyFlows () { + for (const flow of this._flows) { + flow.destroy(); + } + this._flows = []; + } + + protected createQuadInputAssembler (): boolean { + + // create vertex buffer + + const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; + const vbSize = vbStride * 4; + + this._quadVB = this._device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: vbSize, + stride: vbStride, + }); + + if (!this._quadVB) { + return false; + } + + const verts = new Float32Array(4 * 4); + let n = 0; + verts[n++] = -1.0; verts[n++] = -1.0; verts[n++] = 0.0; verts[n++] = 0.0; + verts[n++] = 1.0; verts[n++] = -1.0; verts[n++] = 1.0; verts[n++] = 0.0; + verts[n++] = -1.0; verts[n++] = 1.0; verts[n++] = 0.0; verts[n++] = 1.0; + verts[n++] = 1.0; verts[n++] = 1.0; verts[n++] = 1.0; verts[n++] = 1.0; + + this._quadVB.update(verts); + + // create index buffer + const ibStride = Uint8Array.BYTES_PER_ELEMENT; + const ibSize = ibStride * 6; + + this._quadIB = this._device.createBuffer({ + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: ibSize, + stride: ibStride, + }); + + if (!this._quadIB) { + return false; + } + + const indices = new Uint8Array(6); + indices[0] = 0; indices[1] = 1; indices[2] = 2; + indices[3] = 1; indices[4] = 3; indices[5] = 2; + + this._quadIB.update(indices); + + // create input assembler + + const attributes: IGFXInputAttribute[] = [ + { name: 'a_position', format: GFXFormat.RG32F }, + { name: 'a_texCoord', format: GFXFormat.RG32F }, + ]; + + this._quadIA = this._device.createInputAssembler({ + attributes, + vertexBuffers: [this._quadVB], + indexBuffer: this._quadIB, + }); + + return true; + } + + protected destroyQuadInputAssembler () { + if (this._quadVB) { + this._quadVB.destroy(); + this._quadVB = null; + } + + if (this._quadIB) { + this._quadIB.destroy(); + this._quadIB = null; + } + + if (this._quadIA) { + this._quadIA.destroy(); + this._quadIA = null; + } + } + + protected createUBOs (): boolean { + this._globalUBO = this._root.device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: UBOGlobal.SIZE, + }); + + if (!this._globalUBO) { + return false; + } + + return true; + } + + protected destroyUBOs () { + if (this._globalUBO) { + this._globalUBO.destroy(); + this._globalUBO = null; + } + } + + protected updateUBOs (view: RenderView) { + + // update UBOGlobal + _vec4Array[0] = this._root.frameTime; + _vec4Array[1] = 0.0; + _vec4Array[2] = 0.0; + _vec4Array[3] = 0.0; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.TIME_OFFSET); + + _vec4Array[0] = this._root.device.width; + _vec4Array[1] = this._root.device.height; + _vec4Array[2] = 1.0 / _vec4Array[0]; + _vec4Array[3] = 1.0 / _vec4Array[1]; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.SCREEN_SIZE_OFFSET); + + _vec4Array[0] = 1.0; + _vec4Array[1] = 1.0; + _vec4Array[2] = 1.0; + _vec4Array[3] = 1.0; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.SCREEN_SCALE_OFFSET); + + const camera = view.camera; + mat4.array(_mat4Array, camera.matView); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_OFFSET); + + mat4.invert(_outMat, camera.matView); + mat4.array(_mat4Array, _outMat); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_INV_OFFSET); + + mat4.array(_mat4Array, camera.matProj); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_OFFSET); + + mat4.invert(_outMat, camera.matProj); + mat4.array(_mat4Array, _outMat); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_INV_OFFSET); + + mat4.array(_mat4Array, camera.matViewProj); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_OFFSET); + + mat4.array(_mat4Array, camera.matViewProjInv); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET); + + vec3.array(_vec4Array, camera.position); + _vec4Array[3] = 1.0; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); + + const scene = view.camera.scene; + const dLights = scene.directionalLights; + for (let i = 0; i < UBOGlobal.MAX_DIR_LIGHTS; i++) { + const light = dLights[i]; + if (light && light.enabled) { + light.update(); + this._uboGlobal.view.set(light.directionArray, UBOGlobal.DIR_LIGHT_DIR_OFFSET + i * 4); + this._uboGlobal.view.set(light.colorData, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + i * 4); + } else { + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.DIR_LIGHT_DIR_OFFSET + i * 4); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + i * 4); + } + } + const pLights = scene.pointLights; + for (let i = 0; i < UBOGlobal.MAX_POINT_LIGHTS; i++) { + const light = pLights[i]; + if (light && light.enabled) { + light.update(); + this._uboGlobal.view.set(light.positionAndRange, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboGlobal.view.set(light.colorData, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + i * 4); + } else { + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + i * 4); + } + } + const sLights = scene.spotLights; + for (let i = 0; i < UBOGlobal.MAX_SPOT_LIGHTS; i++) { + const light = sLights[i]; + if (light && light.enabled) { + light.update(); + this._uboGlobal.view.set(light.positionAndRange, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboGlobal.view.set(light.directionArray, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + i * 4); + this._uboGlobal.view.set(light.colorData, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + i * 4); + } else { + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + i * 4); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + i * 4); + } + } + + // update ubos + this._globalUBO!.update(this._uboGlobal.view); + } + + protected sceneCulling (view: RenderView) { + + const camera = view.camera; + const scene = camera.scene; + + this._queue.clear(); + + for (const model of scene.models) { + + // filter model by view visibility + if (view.visibility > 0 && model.viewID !== view.visibility || !model.enabled) { + continue; + } + + model._updateTransform(); + + // frustum culling + if (model.worldBounds && !intersect.aabb_frustum(model.worldBounds, camera.frustum)) { + // console.log('model is not in view frustum.'); + continue; + } + + model.updateUBOs(); + + // add model pass to render queue + this._queue.add(model, camera); + } + + this._queue.sort(); + } +} diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts new file mode 100644 index 0000000000..4d56c3fc07 --- /dev/null +++ b/cocos/pipeline/render-queue.ts @@ -0,0 +1,113 @@ +import { CachedArray } from '../core/memop/cached-array'; +import { Vec3 } from '../core/value-types'; +import { vec3 } from '../core/vmath'; +import { GFXCommandBuffer } from '../gfx/command-buffer'; +import { Camera } from '../renderer/scene/camera'; +import { Model } from '../renderer/scene/model'; +import { SubModel } from '../renderer/scene/submodel'; + +export interface IRenderItem { + hash: number; + depth: number; + shaderId: number; + subModel: SubModel; + cmdBuff: GFXCommandBuffer; +} + +const _v3tmp = new Vec3(); + +export class RenderQueue { + public opaques: CachedArray; + public transparents: CachedArray; + public cmdBuffs: CachedArray; + public cmdBuffCount: number = 0; + + constructor () { + + // Opaque objects are sorted by depth front to back -> pass priority -> shader id. + const opaqueCompareFn = (a: IRenderItem, b: IRenderItem) => { + if (a.hash === b.hash) { + if (a.depth === b.depth) { + return a.shaderId - b.shaderId; + } else { + return a.depth - b.depth; + } + } else { + return a.hash - b.hash; + } + }; + + // Transparent objects are sorted by depth back to front -> pass priority -> shader id. + const transparentCompareFn = (a: IRenderItem, b: IRenderItem) => { + if (a.hash === b.hash) { + if (a.depth === b.depth) { + return a.shaderId - b.shaderId; + } else { + return b.depth - a.depth; + } + } else { + return a.hash - b.hash; + } + }; + + this.opaques = new CachedArray(64, opaqueCompareFn); + this.transparents = new CachedArray(64, transparentCompareFn); + this.cmdBuffs = new CachedArray(64); + } + + public clear () { + this.opaques.clear(); + this.transparents.clear(); + this.cmdBuffCount = 0; + } + + public add (model: Model, camera: Camera) { + model.node.getWorldPosition(_v3tmp); + vec3.sub(_v3tmp, _v3tmp, camera.position); + const depth = vec3.dot(_v3tmp, camera.forward); + + for (let i = 0; i < model.subModelNum; ++i) { + const subModel = model.getSubModel(i); + for (let p = 0; p < subModel.passes.length; ++p) { + + const pass = subModel.passes[p]; + const pso = subModel.psos[p]; + const isTransparent = pso.blendState.targets[0].blend; + + // TODO: model priority + + if (!isTransparent) { + const hash = (0 << 30) | pass.priority | subModel.priority | p; + + this.opaques.push({ + hash, depth, shaderId: pso.shader.id, + subModel, cmdBuff: subModel.commandBuffers[p]}); + } else { + const hash = (1 << 30) | pass.priority | subModel.priority | p; + + this.transparents.push({ + hash, depth, shaderId: pso.shader.id, + subModel, cmdBuff: subModel.commandBuffers[p]}); + } + } + } + } + + public sort () { + + this.opaques.sort(); + this.transparents.sort(); + + const opaqueCount = this.opaques.length; + const cmdBuffCount = opaqueCount + this.transparents.length; + this.cmdBuffCount = cmdBuffCount; + + for (let i = 0; i < this.opaques.length; ++i) { + this.cmdBuffs.array[i] = this.opaques.array[i].cmdBuff; + } + + for (let i = 0; i < this.transparents.length; ++i) { + this.cmdBuffs.array[opaqueCount + i] = this.transparents.array[i].cmdBuff; + } + } +} diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts new file mode 100644 index 0000000000..9e01792a0b --- /dev/null +++ b/cocos/pipeline/render-stage.ts @@ -0,0 +1,89 @@ +import { GFXCommandBuffer } from '../gfx/command-buffer'; +import { IGFXColor, IGFXRect } from '../gfx/define'; +import { GFXDevice } from '../gfx/device'; +import { GFXFramebuffer } from '../gfx/framebuffer'; +import { Camera } from '../renderer/scene/camera'; +import { RenderFlow } from './render-flow'; +import { RenderPipeline } from './render-pipeline'; +import { RenderView } from './render-view'; + +export interface IRenderStageInfo { + name?: string; + priority: number; + framebuffer: GFXFramebuffer; +} + +export abstract class RenderStage { + + public get flow (): RenderFlow { + return this._flow; + } + + public get pipeline (): RenderPipeline { + return this._pipeline; + } + + public get priority (): number { + return this._priority; + } + + public get framebuffer (): GFXFramebuffer | null { + return this._framebuffer; + } + + protected _flow: RenderFlow; + protected _pipeline: RenderPipeline; + protected _device: GFXDevice; + protected _name: string = ''; + protected _priority: number = 0; + protected _framebuffer: GFXFramebuffer | null = null; + protected _cmdBuff: GFXCommandBuffer | null = null; + protected _clearColors: IGFXColor[]; + protected _clearDepth: number = 1.0; + protected _clearStencil: number = 0; + protected _renderArea: IGFXRect; + + constructor (flow: RenderFlow) { + this._flow = flow; + this._pipeline = flow.pipeline; + this._device = flow.device; + + if (!this._flow.pipeline.root.device) { + throw new Error(''); + } + + this._device = this._flow.pipeline.root.device; + this._clearColors = [{ r: 0.3, g: 0.6, b: 0.9, a: 1.0 }]; + this._renderArea = { x: 0, y: 0, width: 0, height: 0 }; + } + + public abstract initialize (info: IRenderStageInfo): boolean; + public abstract destroy (); + public abstract render (view: RenderView); + public abstract resize (width: number, height: number); + + public setClearColor (color: IGFXColor) { + if (this._clearColors.length > 0) { + this._clearColors[0] = color; + } else { + this._clearColors.push(color); + } + } + + public setClearColors (colors: IGFXColor[]) { + this._clearColors = colors; + } + + public setClearDepth (depth: number) { + this._clearDepth = depth; + } + + public setClearStencil (stencil: number) { + this._clearStencil = stencil; + } + + public setRenderArea (width: number, height: number) { + this._renderArea.width = width; + this._renderArea.height = height; + } +} diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts new file mode 100644 index 0000000000..64e142bb0f --- /dev/null +++ b/cocos/pipeline/render-view.ts @@ -0,0 +1,92 @@ +import { Root } from '../core/root'; +import { GFXWindow } from '../gfx/window'; +import { Camera } from '../renderer/scene/camera'; + +export enum RenderViewPriority { + GENERAL = 100, +} + +export interface IRenderViewInfo { + camera: Camera; + name: string; + priority: number; + isUI: boolean; +} + +export class RenderView { + + public get name () { + return this._name; + } + + public get window () { + return this._window; + } + + public set window (val) { + this._window = val; + } + + public get priority () { + return this._priority; + } + + public set visibility (vis) { + this._visibility = vis; + } + public get visibility () { + return this._visibility; + } + + public get camera () { + return this._camera!; + } + + public get isEnable (): boolean { + return this._isEnable; + } + + public get isUI (): boolean { + return this._isUI; + } + + public static registerCreateFunc (root: Root) { + root._createViewFun = (_root: Root, _camera: Camera): RenderView => new RenderView(_root, _camera); + } + + private _root: Root; + private _name: string = ''; + private _window: GFXWindow | null = null; + private _priority: number = 0; + private _visibility: number = 0; + private _camera: Camera; + private _isEnable: boolean = true; + private _isUI: boolean = false; + + private constructor (root: Root, camera: Camera) { + this._root = root; + this._camera = camera; + } + + public initialize (info: IRenderViewInfo): boolean { + + this._name = info.name; + this._priority = info.priority; + this._isUI = info.isUI; + + return true; + } + + public destroy () { + this._window = null; + this._priority = 0; + } + + public resize (width, height) { + + } + + public enable (isEnable: boolean) { + this._isEnable = isEnable; + } +} diff --git a/cocos/renderer/core/array-buffer-helper.js b/cocos/renderer/core/array-buffer-helper.js index c419e17031..bb660772d4 100644 --- a/cocos/renderer/core/array-buffer-helper.js +++ b/cocos/renderer/core/array-buffer-helper.js @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import enums from '../enums'; +import * as enums from '../enums'; function _defineProperty(target, name, internalName, arrayFn) { target[internalName] = new arrayFn(target._data); diff --git a/cocos/renderer/core/base-renderer.js b/cocos/renderer/core/base-renderer.js deleted file mode 100644 index d8686c2774..0000000000 --- a/cocos/renderer/core/base-renderer.js +++ /dev/null @@ -1,825 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { RecyclePool } from '../../3d/memop'; -import { vec2, vec3, vec4, mat2, mat3, mat4, color3, color4 } from '../../core/vmath'; -import { intersect } from '../../3d/geom-utils'; - -import enums from '../enums'; -import View from './view'; -import ProgramLib from './program-lib'; -import { RenderQueue } from './constants'; - -let _m3_tmp = mat3.create(); -let _m4_tmp = mat4.create(); - -let _camPos = vec3.create(0, 0, 0); -let _camFwd = vec3.create(0, 0, 0); -let _v3_tmp1 = vec3.create(0, 0, 0); - -let _a16_view = new Float32Array(16); -let _a16_proj = new Float32Array(16); -let _a16_viewProj = new Float32Array(16); -let _a3_camPos = new Float32Array(3); - -let _stageInfos = new RecyclePool(() => { - return { - stage: null, - items: null, - }; -}, 8); - -let _float2_pool = new RecyclePool(() => { - return new Float32Array(2); -}, 8); - -let _float3_pool = new RecyclePool(() => { - return new Float32Array(3); -}, 8); - -let _float4_pool = new RecyclePool(() => { - return new Float32Array(4); -}, 8); - -let _float9_pool = new RecyclePool(() => { - return new Float32Array(9); -}, 8); - -let _float16_pool = new RecyclePool(() => { - return new Float32Array(16); -}, 8); - -let _float64_pool = new RecyclePool(() => { - return new Float32Array(64); -}, 8); - -let _int2_pool = new RecyclePool(() => { - return new Int32Array(2); -}, 8); - -let _int3_pool = new RecyclePool(() => { - return new Int32Array(3); -}, 8); - -let _int4_pool = new RecyclePool(() => { - return new Int32Array(4); -}, 8); - -let _int64_pool = new RecyclePool(() => { - return new Int32Array(64); -}, 8); - -let _type2uniformValue = { - [enums.PARAM_INT]: function (value) { - return value; - }, - - [enums.PARAM_INT2]: function (value) { - return vec2.array(_int2_pool.add(), value); - }, - - [enums.PARAM_INT3]: function (value) { - return vec3.array(_int3_pool.add(), value); - }, - - [enums.PARAM_INT4]: function (value) { - return vec4.array(_int4_pool.add(), value); - }, - - [enums.PARAM_FLOAT]: function (value) { - return value; - }, - - [enums.PARAM_FLOAT2]: function (value) { - return vec2.array(_float2_pool.add(), value); - }, - - [enums.PARAM_FLOAT3]: function (value) { - return vec3.array(_float3_pool.add(), value); - }, - - [enums.PARAM_FLOAT4]: function (value) { - return vec4.array(_float4_pool.add(), value); - }, - - [enums.PARAM_COLOR3]: function (value) { - return color3.array(_float3_pool.add(), value); - }, - - [enums.PARAM_COLOR4]: function (value) { - return color4.array(_float4_pool.add(), value); - }, - - [enums.PARAM_MAT2]: function (value) { - return mat2.array(_float4_pool.add(), value); - }, - - [enums.PARAM_MAT3]: function (value) { - return mat3.array(_float9_pool.add(), value); - }, - - [enums.PARAM_MAT4]: function (value) { - return mat4.array(_float16_pool.add(), value); - }, - - // [enums.PARAM_TEXTURE_2D]: function (value) { - // }, - - // [enums.PARAM_TEXTURE_CUBE]: function (value) { - // }, -}; - -let _type2uniformArrayValue = { - [enums.PARAM_INT]: { - func (values) { - let result = _int64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[i] = values[i]; - } - return result; - }, - size: 1, - }, - - [enums.PARAM_INT2]: { - func (values) { - let result = _int64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[2 * i] = values[i].x; - result[2 * i + 1] = values[i].y; - } - return result; - }, - size: 2, - }, - - [enums.PARAM_INT3]: { - func: undefined, - size: 3, - }, - - [enums.PARAM_INT4]: { - func (values) { - let result = _int64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[4 * i] = v.x; - result[4 * i + 1] = v.y; - result[4 * i + 2] = v.z; - result[4 * i + 3] = v.w; - } - return result; - }, - size: 4, - }, - - [enums.PARAM_FLOAT]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[i] = values[i]; - } - return result; - }, - size: 1 - }, - - [enums.PARAM_FLOAT2]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[2 * i] = values[i].x; - result[2 * i + 1] = values[i].y; - } - return result; - }, - size: 2, - }, - - [enums.PARAM_FLOAT3]: { - func: undefined, - size: 3, - }, - - [enums.PARAM_FLOAT4]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[4 * i] = v.x; - result[4 * i + 1] = v.y; - result[4 * i + 2] = v.z; - result[4 * i + 3] = v.w; - } - return result; - }, - size: 4, - }, - - [enums.PARAM_COLOR3]: { - func: undefined, - size: 3, - }, - - [enums.PARAM_COLOR4]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - let scale = v instanceof cc.Color ? 1 / 255 : 1; - result[4 * i] = v.r * scale; - result[4 * i + 1] = v.g * scale; - result[4 * i + 2] = v.b * scale; - result[4 * i + 3] = v.a * scale; - } - return result; - }, - size: 4, - }, - - [enums.PARAM_MAT2]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[4 * i] = v.m00; - result[4 * i + 1] = v.m01; - result[4 * i + 2] = v.m02; - result[4 * i + 3] = v.m03; - } - return result; - }, - size: 4 - }, - - [enums.PARAM_MAT3]: { - func: undefined, - size: 9 - }, - - - [enums.PARAM_MAT4]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[16 * i] = v.m00; - result[16 * i + 1] = v.m01; - result[16 * i + 2] = v.m02; - result[16 * i + 3] = v.m03; - result[16 * i + 4] = v.m04; - result[16 * i + 5] = v.m05; - result[16 * i + 6] = v.m06; - result[16 * i + 7] = v.m07; - result[16 * i + 8] = v.m08; - result[16 * i + 9] = v.m09; - result[16 * i + 10] = v.m10; - result[16 * i + 11] = v.m11; - result[16 * i + 12] = v.m12; - result[16 * i + 13] = v.m13; - result[16 * i + 14] = v.m14; - result[16 * i + 15] = v.m15; - } - return result; - }, - size: 16 - }, - - // [enums.PARAM_TEXTURE_2D]: function (value) { - // }, - - // [enums.PARAM_TEXTURE_CUBE]: function (value) { - // }, -}; - -export default class BaseRenderer { - /** - * @param {gfx.Device} device - */ - constructor(device) { - this._device = device; - this._programLib = new ProgramLib(device); - this._type2defaultValue = { - [enums.PARAM_INT]: 0, - [enums.PARAM_INT2]: vec2.create(0, 0), - [enums.PARAM_INT3]: vec3.create(0, 0, 0), - [enums.PARAM_INT4]: vec4.create(0, 0, 0, 0), - [enums.PARAM_FLOAT]: 0.0, - [enums.PARAM_FLOAT2]: vec2.create(0, 0), - [enums.PARAM_FLOAT3]: vec3.create(0, 0, 0), - [enums.PARAM_FLOAT4]: vec4.create(0, 0, 0, 0), - [enums.PARAM_COLOR3]: color3.create(0, 0, 0), - [enums.PARAM_COLOR4]: color4.create(0, 0, 0, 1), - [enums.PARAM_MAT2]: mat2.create(), - [enums.PARAM_MAT3]: mat3.create(), - [enums.PARAM_MAT4]: mat4.create(), - [enums.PARAM_TEXTURE_2D]: null, - [enums.PARAM_TEXTURE_CUBE]: null, - }; - this._renderQueueFn = {}; - this._stage2fn = {}; - this._modelType2fn = {}; - this._usedTextureUnits = 0; - this.frustum_test_func = intersect.aabb_frustum; - this._accurateFrustumCulling = false; - this._currentView = null; - - this._viewPools = new RecyclePool(() => { - return new View(); - }, 8); - - // store renderable based on material - this._drawItemsPools = new RecyclePool(() => { - return { - model: null, - node: null, - ia: null, - effect: null, - defines: null, - dependencies: null, - }; - }, 100); - - // store renderable based on pass - this._stageItemsPools = new RecyclePool(() => { - return new RecyclePool(() => { - return { - model: null, - node: null, - ia: null, - effect: null, - defines: null, - dependencies: null, - tech: null, - pass: null, - passIndex: 0, - sortKey: -1, - }; - }, 100); - }, 16); - - this._registerRenderQueue('TRANSPARENT', this._renderTransparent.bind(this)); - this._registerRenderQueue('OPAQUE', this._renderOpaque.bind(this)); - this._registerRenderQueue('OVERLAY', this._renderOverlay.bind(this)); - } - - /** - * @param {Object} opts - * @param {gfx.Texture2D} opts.defaultTexture - * @param {gfx.TextureCube} opts.defaultTextureCube - */ - setBuiltins(opts) { - this._opts = opts; - this._type2defaultValue[enums.PARAM_TEXTURE_2D] = opts.defaultTexture; - this._type2defaultValue[enums.PARAM_TEXTURE_CUBE] = opts.defaultTextureCube; - } - - _resetTextureUnit() { - this._usedTextureUnits = 0; - } - - _allocTextureUnit() { - const device = this._device; - - let unit = this._usedTextureUnits; - if (unit >= device._caps.maxTextureUnits) { - console.warn(`Trying to use ${unit} texture units while this GPU supports only ${device._caps.maxTextureUnits}`); - } - - this._usedTextureUnits += 1; - return unit; - } - - _registerRenderQueue(name, fn) { - this._renderQueueFn[name] = fn; - } - - _registerStage(name, fn) { - this._stage2fn[name] = fn; - } - - _registerModel(name, fn) { - this._modelType2fn[name] = fn; - } - - _reset() { - this._currentView = null; - this._viewPools.reset(); - this._stageItemsPools.reset(); - } - - _requestView() { - let view = this._viewPools.add(); - view._frustum.accurate = this._accurateFrustumCulling; - return view; - } - - set accurateFrustumCulling(accurate) { - this._accurateFrustumCulling = accurate; - if (!accurate) this.frustum_test_func = intersect.aabb_frustum; - else this.frustum_test_func = intersect.aabb_frustum_accurate; - } - - _render(view, scene) { - const device = this._device; - this._currentView = view; - - // setup framebuffer - device.setFrameBuffer(view._framebuffer); - - // setup viewport - device.setViewport( - view._rect.x, - view._rect.y, - view._rect.w, - view._rect.h - ); - - // setup clear - let clearOpts = {}; - if (view._clearFlags & enums.CLEAR_COLOR) { - clearOpts.color = [ - view._color.r, - view._color.g, - view._color.b, - view._color.a - ]; - } - if (view._clearFlags & enums.CLEAR_DEPTH) { - clearOpts.depth = view._depth; - } - if (view._clearFlags & enums.CLEAR_STENCIL) { - clearOpts.stencil = view._stencil; - } - device.clear(clearOpts); - - // get all draw items - this._drawItemsPools.reset(); - - if ((view._clearFlags & enums.CLEAR_SKYBOX) && view._clearModel != null) { - let drawItem = this._drawItemsPools.add(); - view._clearModel.extractDrawItem(drawItem); - } - - for (let i = 0; i < scene._models.length; ++i) { - let model = scene._models.data[i]; - - // TODO: HACK: filter model by view - if (view._cullingByID) { - if (model._viewID !== view._id) { - continue; - } - } else { - if (model._viewID !== -1) { - continue; - } - } - - // frustum culling - if (model._boundingShape !== null) { // if model does not have boundingBox, skip culling. - if (!this.frustum_test_func(model._boundingShape, view._frustum)) { - // console.log('model is not in view frustum.'); - continue; - } - } - - let drawItem = this._drawItemsPools.add(); - model.extractDrawItem(drawItem); - } - - // dispatch draw items to different stage - _stageInfos.reset(); - - // for (let i = 0; i < view._stages.length; ++i) { - // let stage = view._stages[i]; - let renderQueues = Object.keys(RenderQueue); - for (let qi = 0; qi < renderQueues.length; qi++) { - this._stageItemsPools.add().reset(); - } - - for (let j = 0; j < this._drawItemsPools.length; ++j) { - let drawItem = this._drawItemsPools.data[j]; - let tech = drawItem.effect.getActiveTechnique(); - - if (tech) { - for (let k = 0; k < tech.passes.length; k++) { - if (!(view._stages & tech._passes[k]._stage)) - continue; - - let stageItem = this._stageItemsPools.data[tech.renderQueue].add(); - stageItem.model = drawItem.model; - stageItem.node = drawItem.node; - stageItem.ia = drawItem.ia; - stageItem.effect = drawItem.effect; - stageItem.defines = drawItem.defines; - stageItem.dependencies = drawItem.dependencies; - stageItem.tech = tech; - stageItem.pass = tech._passes[k]; - stageItem.passIndex = k; - stageItem.sortKey = -1; - } - } - } - - // let stageInfo = _stageInfos.add(); - // stageInfo.stage = stage; - // stageInfo.items = stageItems; - // } - - // render stages - // for (let i = 0; i < _stageInfos.length; ++i) { - // let info = _stageInfos.data[i]; - // let stageFn = this._stage2fn[info.stage]; - - // stageFn(view, info.items); - // } - - for (let qi = 0; qi < renderQueues.length; qi++) { - this._renderQueueFn[renderQueues[qi]](view, this._stageItemsPools.data[qi]); - } - this._stageItemsPools.reset(); - } - - _drawModel(item) { - let model = item.model; - let drawFn = this._modelType2fn[model._type]; - - if (!drawFn) { - // console.warn(`Can not find draw function for modle type ${model.type}`); - return; - } - - drawFn(item); - } - - _draw(item) { - - - // for each pass - // for (let i = 0; i < technique._passes.length; ++i) { - // let pass = technique._passes[i]; - this._stage2fn[item.pass._stage](item); - // } - } - - _isPassSuitable(view, stage) { - return view._stages.includes(stage); - } - - _renderOpaque(view, stageItems) { - - const programLib = this._programLib; - view.getPosition(_camPos); - - // update uniforms - this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - this._device.setUniform('_eye', vec3.array(_a3_camPos, _camPos)); - - // calculate sorting key - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - item.sortKey = programLib.getKey( - item.pass._programName, - item.defines - ); - } - - // sort items - stageItems.sort((a, b) => { - // first,sort by queue - if (a.tech._priority !== b.tech._priority) { - return a.tech._priority - b.tech._priority; - } - // second,sort by shader - return a.sortKey - b.sortKey; - }); - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - - this._drawModel(item); - } - } - - _renderTransparent(view, stageItems) { - - view.getPosition(_camPos); - view.getForward(_camFwd); - - // update uniforms - this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - this._device.setUniform('_eye', vec3.array(_a3_camPos, _camPos)); - - // calculate zdist - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - - // TODO: we should use mesh center instead! - item.node.getWorldPosition(_v3_tmp1); - - vec3.sub(_v3_tmp1, _v3_tmp1, _camPos); - item.sortKey = -vec3.dot(_v3_tmp1, _camFwd); - } - - // sort items - stageItems.sort((a, b) => { - // first, sort by queue - if (a.tech._priority !== b.tech._priority) { - return a.tech._priority - b.tech._priority; - } - // second, sort by distance - return a.sortKey - b.sortKey; - }); - - // draw it - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - - this._drawModel(item); - } - - } - - _renderOverlay(view, stageItems) { - // update uniforms - this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - - // sort items - stageItems.sort((a, b) => { - if (a.tech._priority !== b.tech._priority) { - return a.tech._priority - b.tech._priority; - } - return a.model._userKey - b.model._userKey; - }); - - // draw it - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - this._drawModel(item); - } - } - - _drawPass(item) { - const device = this._device; - const programLib = this._programLib; - const { node, ia, effect, pass, defines, dependencies } = item; - - // reset the pool - // NOTE: we can use drawCounter optimize this - // TODO: should be configurable - _float2_pool.reset(); - _float3_pool.reset(); - _float4_pool.reset(); - _float9_pool.reset(); - _float16_pool.reset(); - _float64_pool.reset(); - _int2_pool.reset(); - _int3_pool.reset(); - _int4_pool.reset(); - _int64_pool.reset(); - - node.getWorldMatrix(_m4_tmp); - device.setUniform('_model', mat4.array(_float16_pool.add(), _m4_tmp)); - - mat3.normalFromMat4(_m3_tmp, _m4_tmp); - device.setUniform('_normalMatrix', mat3.array(_float9_pool.add(), _m3_tmp)); - - // set uniforms - for (let name in effect._properties) { - let propInfo = effect._properties[name]; - let prop = propInfo.value; - - if (prop === undefined || prop === null) { - prop = this._type2defaultValue[propInfo.type]; - } - - if (prop === undefined || prop === null) { - console.warn(`Failed to set technique property ${name}, value not found.`); - continue; - } - - if ( - propInfo.type === enums.PARAM_TEXTURE_2D || - propInfo.type === enums.PARAM_TEXTURE_CUBE - ) { - if (defines['USE_' + name.toUpperCase()] == false) continue; - if (propInfo.size !== undefined) { - if (propInfo.size !== prop.length) { - console.error(`The length of texture array (${prop.length}) is not corrent(expect ${propInfo.size}).`); - continue; - } - let slots = _int64_pool.add(); - for (let index = 0; index < prop.length; ++index) { - slots[index] = this._allocTextureUnit(); - } - device.setTextureArray(name, prop, slots); - } else { - device.setTexture(name, prop, this._allocTextureUnit()); - } - } else { - let convertedValue; - if (propInfo.size !== undefined) { - let convertArray = _type2uniformArrayValue[propInfo.type]; - if (convertArray.func === undefined) { - console.error('Uniform array of color3/int3/float3/mat3 can not be supportted!'); - continue; - } - if (propInfo.size * convertArray.size > 64) { - console.error('Uniform array is too long!'); - continue; - } - convertedValue = convertArray.func(prop); - } else { - let convertFn = _type2uniformValue[propInfo.type]; - convertedValue = convertFn(prop); - } - device.setUniform(name, convertedValue); - } - } - - let count = ia.count; - - // set vertex buffer - device.setVertexBuffer(0, ia._vertexBuffer); - - // set index buffer - if (ia._indexBuffer) { - device.setIndexBuffer(ia._indexBuffer); - } - - // set primitive type - device.setPrimitiveType(ia._primitiveType); - - // set program - let program = programLib.getProgram(pass._programName, defines, dependencies, effect._name); - device.setProgram(program); - - // cull mode - device.setCullMode(pass._cullMode); - - // blend - if (pass._blend) { - device.enableBlend(); - device.setBlendFuncSep( - pass._blendSrc, - pass._blendDst, - pass._blendSrcAlpha, - pass._blendDstAlpha - ); - device.setBlendEqSep( - pass._blendEq, - pass._blendAlphaEq - ); - device.setBlendColor32(pass._blendColor); - } - - // depth test & write - if (pass._depthTest) { - device.enableDepthTest(); - device.setDepthFunc(pass._depthFunc); - } - if (pass._depthWrite) { - device.enableDepthWrite(); - } - - // stencil - if (pass._stencilTest) { - device.enableStencilTest(); - - // front - device.setStencilFuncFront( - pass._stencilFuncFront, - pass._stencilRefFront, - pass._stencilMaskFront - ); - device.setStencilOpFront( - pass._stencilFailOpFront, - pass._stencilZFailOpFront, - pass._stencilZPassOpFront, - pass._stencilWriteMaskFront - ); - - // back - device.setStencilFuncBack( - pass._stencilFuncBack, - pass._stencilRefBack, - pass._stencilMaskBack - ); - device.setStencilOpBack( - pass._stencilFailOpBack, - pass._stencilZFailOpBack, - pass._stencilZPassOpBack, - pass._stencilWriteMaskBack - ); - } - - // draw pass - device.draw(ia._start, count); - - this._resetTextureUnit(); - } -} diff --git a/cocos/renderer/core/buffer-pool.js b/cocos/renderer/core/buffer-pool.js index d9d7052574..c0868f631b 100644 --- a/cocos/renderer/core/buffer-pool.js +++ b/cocos/renderer/core/buffer-pool.js @@ -2,7 +2,7 @@ import { bits } from '../../core/vmath'; import ArrayBufferHelper from './array-buffer-helper'; -import enums from '../enums'; +import * as enums from '../enums'; const _DEFAULT_MAX_BATCH_BYTES = 512000; // 500 kb const _MIN_BATCH_BYTES = 64; diff --git a/cocos/renderer/core/constants.js b/cocos/renderer/core/constants.js deleted file mode 100644 index 59e6ca8938..0000000000 --- a/cocos/renderer/core/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -let RenderQueue = { - OPAQUE: 0, - TRANSPARENT: 1, - OVERLAY: 2 -}; - -let PassStage = { - DEFAULT: 1, - FORWARD: 2, - SHADOWCAST: 4 -}; - -export { RenderQueue, PassStage }; diff --git a/cocos/renderer/core/constants.ts b/cocos/renderer/core/constants.ts new file mode 100644 index 0000000000..9001458f58 --- /dev/null +++ b/cocos/renderer/core/constants.ts @@ -0,0 +1,11 @@ +export enum RenderQueue { + OPAQUE = 0, + TRANSPARENT = 1, + OVERLAY = 2 +}; + +export enum PassStage { + DEFAULT = 1, + FORWARD = 2, + SHADOWCAST = 4 +}; diff --git a/cocos/renderer/core/dynamic-ia-pool.js b/cocos/renderer/core/dynamic-ia-pool.js index c2e6529c7f..70bfa85ecd 100644 --- a/cocos/renderer/core/dynamic-ia-pool.js +++ b/cocos/renderer/core/dynamic-ia-pool.js @@ -4,7 +4,7 @@ import gfx from '../gfx'; import { CircularPool } from '../../3d/memop'; import InputAssembler from './input-assembler'; import BufferPool from './buffer-pool'; -import enums from '../enums'; +import * as enums from '../enums'; let _attr2bufviewType = {}; _attr2bufviewType[gfx.ATTR_TYPE_INT8] = enums.BUFFER_VIEW_INT8; diff --git a/cocos/renderer/core/effect.js b/cocos/renderer/core/effect.js deleted file mode 100644 index af0ca98e13..0000000000 --- a/cocos/renderer/core/effect.js +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import enums from '../enums'; -import Pass from './pass'; -import Technique from './technique'; -import { Vec2, Vec3, Vec4, Color, Mat4 } from '../../core/value-types'; -import { CCObject } from '../../core/data'; -import Texture2D from '../gfx/texture-2d'; -import TextureCube from '../gfx/texture-cube'; - -let _typeMap = { - [enums.PARAM_INT]: Number, - [enums.PARAM_INT2]: Vec2, - [enums.PARAM_INT3]: Vec3, - [enums.PARAM_INT4]: Vec4, - [enums.PARAM_FLOAT]: Number, - [enums.PARAM_FLOAT2]: Vec2, - [enums.PARAM_FLOAT3]: Vec3, - [enums.PARAM_FLOAT4]: Vec4, - [enums.PARAM_COLOR3]: Color, - [enums.PARAM_COLOR4]: Color, - [enums.PARAM_MAT4]: Mat4, - [enums.PARAM_TEXTURE_2D]: Texture2D, - [enums.PARAM_TEXTURE_CUBE]: TextureCube, - number: Number, - boolean: Boolean, - default: CCObject -}; -let getInstanceType = function(t) { return _typeMap[t] || _typeMap.default; }; -let typeCheck = function(value, type) { - let instanceType = getInstanceType(type); - switch (typeof value) { - case 'object': return (value === null) || (value instanceof instanceType); - case 'number': return instanceType === Number; - default: return false; - } -}; - -let _globalTechLod = 600; - -class Effect { - /** - * @param {Array} techniques - */ - constructor(name, techniques, programs, properties = {}, lod = -1) { - this._name = name; - this._techniques = techniques; - this._properties = properties; - this._programs = programs; - this._defines = {}; - this._dependencies = {}; - this._maxLOD = lod; - this.selectTechnique(); - } - - set LOD(lod) { - if (lod === this._maxLOD) { - return; - } - this._maxLOD = lod; - this.selectTechnique(); - } - - clear() { - this._techniques.length = 0; - this._properties = {}; - this._defines = {}; - this._dependencies.length = 0; - } - - getTechnique(index) { - if (index < 0 || index >= this._techniques.length) - return null; - return this._techniques[index]; - } - - getProperty(name) { - if (!this._properties[name]) { - console.warn(`Failed to get property ${name}, property not found.`); - return null; - } - return this._properties[name].value; - } - - setProperty(name, value) { - let prop = this._properties[name]; - if (!prop) { - console.warn(`Failed to set property ${name}, property not found.`); - return; - } - else if (!typeCheck(value, prop.type)) { - console.warn(`Failed to set property ${name}, property type mismatch.`); - return; - } - this._properties[name].value = value; - } - - getDefine(name) { - let def = this._defines[name]; - if (def !== undefined) return def; - console.warn(`Failed to get define ${name}, define not found.`); - return null; - } - - define(name, value) { - if (this._defines[name] !== undefined) this._defines[name] = value; - else console.warn(`Failed to set define ${name}, define not found.`); - } - - extractDefines(out = {}) { - return Object.assign(out, this._defines); - } - - extractDependencies(out = {}) { - return Object.assign(out, this._dependencies); - } - - getActiveTechnique() { - return this._techniques[this._activeTechIdx]; - } - - selectTechnique() { - let lod = this._maxLOD === -1 ? _globalTechLod : this._maxLOD; - this._activeTechIdx = 0; - for (let i = 0; i < this._techniques.length; i++) { - if (this._techniques[i]._lod <= lod) { - this._activeTechIdx = i; - break; - } - } - - // defines - this._defines = {}; - this._techniques[this._activeTechIdx].passes.forEach(pass => this._programs[pass._programName].defines.forEach(def => - this._defines[def.name] = getInstanceCtor(def.type)())); - - // extensions - this._dependencies = {}; - this._techniques[this._activeTechIdx].passes.forEach(pass => this._programs[pass._programName].extensions - .filter(ext => ext.define).forEach(ext => this._dependencies[ext.define] = ext.name)); - } - - static setGlobalLod(lod) { - _globalTechLod = lod; - } -} - -let _ctorMap = { - [Number]: v => v || 0, - [Boolean]: v => v || false, - [Vec2]: v => v ? cc.v2(v[0], v[1]) : cc.v2(), - [Vec3]: v => v ? cc.v3(v[0], v[1], v[2]) : cc.v3(), - [Vec4]: v => v ? cc.v4(v[0], v[1], v[2], v[3]) : cc.v4(), - [Color]: v => v ? cc.color(v[0] * 255, v[1] * 255, v[2] * 255, - (v[3] || 1) * 255) : cc.color(), - [Mat4]: v => v ? cc.mat4( - v[0], v[1], v[2], v[3], - v[4], v[5], v[6], v[7], - v[8], v[9], v[10], v[11], - v[12], v[13], v[14], v[15], - ) : cc.mat4(), - [Texture2D]: () => null, - [TextureCube]: () => null, - [CCObject]: () => null -}; -let getInstanceCtor = function(t) { return _ctorMap[getInstanceType(t)]; }; - -let getInvolvedPrograms = function(effect) { - let programs = {}, lib = cc.game._renderer._programLib; - effect.techniques.forEach(tech => { - tech.passes.forEach(pass => { - programs[pass.program] = lib.getTemplate(pass.program); - }); - }); - return programs; -}; - -let parseProperties = (function() { - function genPropInfo(displayName, type, value) { - return { - type: type, - displayName: displayName, - instanceType: getInstanceType(type), - value: getInstanceCtor(type)(value) - }; - } - return function(effect, programs) { - let props = {}; - // properties may be specified in the shader too - for (let p in programs) { - programs[p].uniforms.forEach(prop => { - if (!prop.property) return; - props[prop.name] = genPropInfo(prop.displayName, prop.type, prop.value); - }); - } - for (let prop in effect.properties) { - let propInfo = effect.properties[prop], uniformInfo; - // always try getting the type from shaders first - if (propInfo.tech !== undefined && propInfo.pass !== undefined) { - let pname = effect.techniques[propInfo.tech].passes[propInfo.pass].program; - uniformInfo = programs[pname].uniforms.find(u => u.name === prop); - } else { - for (let p in programs) { - uniformInfo = programs[p].uniforms.find(u => u.name === prop); - if (uniformInfo) break; - } - } - // the property is not defined in all the shaders used in techs - if (!uniformInfo) { - console.warn(`illegal property: ${prop}`); - continue; - } - // TODO: different param with same name for different passes - props[prop] = genPropInfo( - propInfo.displayName || uniformInfo.displayName, - propInfo.type || uniformInfo.type, - propInfo.value || uniformInfo.value); - } - return props; - }; -})(); - -Effect.parseEffect = function(effect) { - // techniques - let techNum = effect.techniques.length, tech; - let programs = getInvolvedPrograms(effect); - let techniques = new Array(techNum); - for (let j = 0; j < techNum; ++j) { - tech = effect.techniques[j]; - let passNum = tech.passes.length; - let passes = new Array(passNum); - for (let k = 0; k < passNum; ++k) { - let pass = tech.passes[k]; - passes[k] = new Pass(pass.program); - passes[k].setStage(pass.stage); - passes[k].setDepth(pass.depthTest, pass.depthWrite, pass.depthFunc); - passes[k].setCullMode(pass.cullMode); - passes[k].setBlend(pass.blend, pass.blendEq, pass.blendSrc, - pass.blendDst, pass.blendAlphaEq, pass.blendSrcAlpha, pass.blendDstAlpha, pass.blendColor); - passes[k].setStencilFront(pass.stencilTest, pass.stencilFuncFront, pass.stencilRefFront, pass.stencilMaskFront, - pass.stencilFailOpFront, pass.stencilZFailOpFront, pass.stencilZPassOpFront, pass.stencilWriteMaskFront); - passes[k].setStencilBack(pass.stencilTest, pass.stencilFuncBack, pass.stencilRefBack, pass.stencilMaskBack, - pass.stencilFailOpBack, pass.stencilZFailOpBack, pass.stencilZPassOpBack, pass.stencilWriteMaskBack); - } - techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes); - } - // uniforms - let props = parseProperties(effect, programs), uniforms = {}; - for (let pn in programs) { - programs[pn].uniforms.forEach(u => { - let prop = props[u.name]; - uniforms[u.name] = { - type: prop ? prop.type : u.type, - value: prop ? prop.value : getInstanceCtor(u.type)(u.value) - }; - }); - } - - let parsedEffect = new Effect(effect.name, techniques, programs, uniforms); - return parsedEffect; -}; - -if (CC_EDITOR) { - Effect.parseForInspector = function(effect) { - let programs = getInvolvedPrograms(effect); - let props = parseProperties(effect, programs), defines = {}; - for (let pn in programs) { - programs[pn].uniforms.forEach(u => { - let prop = props[u.name]; - if (!prop) return; - prop.defines = u.defines; - }); - programs[pn].defines.forEach(define => { - defines[define.name] = { - instanceType: getInstanceType(define.type), - value: getInstanceCtor(define.type)(), - defines: define.defines - }; - }); - } - return { props, defines }; - }; -} - -export default Effect; -cc.Effect = Effect; diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts new file mode 100644 index 0000000000..125ae93f1d --- /dev/null +++ b/cocos/renderer/core/effect.ts @@ -0,0 +1,46 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { EffectAsset } from '../../3d/assets/effect-asset'; +import { RenderPassStage } from '../../pipeline/define'; +import { IPassInfoFull, Pass } from './pass'; +import { programLib } from './program-lib'; + +export interface IDefineMap { [name: string]: number | boolean; } +export interface IEffectInfo { + techIdx?: number; + defines?: IDefineMap[]; +} + +export class Effect { + public static getPassInfos (effect: EffectAsset, techIdx: number) { + return effect.techniques[techIdx].passes; + } + + public static parseEffect (effect: EffectAsset, info?: IEffectInfo) { + // techniques + const { techIdx, defines } = info || {} as IEffectInfo; + const tech = effect.techniques[techIdx || 0]; + const passNum = tech.passes.length; + const passes: Pass[] = new Array(passNum); + for (let k = 0; k < passNum; ++k) { + const passInfo = tech.passes[k] as IPassInfoFull; + const shader = programLib.getGFXShader(cc.game._gfxDevice, + passInfo.program, defines && defines[k] || {}); + const renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); + const prog = programLib.getTemplate(passInfo.program); + passInfo.blocks = prog.blocks; + passInfo.samplers = prog.samplers; + passInfo.globals = cc.director.root.pipeline.globalUBO; + if (shader) { passInfo.shader = shader; } + else { console.warn(`create shader ${passInfo.program} failed`); } + if (renderPass) { passInfo.renderPass = renderPass; } + else { console.warn(`illegal pass stage in ${effect.name}`); } + const pass = new Pass(cc.game._gfxDevice); + pass.initialize(passInfo); + passes[k] = pass; + } + return passes; + } +} + +cc.Effect = Effect; diff --git a/cocos/renderer/core/input-assembler.js b/cocos/renderer/core/input-assembler.js deleted file mode 100644 index ebe23ca6fb..0000000000 --- a/cocos/renderer/core/input-assembler.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; - -export default class InputAssembler { - constructor(vb, ib, pt = gfx.PT_TRIANGLES) { - this._vertexBuffer = vb; - this._indexBuffer = ib; - this._primitiveType = pt; - this._start = 0; - this._count = -1; - - // TODO: instancing data - // this._stream = 0; - } - - /** - * @property {Number} count The number of indices or vertices to dispatch in the draw call. - */ - get count() { - if (this._count !== -1) { - return this._count; - } - - if (this._indexBuffer) { - return this._indexBuffer.count; - } - - return this._vertexBuffer.count; - } -} \ No newline at end of file diff --git a/cocos/renderer/core/pass.js b/cocos/renderer/core/pass.js deleted file mode 100644 index d1bd128b0b..0000000000 --- a/cocos/renderer/core/pass.js +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; -import { PassStage } from './constants'; - -export default class Pass { - constructor(name) { - this._programName = name; - this._stage = PassStage.DEFAULT; - - // cullmode - this._cullMode = gfx.CULL_BACK; - - // blending - this._blend = false; - this._blendEq = gfx.BLEND_FUNC_ADD; - this._blendAlphaEq = gfx.BLEND_FUNC_ADD; - this._blendSrc = gfx.BLEND_SRC_ALPHA; - this._blendDst = gfx.BLEND_ONE_MINUS_SRC_ALPHA; - this._blendSrcAlpha = gfx.BLEND_ONE; - this._blendDstAlpha = gfx.BLEND_ZERO; - this._blendColor = 0xffffffff; - - // depth - this._depthTest = false; - this._depthWrite = false; - this._depthFunc = gfx.DS_FUNC_LESS, - - // stencil - this._stencilTest = false; - // front - this._stencilFuncFront = gfx.DS_FUNC_ALWAYS; - this._stencilRefFront = 0; - this._stencilMaskFront = 0xff; - this._stencilFailOpFront = gfx.STENCIL_OP_KEEP; - this._stencilZFailOpFront = gfx.STENCIL_OP_KEEP; - this._stencilZPassOpFront = gfx.STENCIL_OP_KEEP; - this._stencilWriteMaskFront = 0xff; - // back - this._stencilFuncBack = gfx.DS_FUNC_ALWAYS; - this._stencilRefBack = 0; - this._stencilMaskBack = 0xff; - this._stencilFailOpBack = gfx.STENCIL_OP_KEEP; - this._stencilZFailOpBack = gfx.STENCIL_OP_KEEP; - this._stencilZPassOpBack = gfx.STENCIL_OP_KEEP; - this._stencilWriteMaskBack = 0xff; - } - - setStage(stage = PassStage.DEFAULT) { - this._stage = stage; - } - - setCullMode(cullMode = gfx.CULL_BACK) { - this._cullMode = cullMode; - } - - setBlend( - enabled = false, - blendEq = gfx.BLEND_FUNC_ADD, - blendSrc = gfx.BLEND_SRC_ALPHA, - blendDst = gfx.BLEND_ONE_MINUS_SRC_ALPHA, - blendAlphaEq = gfx.BLEND_FUNC_ADD, - blendSrcAlpha = gfx.BLEND_SRC_ALPHA, - blendDstAlpha = gfx.BLEND_ONE_MINUS_SRC_ALPHA, - blendColor = 0xffffffff - ) { - this._blend = enabled; - this._blendEq = blendEq; - this._blendSrc = blendSrc; - this._blendDst = blendDst; - this._blendAlphaEq = blendAlphaEq; - this._blendSrcAlpha = blendSrcAlpha; - this._blendDstAlpha = blendDstAlpha; - this._blendColor = blendColor; - } - - setDepth( - depthTest = false, - depthWrite = false, - depthFunc = gfx.DS_FUNC_LESS - ) { - this._depthTest = depthTest; - this._depthWrite = depthWrite; - this._depthFunc = depthFunc; - } - - setStencilFront( - enabled = false, - stencilFunc = gfx.DS_FUNC_ALWAYS, - stencilRef = 0, - stencilMask = 0xff, - stencilFailOp = gfx.STENCIL_OP_KEEP, - stencilZFailOp = gfx.STENCIL_OP_KEEP, - stencilZPassOp = gfx.STENCIL_OP_KEEP, - stencilWriteMask = 0xff - ) { - this._stencilTest = enabled; - this._stencilFuncFront = stencilFunc; - this._stencilRefFront = stencilRef; - this._stencilMaskFront = stencilMask; - this._stencilFailOpFront = stencilFailOp; - this._stencilZFailOpFront = stencilZFailOp; - this._stencilZPassOpFront = stencilZPassOp; - this._stencilWriteMaskFront = stencilWriteMask; - } - - setStencilBack( - enabled = false, - stencilFunc = gfx.DS_FUNC_ALWAYS, - stencilRef = 0, - stencilMask = 0xff, - stencilFailOp = gfx.STENCIL_OP_KEEP, - stencilZFailOp = gfx.STENCIL_OP_KEEP, - stencilZPassOp = gfx.STENCIL_OP_KEEP, - stencilWriteMask = 0xff - ) { - this._stencilTest = enabled; - this._stencilFuncBack = stencilFunc; - this._stencilRefBack = stencilRef; - this._stencilMaskBack = stencilMask; - this._stencilFailOpBack = stencilFailOp; - this._stencilZFailOpBack = stencilZFailOp; - this._stencilZPassOpBack = stencilZPassOp; - this._stencilWriteMaskBack = stencilWriteMask; - } -} diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts new file mode 100644 index 0000000000..9de364d044 --- /dev/null +++ b/cocos/renderer/core/pass.ts @@ -0,0 +1,389 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { IBlockInfo, IPassInfo, ISamplerInfo } from '../../3d/assets/effect-asset'; +import { builtinResMgr } from '../../3d/builtin'; +import { TextureBase } from '../../assets/texture-base'; +import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath'; +import { GFXBindingLayout, IGFXBinding } from '../../gfx/binding-layout'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBindingType, GFXBufferUsageBit, GFXDynamicState, + GFXMemoryUsageBit, GFXPrimitiveMode, GFXType } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; +import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, + GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; +import { GFXRenderPass } from '../../gfx/render-pass'; +import { GFXSampler } from '../../gfx/sampler'; +import { GFXShader } from '../../gfx/shader'; +import { GFXTextureView } from '../../gfx/texture-view'; +import { RenderPassStage, RenderPriority } from '../../pipeline/define'; +import { UBOGlobal } from '../../pipeline/render-pipeline'; + +export interface IPassInfoFull extends IPassInfo { + // generated part + blocks: IBlockInfo[]; + samplers: ISamplerInfo[]; + shader: GFXShader; + renderPass: GFXRenderPass; + globals: GFXBuffer; +} + +type RecursivePartial = { + [P in keyof T]?: + T[P] extends Array ? Array> : + T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; +}; +export type PassOverrides = RecursivePartial; + +const _type2fn = { + [GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, + [GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => vec2.array(a, v, idx * 2), + [GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => vec3.array(a, v, idx * 3), + [GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => vec4.array(a, v, idx * 4), + [GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, + [GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => vec2.array(a, v, idx * 2), + [GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => vec3.array(a, v, idx * 3), + [GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => vec4.array(a, v, idx * 4), + [GFXType.COLOR4]: (a: Float32Array, v: any, idx: number = 0) => color4.array(a, v, idx * 4), + [GFXType.MAT2]: (a: Float32Array, v: any, idx: number = 0) => mat2.array(a, v, idx * 4), + [GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => mat3.array(a, v, idx * 9), + [GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => mat4.array(a, v, idx * 16), +}; + +const _type2default = { + [GFXType.INT]: 0, + [GFXType.INT2]: [0, 0], + [GFXType.INT3]: [0, 0, 0], + [GFXType.INT4]: [0, 0, 0, 0], + [GFXType.FLOAT]: 0, + [GFXType.FLOAT2]: [0, 0], + [GFXType.FLOAT3]: [0, 0, 0], + [GFXType.FLOAT4]: [0, 0, 0, 0], + [GFXType.COLOR4]: [0, 0, 0, 1], + [GFXType.MAT2]: [1, 0, 0, 1], + [GFXType.MAT3]: [1, 0, 0, 0, 1, 0, 0, 0, 1], + [GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + [GFXType.SAMPLER2D]: 'default-texture', + [GFXType.SAMPLER_CUBE]: 'default-cube-texture', +}; + +const builtinRE = /^CC.*?/; + +const btMask = 0xf0000000; // 4 bits, 16 slots +const typeMask = 0x0fc00000; // 6 bits, 64 slots +const bindingMask = 0x003ff800; // 11 bits, 2048 slots +const indexMask = 0x000007ff; // 11 bits, 2048 slots +const genHandle = (bt: GFXBindingType, type: GFXType, binding: number, index: number = 0) => + ((bt << 28) & btMask) | ((type << 22) & typeMask) | ((binding << 11) & bindingMask) | (index & indexMask); +const getBindingTypeFromHandle = (handle: number) => (handle & btMask) >>> 28; +const getTypeFromHandle = (handle: number) => (handle & typeMask) >>> 22; +const getBindingFromHandle = (handle: number) => (handle & bindingMask) >>> 11; +const getIndexFromHandle = (handle: number) => (handle & indexMask); + +interface IBlock { + buffer: ArrayBuffer; + views: Float32Array[]; + dirty: boolean; +} + +interface IPassResources { + bindingLayout: GFXBindingLayout; + pipelineLayout: GFXPipelineLayout; + pipelineState: GFXPipelineState; +} + +interface IPassDynamics { + [type: string]: { + dirty: boolean, + value: number[], + }; +} + +export class Pass { + public static getBindingTypeFromHandle = getBindingTypeFromHandle; + public static getTypeFromHandle = getTypeFromHandle; + public static getBindingFromHandle = getBindingFromHandle; + public static getIndexFromHandle = getIndexFromHandle; + // internal resources + protected _buffers: Record = {}; + protected _samplers: Record = {}; + protected _textureViews: Record = {}; + protected _resources: IPassResources[] = []; + // internal data + protected _programName: string = ''; + protected _priority: RenderPriority = RenderPriority.DEFAULT; + protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + protected _stage: RenderPassStage = RenderPassStage.DEFAULT; + protected _bindings: IGFXBinding[] = []; + protected _bs: GFXBlendState = new GFXBlendState(); + protected _dss: GFXDepthStencilState = new GFXDepthStencilState(); + protected _rs: GFXRasterizerState = new GFXRasterizerState(); + protected _dynamicStates: GFXDynamicState[] = []; + protected _dynamics: IPassDynamics = {}; + protected _handleMap: Record = {}; + protected _blocks: IBlock[] = []; + // external references + protected _device: GFXDevice; + protected _shader: GFXShader | null = null; + protected _renderPass: GFXRenderPass | null = null; + protected _globalUBO: GFXBuffer | null = null; + + public constructor (device: GFXDevice) { + this._device = device; + } + + public initialize (info: IPassInfoFull) { + this._programName = info.program; + // pipeline state + const device = this._device; + this._bindings = info.blocks.map((u) => + ({ name: u.name, binding: u.binding, type: GFXBindingType.UNIFORM_BUFFER }), + ).concat(info.samplers.map((u) => + ({ name: u.name, binding: u.binding, type: GFXBindingType.SAMPLER }), + )); + this._shader = info.shader; + this._renderPass = info.renderPass; + this._globalUBO = info.globals; + this._fillinPipelineInfo(info); + + for (const u of info.blocks) { + if (builtinRE.test(u.name)) { continue; } + // create gfx buffer resource + const buffer = device.createBuffer({ + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: u.size, + stride: 1, // N/A for blocks + usage: GFXBufferUsageBit.UNIFORM, + }); + if (buffer) { this._buffers[u.binding] = buffer; } + else { console.error('create buffer failed.'); return; } + // buffer data processing system + const block: IBlock = this._blocks[u.binding] = { + buffer: buffer.buffer as ArrayBuffer, + dirty: false, + views: [], + }; + u.members.reduce((acc, cur, idx) => { + // create property-specific buffer views + const view = new Float32Array(block.buffer, acc, cur.size / Float32Array.BYTES_PER_ELEMENT); + block.views.push(view); + // store handle map, type and initial value + const inf = info.properties && info.properties[cur.name]; + const type = inf && inf.type || cur.type; // property overloads + const value = inf && inf.value; + view.set(value ? value as number[] : _type2default[type]); + this._handleMap[cur.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, type, u.binding, idx); + // proceed the counter + return acc + cur.size; + }, 0); // === u.size + buffer.update(block.buffer); + } + + for (const u of info.samplers) { + this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); + const inf = info.properties && info.properties[u.name]; + const samplerInfo = Object.assign({ name: u.name }, inf && inf.sampler); + const sampler = device.createSampler(samplerInfo); + if (sampler) { this._samplers[u.binding] = sampler; } + else { console.error('create sampler failed.'); } + const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; + const texture = builtinResMgr.get(texName); + if (texture) { this._textureViews[u.binding] = texture.getGFXTextureView()!; } + else { console.warn(`illegal texture default value ${texName}`); } + } + } + + public getHandle (name: string) { + const handle = this._handleMap[name]; + if (!handle) { console.warn(`illegal property name ${name}`); } + return handle; + } + + public getBinding (name: string) { + return Pass.getBindingFromHandle(this.getHandle(name)); + } + + public setUniform (handle: number, value: any) { + const binding = Pass.getBindingFromHandle(handle); + const type = Pass.getTypeFromHandle(handle); + const idx = Pass.getIndexFromHandle(handle); + const block = this._blocks[binding]; + _type2fn[type](block.views[idx], value); + block.dirty = true; + } + + public setUniformArray (handle: number, value: any[]) { + const binding = Pass.getBindingFromHandle(handle); + const type = Pass.getTypeFromHandle(handle); + const idx = Pass.getIndexFromHandle(handle); + const block = this._blocks[binding]; + for (let i = 0; i < value.length; i++) { + _type2fn[type](block.views[idx], value[i], i); + } + block.dirty = true; + } + + public bindBuffer (binding: number, value: GFXBuffer) { + this._buffers[binding] = value; + for (const res of this._resources) { + res.bindingLayout.bindBuffer(binding, value); + } + } + + public bindTextureView (binding: number, value: GFXTextureView) { + this._textureViews[binding] = value; + for (const res of this._resources) { + res.bindingLayout.bindTextureView(binding, value); + } + } + + public bindSampler (binding: number, value: GFXSampler) { + this._samplers[binding] = value; + for (const res of this._resources) { + res.bindingLayout.bindSampler(binding, value); + } + } + + public setDynamicState (state: GFXDynamicState, value: any) { + const ds = this._dynamics[state]; + if (ds && ds.value === value) { return; } + ds.value = value; ds.dirty = true; + } + + public overridePipelineStates (original: IPassInfo, overrides: PassOverrides) { + this._bs = new GFXBlendState(); + this._dss = new GFXDepthStencilState(); + this._rs = new GFXRasterizerState(); + this._fillinPipelineInfo(original); + this._fillinPipelineInfo(overrides); + } + + public update () { + const len = this._blocks.length; + for (let i = 0; i < len; i++) { + const block = this._blocks[i]; + if (block.dirty) { + this._buffers[i].update(block.buffer); + block.dirty = false; + } + } + } + + public destroy () { + if (this._buffers) { + for (const b of Object.values(this._buffers)) { + b.destroy(); + } + this._buffers = {}; + } + if (this._samplers) { + for (const s of Object.values(this._samplers)) { + s.destroy(); + } + this._samplers = {}; + } + } + + public createPipelineState () { + if (!this._renderPass || !this._shader) { return null; } + const bindingLayout = this._device.createBindingLayout({ bindings: this._bindings }); + for (const b of Object.keys(this._buffers)) { + bindingLayout.bindBuffer(parseInt(b), this._buffers[b]); + } + for (const s of Object.keys(this._samplers)) { + bindingLayout.bindSampler(parseInt(s), this._samplers[s]); + } + for (const t of Object.keys(this._textureViews)) { + bindingLayout.bindTextureView(parseInt(t), this._textureViews[t]); + } + bindingLayout.bindBuffer(UBOGlobal.BLOCK.binding, this._globalUBO!); + const pipelineLayout = this._device.createPipelineLayout({ layouts: [bindingLayout] }); + const pipelineState = this._device.createPipelineState({ + bs: this._bs, + dss: this._dss, + dynamicStates: this._dynamicStates, + is: new GFXInputState(), + layout: pipelineLayout, + primitive: this._primitive, + renderPass: this._renderPass, + rs: this._rs, + shader: this._shader, + }); + this._resources.push({ bindingLayout, pipelineLayout, pipelineState }); + return pipelineState; + } + + public destroyPipelineState (pipelineStates: GFXPipelineState) { + const idx = this._resources.findIndex((res) => res.pipelineState === pipelineStates); + if (idx >= 0) { + const { bindingLayout: bl, pipelineLayout: pl, pipelineState: ps } = this._resources[idx]; + bl.destroy(); pl.destroy(); ps.destroy(); + this._resources.splice(idx, 1); + } + } + + public serializePipelineStates () { + const shaderName = this._shader && this._shader.name; + let res = `${shaderName},${this._stage},${this._primitive}`; + res += serializeBlendState(this._bs); + res += serializeDepthStencilState(this._dss); + res += serializeRasterizerState(this._rs); + return res; + } + + protected _fillinPipelineInfo (info: PassOverrides) { + if (info.priority !== undefined) { this._priority = info.priority; } + if (info.primitive !== undefined) { this._primitive = info.primitive; } + if (info.stage !== undefined) { this._stage = info.stage; } + if (info.dynamics !== undefined) { this._dynamicStates = info.dynamics; } + + const bs = this._bs; + if (info.blendState) { + const bsInfo = Object.assign({}, info.blendState); + if (bsInfo.targets) { + bsInfo.targets.forEach((t, i) => Object.assign( + bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t)); + } + delete bsInfo.targets; + Object.assign(bs, bsInfo); + } + Object.assign(this._rs, info.rasterizerState); + Object.assign(this._dss, info.depthStencilState); + } + + get programName () { return this._programName; } + get priority () { return this._priority; } + get primitive () { return this._primitive; } + get stage () { return this._stage; } + get bindings () { return this._bindings; } + get blendState () { return this._bs; } + get depthStencilState () { return this._dss; } + get rasterizerState () { return this._rs; } + get shader () { return this._shader; } + get renderPass () { return this._renderPass; } + get dynamics () { return this._dynamics; } +} + +function serializeBlendState (bs: GFXBlendState) { + let res = `,bs,${bs.isA2C},${bs.blendColor}`; + for (const t of bs.targets) { + res += `,bt,${t.blend},${t.blendEq},${t.blendAlphaEq},${t.blendColorMask}`; + res += `,${t.blendSrc},${t.blendDst},${t.blendSrcAlpha},${t.blendDstAlpha}`; + } + return res; +} + +function serializeRasterizerState (rs: GFXRasterizerState) { + const res = `,rs,${rs.cullMode},${rs.depthBias},${rs.isFrontFaceCCW}`; + return res; +} + +// tslint:disable: max-line-length +function serializeDepthStencilState (dss: GFXDepthStencilState) { + let res = `,dss,${dss.depthTest},${dss.depthWrite},${dss.depthFunc}`; + res += `,${dss.stencilTestFront},${dss.stencilFuncFront},${dss.stencilRefFront},${dss.stencilReadMaskFront}`; + res += `,${dss.stencilFailOpFront},${dss.stencilZFailOpFront},${dss.stencilPassOpFront},${dss.stencilWriteMaskFront}`; + res += `,${dss.stencilTestBack},${dss.stencilFuncBack},${dss.stencilRefBack},${dss.stencilReadMaskBack}`; + res += `,${dss.stencilFailOpBack},${dss.stencilZFailOpBack},${dss.stencilPassOpBack},${dss.stencilWriteMaskBack}`; + return res; +} diff --git a/cocos/renderer/core/program-lib.js b/cocos/renderer/core/program-lib.js deleted file mode 100644 index 46923aad4f..0000000000 --- a/cocos/renderer/core/program-lib.js +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; - -let _shdID = 0; - -function _generateDefines(device, defs, deps) { - let defines = []; - for (let def in defs) { - let d = defs[def]; - let result = typeof d === 'number' ? d : d ? 1 : 0; - // fallback if extension dependency not supported - if (result && deps[def] && !device.ext(deps[def])) { - console.warn(`${deps[def]} not supported on this platform, disabled ${def}`); - result = 0; - } - defines.push(`#define ${def} ${result}`); - } - return defines.join('\n'); -} - -function _replaceMacroNums(string, defs) { - let cache = {}; - let tmp = string; - for (let def in defs) { - if (Number.isInteger(defs[def])) { - cache[def] = defs[def]; - } - } - for (let def in cache) { - let reg = new RegExp(def, 'g'); - tmp = tmp.replace(reg, cache[def]); - } - return tmp; -} - -function _unrollLoops(string) { - let pattern = /#pragma for (\w+) in range\(\s*(\d+)\s*,\s*(\d+)\s*\)([\s\S]+?)#pragma endFor/g; - function replace(match, index, begin, end, snippet) { - let unroll = ''; - let parsedBegin = parseInt(begin); - let parsedEnd = parseInt(end); - if (parsedBegin.isNaN || parsedEnd.isNaN) { - console.error('Unroll For Loops Error: begin and end of range must be an int num.'); - } - for (let i = parsedBegin; i < parsedEnd; ++i) { - unroll += snippet.replace(new RegExp(`{${index}}`, 'g'), i); - } - return unroll; - } - return string.replace(pattern, replace); -} - -export default class ProgramLib { - /** - * @param {gfx.Device} device - * @param {Array} templates - */ - constructor(device) { - this._device = device; - this._precision = `precision highp float;\n`; - this._templates = {}; - this._cache = {}; - } - - /** - * @param {string} name - * @param {string} vert - * @param {string} frag - * @param {Object[]} defines - * - * @example: - * // this object is auto-generated from your actual shaders - * let program = { - * name: 'foobar', - * vert: vertTmpl, - * frag: fragTmpl, - * defines: [ - * { name: 'shadow', type: 'boolean' }, - * { name: 'lightCount', type: 'number', min: 1, max: 4 } - * ], - * attributes: [{ name: 'a_position', type: 'vec3' }], - * uniforms: [{ name: 'color', type: 'vec4' }], - * extensions: [{ name: 'GL_OES_standard_derivatives', defines: ['USE_NORMAL_TEXTURE'] }], - * }; - * programLib.define(program); - */ - define(prog) { - const { name, defines } = prog; - if (this._templates[name]) return; - - prog.id = ++_shdID; - prog.vert = this._precision + prog.vert; - prog.frag = this._precision + prog.frag; - - // calculate option mask offset - let offset = 0; - for (let i = 0; i < defines.length; ++i) { - let def = defines[i]; - let cnt = 1; - - if (def.type === 'number') { - let range = def.range || []; - def.min = range[0] || 0; - def.max = range[1] || 4; - cnt = Math.ceil(Math.log2(def.max - def.min)); - - def._map = function (value) { - return (value - this.min) << this._offset; - }.bind(def); - } else { // boolean - def._map = function (value) { - if (value) { - return 1 << this._offset; - } - return 0; - }.bind(def); - } - - offset += cnt; - def._offset = offset; - } - - // store it - this._templates[name] = prog; - } - - getTemplate(name) { - return this._templates[name]; - } - - /** - * Does this library has the specified program? - * @param {string} name - * @returns {boolean} - */ - hasProgram(name) { - return this._templates[name] !== undefined; - } - - /** - * @param {string} name - * @param {Object} defines - */ - getKey(name, defines) { - let tmpl = this._templates[name]; - let key = 0; - for (let i = 0; i < tmpl.defines.length; ++i) { - let tmplDefs = tmpl.defines[i]; - let value = defines[tmplDefs.name]; - if (value === undefined) { - continue; - } - - key |= tmplDefs._map(value); - } - - return key << 8 | (tmpl.id & 0xff); - } - - /** - * @param {string} name - * @param {Object} defines - * @param {Object} extensions - */ - getProgram(name, defines, extensions, effectName) { - let key = this.getKey(name, defines); - let program = this._cache[key]; - if (program) { - return program; - } - - // get template - let tmpl = this._templates[name]; - let customDef = _generateDefines(this._device, defines, extensions) + '\n'; - let vert = _replaceMacroNums(tmpl.vert, defines); - vert = customDef + _unrollLoops(vert); - let frag = _replaceMacroNums(tmpl.frag, defines); - frag = customDef + _unrollLoops(frag); - - program = new gfx.Program(this._device, { - vert, - frag - }); - program.link(); - if (!program._linked) { - console.warn(`Failed to link program from effect ${effectName}.`); - } - this._cache[key] = program; - - return program; - } -} diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts new file mode 100644 index 0000000000..1f7932888c --- /dev/null +++ b/cocos/renderer/core/program-lib.ts @@ -0,0 +1,193 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { IBlockInfo, IBlockMember, IDefineInfo, IShaderInfo, ISamplerInfo } from '../../3d/assets/effect-asset'; +import { GFXGetTypeSize, GFXShaderType } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXShader, GFXUniform, GFXUniformBlock, GFXUniformSampler } from '../../gfx/shader'; +import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; +import { SkinningUBO } from '../models/model-uniforms'; +import { IDefineMap } from './effect'; + +function _generateDefines ( + device: GFXDevice, + defs: IDefineMap, + tDefs: IDefineInfo[], + deps: Record, +) { + const defines: string[] = []; + for (const { name } of tDefs) { + const d = defs[name]; + let result = (typeof d === 'number') ? d : (d ? 1 : 0); + // fallback if extension dependency not supported + if (result && deps[name] && !device[deps[name]]) { + console.warn(`${deps[name]} not supported on this platform, disabled ${name}`); + result = 0; + } + defines.push(`#define ${name} ${result}`); + } + return defines.join('\n'); +} + +let _shdID = 0; +interface IDefineRecord extends IDefineInfo { + _map: (value: any) => number; + _offset: number; +} +interface IProgramInfo extends IShaderInfo { + id: number; + defines: IDefineRecord[]; +} + +class ProgramLib { + protected _precision: string; + protected _templates: Record; + protected _cache: Record; + + constructor () { + this._precision = `precision highp float;\n`; + this._templates = {}; + this._cache = {}; + } + + /** + * @example: + * // this object is auto-generated from your actual shaders + * let program = { + * name: 'foobar', + * vert: vertTmpl, + * frag: fragTmpl, + * defines: [ + * { name: 'shadow', type: 'boolean' }, + * { name: 'lightCount', type: 'number', range: [1, 4] } + * ], + * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [ + * { name: 'color', type: 'vec4' }], defines: [] } + * ], + * dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' }, + * }; + * programLib.define(program); + */ + public define (prog: IShaderInfo) { + if (this._templates[prog.name]) { return; } + const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo; + tmpl.vert = this._precision + prog.vert; + tmpl.frag = this._precision + prog.frag; + tmpl.blocks = tmpl.blocks.concat(globals, locals); + + // calculate option mask offset + let offset = 0; + for (const def of tmpl.defines) { + let cnt = 1; + if (def.type === 'number') { + const range = def.range || [0, 4]; + cnt = Math.ceil(Math.log2(range[1] - range[0])); + def._map = ((value: number) => (value - range[0]) << def._offset); + } else { // boolean + def._map = ((value: any) => (value ? (1 << def._offset) : 0)); + } + if (def.name === 'CC_USE_SKINNING') { + tmpl.blocks = tmpl.blocks.concat(skinning); + } else if (def.name === 'CC_USE_JOINTS_TEXTURE') { + tmpl.samplers = tmpl.samplers.concat(jointsTexture); + } + offset += cnt; + def._offset = offset; + } + // store it + this._templates[prog.name] = tmpl; + } + + public getTemplate (name: string) { + return this._templates[name]; + } + + /** + * Does this library has the specified program? + */ + public hasProgram (name: string) { + return this._templates[name] !== undefined; + } + + public getKey (name: string, defines: IDefineMap) { + const tmpl = this._templates[name]; + let key = 0; + for (const tmplDef of tmpl.defines) { + const value = defines[tmplDef.name]; + if (value === undefined || !tmplDef._map) { + continue; + } + key |= tmplDef._map(value); + } + return key << 8 | (tmpl.id & 0xff); + } + + public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap = {}) { + const key = this.getKey(name, defines); + let program = this._cache[key]; + if (program !== undefined) { + return program; + } + + // get template + const tmpl = this._templates[name]; + const customDef = _generateDefines(device, defines, tmpl.defines, tmpl.dependencies) + '\n'; + const vert = customDef + tmpl.vert; + const frag = customDef + tmpl.frag; + + const instanceName = Object.keys(defines).reduce((acc, cur) => defines[cur] ? `${acc}|${cur}` : acc, name); + program = device.createShader({ + name: instanceName, + blocks: tmpl.blocks, + samplers: tmpl.samplers, + stages: [ + { type: GFXShaderType.VERTEX, source: vert }, + { type: GFXShaderType.FRAGMENT, source: frag }, + ], + }); + this._cache[key] = program; + return program; + } +} + +const globals = convertToBlockInfo(UBOGlobal.BLOCK); +const locals = convertToBlockInfo(UBOLocal.BLOCK); +const skinning = convertToBlockInfo(SkinningUBO.BLOCK); +const jointsTexture = convertToSamplerInfo(SkinningUBO.JOINT_TEXTURE); + +function convertToUniformInfo (uniform: GFXUniform): IBlockMember { + return { + name: uniform.name, + type: uniform.type, + count: uniform.count, + size: GFXGetTypeSize(uniform.type) * uniform.count, + }; +} + +function convertToBlockInfo (block: GFXUniformBlock): IBlockInfo { + const members: IBlockMember[] = []; + let size: number = 0; + for (let i = 0; i < block.members.length; i++) { + members.push(convertToUniformInfo(block.members[i])); + size += members[i].size; + } + return { + name: block.name, + binding: block.binding, + defines: [], + members, + size, + }; +} + +function convertToSamplerInfo (sampler: GFXUniformSampler): ISamplerInfo { + return { + name: sampler.name, + binding: sampler.binding, + defines: [], + type: sampler.type, + count: sampler.count + }; +} + +const programLib = cc.programLib = new ProgramLib(); +export { programLib }; diff --git a/cocos/renderer/core/technique.js b/cocos/renderer/core/technique.js deleted file mode 100644 index 6ec993f2ab..0000000000 --- a/cocos/renderer/core/technique.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { RenderQueue } from "./constants"; - -let _genID = 0; - -export default class Technique { - /** - * @param {Array} stages - * @param {Array} passes - * @param {Number} renderQueue - */ - constructor(renderQueue = RenderQueue.OPAQUE, priority = 0, lod = -1, passes = []) { - this._id = _genID++; - this._renderQueue = renderQueue; - this._priority = priority; - this._lod = lod; - this._passes = passes; - // TODO: this._version = 'webgl' or 'webgl2' // ???? - } - - setRenderQueue(renderQueue) { - this._renderQueue = renderQueue; - } - - get renderQueue() { - return this._renderQueue; - } - - get passes() { - return this._passes; - } -} diff --git a/cocos/renderer/core/view.js b/cocos/renderer/core/view.js deleted file mode 100644 index c4e0c707ad..0000000000 --- a/cocos/renderer/core/view.js +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { vec3, color4, mat4 } from '../../core/vmath'; -import enums from '../enums'; -import { frustum } from '../../3d/geom-utils'; - -let _m4_tmp = mat4.create(); -let _genID = 0; - -/** - * A representation of a single camera view - */ -export default class View { - /** - * Setup a default view - */ - constructor() { - this._id = _genID++; - - // priority. the smaller one will be rendered first - this._priority = 0; - - // viewport - this._rect = { - x: 0, y: 0, w: 1, h: 1 - }; - - // TODO: - // this._scissor = { - // x: 0, y: 0, w: 1, h: 1 - // }; - - // clear options - this._color = color4.create(0.3, 0.3, 0.3, 1); - this._depth = 1; - this._stencil = 0; - this._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; - this._clearModel = null; - - // matrix - this._matView = mat4.create(); - this._matProj = mat4.create(); - this._matViewProj = mat4.create(); - this._matInvViewProj = mat4.create(); - - // stages & framebuffer - this._stages = []; - this._cullingByID = false; - this._framebuffer = null; - - this._shadowLight = null; // TODO: should not refer light in view. - - this._frustum = frustum.create(); - } - - /** - * Get the view's forward direction - * @param {vec3} out the receiving vector - * @returns {vec3} the receiving vector - */ - getForward(out) { - return vec3.set( - out, - -this._matView.m02, - -this._matView.m06, - -this._matView.m10 - ); - } - - /** - * Get the view's observing location - * @param {vec3} out the receiving vector - * @returns {vec3} the receiving vector - */ - getPosition(out) { - mat4.invert(_m4_tmp, this._matView); - return mat4.getTranslation(out, _m4_tmp); - } -} diff --git a/cocos/renderer/enums.js b/cocos/renderer/enums.js deleted file mode 100644 index 4dd45af301..0000000000 --- a/cocos/renderer/enums.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -export default { - // projection - PROJ_PERSPECTIVE: 0, - PROJ_ORTHO: 1, - - // lights - LIGHT_DIRECTIONAL: 0, - LIGHT_POINT: 1, - LIGHT_SPOT: 2, - - // shadows - SHADOW_NONE: 0, - SHADOW_HARD: 1, - SHADOW_SOFT: 2, - - // parameter type - PARAM_INT: 0, - PARAM_INT2: 1, - PARAM_INT3: 2, - PARAM_INT4: 3, - PARAM_FLOAT: 4, - PARAM_FLOAT2: 5, - PARAM_FLOAT3: 6, - PARAM_FLOAT4: 7, - PARAM_COLOR3: 8, - PARAM_COLOR4: 9, - PARAM_MAT2: 10, - PARAM_MAT3: 11, - PARAM_MAT4: 12, - PARAM_TEXTURE_2D: 13, - PARAM_TEXTURE_CUBE: 14, - - // clear flags - CLEAR_COLOR: 1, - CLEAR_DEPTH: 2, - CLEAR_STENCIL: 4, - CLEAR_SKYBOX: 8, - - // - BUFFER_VIEW_INT8: 0, - BUFFER_VIEW_UINT8: 1, - BUFFER_VIEW_INT16: 2, - BUFFER_VIEW_UINT16: 3, - BUFFER_VIEW_INT32: 4, - BUFFER_VIEW_UINT32: 5, - BUFFER_VIEW_FLOAT32: 6, -}; diff --git a/cocos/renderer/gfx/device.js b/cocos/renderer/gfx/device.js deleted file mode 100644 index 3165c109ed..0000000000 --- a/cocos/renderer/gfx/device.js +++ /dev/null @@ -1,1287 +0,0 @@ -import State from './state'; -import { enums } from './enums'; - -import Texture2D from './texture-2d'; -import TextureCube from './texture-cube'; - -const GL_INT = 5124; -const GL_FLOAT = 5126; -const GL_FLOAT_VEC2 = 35664; -const GL_FLOAT_VEC3 = 35665; -const GL_FLOAT_VEC4 = 35666; -const GL_INT_VEC2 = 35667; -const GL_INT_VEC3 = 35668; -const GL_INT_VEC4 = 35669; -const GL_BOOL = 35670; -const GL_BOOL_VEC2 = 35671; -const GL_BOOL_VEC3 = 35672; -const GL_BOOL_VEC4 = 35673; -const GL_FLOAT_MAT2 = 35674; -const GL_FLOAT_MAT3 = 35675; -const GL_FLOAT_MAT4 = 35676; -const GL_SAMPLER_2D = 35678; -const GL_SAMPLER_CUBE = 35680; - -/** - * _type2uniformCommit - */ -let _type2uniformCommit = { - [GL_INT]: function (gl, id, value) { - gl.uniform1i(id, value); - }, - - [GL_FLOAT]: function (gl, id, value) { - gl.uniform1f(id, value); - }, - - [GL_FLOAT_VEC2]: function (gl, id, value) { - gl.uniform2fv(id, value); - }, - - [GL_FLOAT_VEC3]: function (gl, id, value) { - gl.uniform3fv(id, value); - }, - - [GL_FLOAT_VEC4]: function (gl, id, value) { - gl.uniform4fv(id, value); - }, - - [GL_INT_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_INT_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_INT_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_BOOL]: function (gl, id, value) { - gl.uniform1i(id, value); - }, - - [GL_BOOL_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_BOOL_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_BOOL_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_FLOAT_MAT2]: function (gl, id, value) { - gl.uniformMatrix2fv(id, false, value); - }, - - [GL_FLOAT_MAT3]: function (gl, id, value) { - gl.uniformMatrix3fv(id, false, value); - }, - - [GL_FLOAT_MAT4]: function (gl, id, value) { - gl.uniformMatrix4fv(id, false, value); - }, - - [GL_SAMPLER_2D]: function (gl, id, value) { - gl.uniform1i(id, value); - }, - - [GL_SAMPLER_CUBE]: function (gl, id, value) { - gl.uniform1i(id, value); - }, -}; - -/** - * _type2uniformArrayCommit - */ -let _type2uniformArrayCommit = { - [GL_INT]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, - - [GL_FLOAT]: function (gl, id, value) { - gl.uniform1fv(id, value); - }, - - [GL_FLOAT_VEC2]: function (gl, id, value) { - gl.uniform2fv(id, value); - }, - - [GL_FLOAT_VEC3]: function (gl, id, value) { - gl.uniform3fv(id, value); - }, - - [GL_FLOAT_VEC4]: function (gl, id, value) { - gl.uniform4fv(id, value); - }, - - [GL_INT_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_INT_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_INT_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_BOOL]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, - - [GL_BOOL_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_BOOL_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_BOOL_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_FLOAT_MAT2]: function (gl, id, value) { - gl.uniformMatrix2fv(id, false, value); - }, - - [GL_FLOAT_MAT3]: function (gl, id, value) { - gl.uniformMatrix3fv(id, false, value); - }, - - [GL_FLOAT_MAT4]: function (gl, id, value) { - gl.uniformMatrix4fv(id, false, value); - }, - - [GL_SAMPLER_2D]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, - - [GL_SAMPLER_CUBE]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, -}; - -/** - * _commitBlendStates - */ -function _commitBlendStates(gl, cur, next) { - // enable/disable blend - if (cur.blend !== next.blend) { - if (!next.blend) { - gl.disable(gl.BLEND); - return; - } - - gl.enable(gl.BLEND); - - if ( - next.blendSrc === enums.BLEND_CONSTANT_COLOR || - next.blendSrc === enums.BLEND_ONE_MINUS_CONSTANT_COLOR || - next.blendDst === enums.BLEND_CONSTANT_COLOR || - next.blendDst === enums.BLEND_ONE_MINUS_CONSTANT_COLOR - ) { - gl.blendColor( - (next.blendColor >> 24) / 255, - (next.blendColor >> 16 & 0xff) / 255, - (next.blendColor >> 8 & 0xff) / 255, - (next.blendColor & 0xff) / 255 - ); - } - - if (next.blendSep) { - gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); - gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); - } else { - gl.blendFunc(next.blendSrc, next.blendDst); - gl.blendEquation(next.blendEq); - } - - return; - } - - // nothing to update - if (next.blend === false) { - return; - } - - // blend-color - if (cur.blendColor !== next.blendColor) { - gl.blendColor( - (next.blendColor >> 24) / 255, - (next.blendColor >> 16 & 0xff) / 255, - (next.blendColor >> 8 & 0xff) / 255, - (next.blendColor & 0xff) / 255 - ); - } - - // separate diff, reset all - if (cur.blendSep !== next.blendSep) { - if (next.blendSep) { - gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); - gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); - } else { - gl.blendFunc(next.blendSrc, next.blendDst); - gl.blendEquation(next.blendEq); - } - - return; - } - - if (next.blendSep) { - // blend-func-separate - if ( - cur.blendSrc !== next.blendSrc || - cur.blendDst !== next.blendDst || - cur.blendSrcAlpha !== next.blendSrcAlpha || - cur.blendDstAlpha !== next.blendDstAlpha - ) { - gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); - } - - // blend-equation-separate - if ( - cur.blendEq !== next.blendEq || - cur.blendAlphaEq !== next.blendAlphaEq - ) { - gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); - } - } else { - // blend-func - if ( - cur.blendSrc !== next.blendSrc || - cur.blendDst !== next.blendDst - ) { - gl.blendFunc(next.blendSrc, next.blendDst); - } - - // blend-equation - if (cur.blendEq !== next.blendEq) { - gl.blendEquation(next.blendEq); - } - } -} - -/** - * _commitDepthStates - */ -function _commitDepthStates(gl, cur, next) { - // enable/disable depth-test - if (cur.depthTest !== next.depthTest) { - if (!next.depthTest) { - gl.disable(gl.DEPTH_TEST); - return; - } - - gl.enable(gl.DEPTH_TEST); - gl.depthFunc(next.depthFunc); - gl.depthMask(next.depthWrite); - - return; - } - - // commit depth-write - if (cur.depthWrite !== next.depthWrite) { - gl.depthMask(next.depthWrite); - } - - // check if depth-write enabled - if (next.depthTest === false) { - if (next.depthWrite) { - next.depthTest = true; - next.depthFunc = enums.DS_FUNC_ALWAYS; - - gl.enable(gl.DEPTH_TEST); - gl.depthFunc(next.depthFunc); - } - - return; - } - - // depth-func - if (cur.depthFunc !== next.depthFunc) { - gl.depthFunc(next.depthFunc); - } -} - -/** - * _commitStencilStates - */ -function _commitStencilStates(gl, cur, next) { - if (next.stencilTest !== cur.stencilTest) { - if (!next.stencilTest) { - gl.disable(gl.STENCIL_TEST); - return; - } - - gl.enable(gl.STENCIL_TEST); - - if (next.stencilSep) { - gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); - gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); - gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); - gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); - } else { - gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMask(next.stencilWriteMaskFront); - gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - - return; - } - - // fast return - if (!next.stencilTest) { - return; - } - - if (cur.stencilSep !== next.stencilSep) { - if (next.stencilSep) { - gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); - gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); - gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); - gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); - } else { - gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMask(next.stencilWriteMaskFront); - gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - return; - } - - if (next.stencilSep) { - // front - if ( - cur.stencilFuncFront !== next.stencilFuncFront || - cur.stencilRefFront !== next.stencilRefFront || - cur.stencilMaskFront !== next.stencilMaskFront - ) { - gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - } - if (cur.stencilWriteMaskFront !== next.stencilWriteMaskFront) { - gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); - } - if ( - cur.stencilFailOpFront !== next.stencilFailOpFront || - cur.stencilZFailOpFront !== next.stencilZFailOpFront || - cur.stencilZPassOpFront !== next.stencilZPassOpFront - ) { - gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - - // back - if ( - cur.stencilFuncBack !== next.stencilFuncBack || - cur.stencilRefBack !== next.stencilRefBack || - cur.stencilMaskBack !== next.stencilMaskBack - ) { - gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); - } - if (cur.stencilWriteMaskBack !== next.stencilWriteMaskBack) { - gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); - } - if ( - cur.stencilFailOpBack !== next.stencilFailOpBack || - cur.stencilZFailOpBack !== next.stencilZFailOpBack || - cur.stencilZPassOpBack !== next.stencilZPassOpBack - ) { - gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); - } - } else { - if ( - cur.stencilFuncFront !== next.stencilFuncFront || - cur.stencilRefFront !== next.stencilRefFront || - cur.stencilMaskFront !== next.stencilMaskFront - ) { - gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - } - if (cur.stencilWriteMaskFront !== next.stencilWriteMaskFront) { - gl.stencilMask(next.stencilWriteMaskFront); - } - if ( - cur.stencilFailOpFront !== next.stencilFailOpFront || - cur.stencilZFailOpFront !== next.stencilZFailOpFront || - cur.stencilZPassOpFront !== next.stencilZPassOpFront - ) { - gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - } - -} - -/** - * _commitCullMode - */ -function _commitCullMode(gl, cur, next) { - if (cur.cullMode === next.cullMode) { - return; - } - - if (next.cullMode === enums.CULL_NONE) { - gl.disable(gl.CULL_FACE); - return; - } - - gl.enable(gl.CULL_FACE); - gl.cullFace(next.cullMode); -} - -/** - * _commitVertexBuffers - */ -function _commitVertexBuffers(device, gl, cur, next) { - let attrsDirty = false; - - // nothing changed for vertex buffer - if (next.maxStream === -1) { - console.warn('VertexBuffer not assigned, please call setVertexBuffer before every draw.'); - return; - } - - if (cur.maxStream !== next.maxStream) { - attrsDirty = true; - } else if (cur.program !== next.program) { - attrsDirty = true; - } else { - for (let i = 0; i < next.maxStream + 1; ++i) { - if ( - cur.vertexBuffers[i] !== next.vertexBuffers[i] || - cur.vertexBufferOffsets[i] !== next.vertexBufferOffsets[i] - ) { - attrsDirty = true; - break; - } - } - } - - if (attrsDirty) { - for (let i = 0; i < device._caps.maxVertexAttribs; ++i) { - device._newAttributes[i] = 0; - } - - for (let i = 0; i < next.maxStream + 1; ++i) { - let vb = next.vertexBuffers[i]; - let vbOffset = next.vertexBufferOffsets[i]; - if (!vb) { - continue; - } - - gl.bindBuffer(gl.ARRAY_BUFFER, vb._glID); - - for (let j = 0; j < next.program._attributes.length; ++j) { - let attr = next.program._attributes[j]; - - let el = vb._format.element(attr.name); - if (!el) { - console.warn(`Can not find vertex attribute: ${attr.name}`); - continue; - } - - if (device._enabledAttributes[attr.location] === 0) { - gl.enableVertexAttribArray(attr.location); - device._enabledAttributes[attr.location] = 1; - } - device._newAttributes[attr.location] = 1; - - gl.vertexAttribPointer( - attr.location, - el.num, - el.type, - el.normalize, - el.stride, - el.offset + vbOffset * el.stride - ); - } - } - - // disable unused attributes - for (let i = 0; i < device._caps.maxVertexAttribs; ++i) { - if (device._enabledAttributes[i] !== device._newAttributes[i]) { - gl.disableVertexAttribArray(i); - device._enabledAttributes[i] = 0; - } - } - } -} - -/** - * _commitTextures - */ -function _commitTextures(gl, cur, next) { - for (let i = 0; i < next.maxTextureSlot + 1; ++i) { - if (cur.textureUnits[i] !== next.textureUnits[i]) { - let texture = next.textureUnits[i]; - if (texture !== undefined && texture._glID !== -1) { - gl.activeTexture(gl.TEXTURE0 + i); - gl.bindTexture(texture._target, texture._glID); - } - } - } -} - -/** - * _attach - */ -function _attach(gl, location, attachment, face = 0) { - if (attachment instanceof Texture2D) { - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - location, - gl.TEXTURE_2D, - attachment._glID, - 0 - ); - } else if (attachment instanceof TextureCube) { - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - location, - gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, - attachment._glID, - 0 - ); - } else { - gl.framebufferRenderbuffer( - gl.FRAMEBUFFER, - location, - gl.RENDERBUFFER, - attachment._glID - ); - } -} - -export default class Device { - /** - * @param {HTMLElement} canvasEL - * @param {object} opts - */ - constructor(canvasEL, opts) { - let gl; - - // default options - opts = opts || {}; - if (opts.alpha === undefined) { - opts.alpha = false; - } - if (opts.stencil === undefined) { - opts.stencil = true; - } - if (opts.depth === undefined) { - opts.depth = true; - } - if (opts.antialias === undefined) { - opts.antialias = false; - } - // NOTE: it is said the performance improved in mobile device with this flag off. - if (opts.preserveDrawingBuffer === undefined) { - opts.preserveDrawingBuffer = false; - } - - try { - gl = canvasEL.getContext('webgl', opts); - } catch (err) { - console.error(err); - return; - } - - // No errors are thrown using try catch - // Tested through ios baidu browser 4.14.1 - if (!gl) { - console.error('This device does not support webgl'); - } - - // statics - /** - * @type {WebGLRenderingContext} - */ - this._gl = gl; - this._extensions = {}; - this._caps = {}; // capability - this._stats = { - texture: 0, - vb: 0, - ib: 0, - drawcalls: 0, - }; - - let builtin_exts = [ - 'EXT_texture_filter_anisotropic', - 'EXT_shader_texture_lod', - 'OES_standard_derivatives', - 'OES_texture_float', - 'OES_texture_float_linear', - 'OES_texture_half_float', - 'OES_texture_half_float_linear', - 'OES_vertex_array_object', - 'WEBGL_compressed_texture_atc', - 'WEBGL_compressed_texture_etc1', - 'WEBGL_compressed_texture_pvrtc', - 'WEBGL_compressed_texture_s3tc', - 'WEBGL_depth_texture', - 'WEBGL_draw_buffers', - ]; - for (let i = 0; i < builtin_exts.length; ++i) { - this._initExtension(builtin_exts[i]); - } - let exts = gl.getSupportedExtensions(); - this._supportedExts = exts.reduce((acc, cur) => { acc[cur] = true; return acc; }, {}); - - this._initCaps(); - this._initStates(); - - // runtime - State.initDefault(this); - this._current = new State(this); - this._next = new State(this); - this._uniforms = {}; // name: { value, num, dirty } - this._vx = this._vy = this._vw = this._vh = 0; - this._sx = this._sy = this._sw = this._sh = 0; - this._framebuffer = null; - - // - this._enabledAttributes = new Array(this._caps.maxVertexAttribs); - this._newAttributes = new Array(this._caps.maxVertexAttribs); - - for (let i = 0; i < this._caps.maxVertexAttribs; ++i) { - this._enabledAttributes[i] = 0; - this._newAttributes[i] = 0; - } - } - - _initCaps() { - const gl = this._gl; - const extDrawBuffers = this.ext('WEBGL_draw_buffers'); - - this._caps.maxVertexStreams = 4; - this._caps.maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); - this._caps.maxFragUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); - this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - this._caps.maxVertexAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - this._caps.maxDrawBuffers = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_DRAW_BUFFERS_WEBGL) : 1; - this._caps.maxColorAttachments = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_COLOR_ATTACHMENTS_WEBGL) : 1; - } - - _initStates() { - const gl = this._gl; - - // gl.frontFace(gl.CCW); - gl.disable(gl.BLEND); - gl.blendFunc(gl.ONE, gl.ZERO); - gl.blendEquation(gl.FUNC_ADD); - gl.blendColor(1,1,1,1); - - gl.colorMask(true, true, true, true); - - gl.enable(gl.CULL_FACE); - gl.cullFace(gl.BACK); - - gl.disable(gl.DEPTH_TEST); - gl.depthFunc(gl.LESS); - gl.depthMask(false); - gl.disable(gl.POLYGON_OFFSET_FILL); - gl.depthRange(0,1); - - gl.disable(gl.STENCIL_TEST); - gl.stencilFunc(gl.ALWAYS, 0, 0xFF); - gl.stencilMask(0xFF); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - - // TODO: - // this.setAlphaToCoverage(false); - // this.setTransformFeedbackBuffer(null); - // this.setRaster(true); - // this.setDepthBias(false); - - gl.clearDepth(1); - gl.clearColor(0, 0, 0, 0); - gl.clearStencil(0); - - gl.disable(gl.SCISSOR_TEST); - } - - _restoreTexture(unit) { - const gl = this._gl; - - let texture = this._current.textureUnits[unit]; - if (texture && texture._glID !== -1) { - gl.bindTexture(texture._target, texture._glID); - } else { - gl.bindTexture(gl.TEXTURE_2D, null); - } - } - - _restoreIndexBuffer () { - const gl = this._gl; - - let ib = this._current.indexBuffer; - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib ? ib._glID : null); - } - - _initExtension(name) { - const gl = this._gl; - let ext = gl.getExtension(name); - return this._extensions[name] = ext; - } - - /** - * @method ext - * @param {string} name - */ - ext(name) { - let ext = this._extensions[name]; - if (ext) return ext; - if (this.supportExtension(name)) return this._initExtension(name); - } - - supportExtension(name) { - return this._supportedExts[name] === true; - } - - allowFloatTexture() { - return this.ext("OES_texture_float") != null; - } - - // =============================== - // Immediate Settings - // =============================== - - /** - * @method setFrameBuffer - * @param {FrameBuffer} fb - null means use the backbuffer - */ - setFrameBuffer(fb) { - if (this._framebuffer === fb) { - return; - } - - this._framebuffer = fb; - const gl = this._gl; - - if (fb === null) { - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - return; - } - - gl.bindFramebuffer(gl.FRAMEBUFFER, fb._glID); - - let numColors = fb._colors.length; - for (let i = 0; i < numColors; ++i) { - let colorBuffer = fb._colors[i]; - _attach(gl, gl.COLOR_ATTACHMENT0 + i, colorBuffer); - - // TODO: what about cubemap face??? should be the target parameter for colorBuffer - } - for (let i = numColors; i < this._caps.maxColorAttachments; ++i) { - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - gl.COLOR_ATTACHMENT0 + i, - gl.TEXTURE_2D, - null, - 0 - ); - } - - if (fb._depth) { - _attach(gl, gl.DEPTH_ATTACHMENT, fb._depth); - } - - if (fb._stencil) { - _attach(gl, gl.STENCIL_ATTACHMENT, fb._stencil); - } - - if (fb._depthStencil) { - _attach(gl, gl.DEPTH_STENCIL_ATTACHMENT, fb._depthStencil); - } - } - - /** - * @method setViewport - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - */ - setViewport(x, y, w, h) { - if ( - this._vx !== x || - this._vy !== y || - this._vw !== w || - this._vh !== h - ) { - this._gl.viewport(x, y, w, h); - this._vx = x; - this._vy = y; - this._vw = w; - this._vh = h; - } - } - - /** - * @method setScissor - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - */ - setScissor(x, y, w, h) { - if ( - this._sx !== x || - this._sy !== y || - this._sw !== w || - this._sh !== h - ) { - this._gl.scissor(x, y, w, h); - this._sx = x; - this._sy = y; - this._sw = w; - this._sh = h; - } - } - - /** - * @method clear - * @param {Object} opts - * @param {Array} opts.color - * @param {Number} opts.depth - * @param {Number} opts.stencil - */ - clear(opts) { - const gl = this._gl; - let flags = 0; - - if (opts.color !== undefined) { - flags |= gl.COLOR_BUFFER_BIT; - gl.clearColor(opts.color[0], opts.color[1], opts.color[2], opts.color[3]); - } - - if (opts.depth !== undefined) { - flags |= gl.DEPTH_BUFFER_BIT; - gl.clearDepth(opts.depth); - - gl.enable(gl.DEPTH_TEST); - gl.depthMask(true); - gl.depthFunc(gl.ALWAYS); - } - - if (opts.stencil !== undefined) { - flags |= gl.STENCIL_BUFFER_BIT; - gl.clearStencil(opts.stencil); - } - - gl.clear(flags); - - // restore depth-write - if (opts.depth !== undefined) { - if (this._current.depthTest === false) { - gl.disable(gl.DEPTH_TEST); - } else { - if (this._current.depthWrite === false) { - gl.depthMask(false); - } - if (this._current.depthFunc !== enums.DS_FUNC_ALWAYS) { - gl.depthFunc(this._current.depthFunc); - } - } - } - } - - // =============================== - // Deferred States - // =============================== - - /** - * @method enableBlend - */ - enableBlend() { - this._next.blend = true; - } - - /** - * @method enableDepthTest - */ - enableDepthTest() { - this._next.depthTest = true; - } - - /** - * @method enableDepthWrite - */ - enableDepthWrite() { - this._next.depthWrite = true; - } - - /** - * @method enableStencilTest - */ - enableStencilTest() { - this._next.stencilTest = true; - } - - /** - * @method setStencilFunc - * @param {DS_FUNC_*} func - * @param {Number} ref - * @param {Number} mask - */ - setStencilFunc(func, ref, mask) { - this._next.stencilSep = false; - this._next.stencilFuncFront = this._next.stencilFuncBack = func; - this._next.stencilRefFront = this._next.stencilRefBack = ref; - this._next.stencilMaskFront = this._next.stencilMaskBack = mask; - } - - /** - * @method setStencilFuncFront - * @param {DS_FUNC_*} func - * @param {Number} ref - * @param {Number} mask - */ - setStencilFuncFront(func, ref, mask) { - this._next.stencilSep = true; - this._next.stencilFuncFront = func; - this._next.stencilRefFront = ref; - this._next.stencilMaskFront = mask; - } - - /** - * @method setStencilFuncBack - * @param {DS_FUNC_*} func - * @param {Number} ref - * @param {Number} mask - */ - setStencilFuncBack(func, ref, mask) { - this._next.stencilSep = true; - this._next.stencilFuncBack = func; - this._next.stencilRefBack = ref; - this._next.stencilMaskBack = mask; - } - - /** - * @method setStencilOp - * @param {STENCIL_OP_*} failOp - * @param {STENCIL_OP_*} zFailOp - * @param {STENCIL_OP_*} zPassOp - * @param {Number} writeMask - */ - setStencilOp(failOp, zFailOp, zPassOp, writeMask) { - this._next.stencilFailOpFront = this._next.stencilFailOpBack = failOp; - this._next.stencilZFailOpFront = this._next.stencilZFailOpBack = zFailOp; - this._next.stencilZPassOpFront = this._next.stencilZPassOpBack = zPassOp; - this._next.stencilWriteMaskFront = this._next.stencilWriteMaskBack = writeMask; - } - - /** - * @method setStencilOpFront - * @param {STENCIL_OP_*} failOp - * @param {STENCIL_OP_*} zFailOp - * @param {STENCIL_OP_*} zPassOp - * @param {Number} writeMask - */ - setStencilOpFront(failOp, zFailOp, zPassOp, writeMask) { - this._next.stencilSep = true; - this._next.stencilFailOpFront = failOp; - this._next.stencilZFailOpFront = zFailOp; - this._next.stencilZPassOpFront = zPassOp; - this._next.stencilWriteMaskFront = writeMask; - } - - /** - * @method setStencilOpBack - * @param {STENCIL_OP_*} failOp - * @param {STENCIL_OP_*} zFailOp - * @param {STENCIL_OP_*} zPassOp - * @param {Number} writeMask - */ - setStencilOpBack(failOp, zFailOp, zPassOp, writeMask) { - this._next.stencilSep = true; - this._next.stencilFailOpBack = failOp; - this._next.stencilZFailOpBack = zFailOp; - this._next.stencilZPassOpBack = zPassOp; - this._next.stencilWriteMaskBack = writeMask; - } - - /** - * @method setDepthFunc - * @param {DS_FUNC_*} depthFunc - */ - setDepthFunc(depthFunc) { - this._next.depthFunc = depthFunc; - } - - /** - * @method setBlendColor32 - * @param {Number} rgba - */ - setBlendColor32(rgba) { - this._next.blendColor = rgba; - } - - /** - * @method setBlendColor - * @param {Number} r - * @param {Number} g - * @param {Number} b - * @param {Number} a - */ - setBlendColor(r, g, b, a) { - this._next.blendColor = ((r * 255) << 24 | (g * 255) << 16 | (b * 255) << 8 | a * 255) >>> 0; - } - - /** - * @method setBlendFunc - * @param {BELND_*} src - * @param {BELND_*} dst - */ - setBlendFunc(src, dst) { - this._next.blendSep = false; - this._next.blendSrc = src; - this._next.blendDst = dst; - } - - /** - * @method setBlendFuncSep - * @param {BELND_*} src - * @param {BELND_*} dst - * @param {BELND_*} srcAlpha - * @param {BELND_*} dstAlpha - */ - setBlendFuncSep(src, dst, srcAlpha, dstAlpha) { - this._next.blendSep = true; - this._next.blendSrc = src; - this._next.blendDst = dst; - this._next.blendSrcAlpha = srcAlpha; - this._next.blendDstAlpha = dstAlpha; - } - - /** - * @method setBlendEq - * @param {BELND_FUNC_*} eq - */ - setBlendEq(eq) { - this._next.blendSep = false; - this._next.blendEq = eq; - } - - /** - * @method setBlendEqSep - * @param {BELND_FUNC_*} eq - * @param {BELND_FUNC_*} alphaEq - */ - setBlendEqSep(eq, alphaEq) { - this._next.blendSep = true; - this._next.blendEq = eq; - this._next.blendAlphaEq = alphaEq; - } - - /** - * @method setCullMode - * @param {CULL_*} mode - */ - setCullMode(mode) { - this._next.cullMode = mode; - } - - /** - * @method setVertexBuffer - * @param {Number} stream - * @param {VertexBuffer} buffer - * @param {Number} start - start vertex - */ - setVertexBuffer(stream, buffer, start = 0) { - this._next.vertexBuffers[stream] = buffer; - this._next.vertexBufferOffsets[stream] = start; - if (this._next.maxStream < stream) { - this._next.maxStream = stream; - } - } - - /** - * @method setIndexBuffer - * @param {IndexBuffer} buffer - */ - setIndexBuffer(buffer) { - this._next.indexBuffer = buffer; - } - - /** - * @method setProgram - * @param {Program} program - */ - setProgram(program) { - this._next.program = program; - } - - /** - * @method setTexture - * @param {String} name - * @param {Texture} texture - * @param {Number} slot - */ - setTexture(name, texture, slot) { - if (slot >= this._caps.maxTextureUnits) { - console.warn(`Can not set texture ${name} at stage ${slot}, max texture exceed: ${this._caps.maxTextureUnits}`); - return; - } - - this._next.textureUnits[slot] = texture; - this.setUniform(name, slot); - - if (this._next.maxTextureSlot < slot) { - this._next.maxTextureSlot = slot; - } - } - - /** - * @method setTextureArray - * @param {String} name - * @param {Array} textures - * @param {Int32Array} slots - */ - setTextureArray(name, textures, slots) { - let len = textures.length; - if (len >= this._caps.maxTextureUnits) { - console.warn(`Can not set ${len} textures for ${name}, max texture exceed: ${this._caps.maxTextureUnits}`); - return; - } - for (let i = 0; i < len; ++i) { - let slot = slots[i]; - this._next.textureUnits[slot] = textures[i]; - } - this.setUniform(name, slots); - } - - /** - * @method setUniform - * @param {String} name - * @param {*} value - */ - setUniform(name, value) { - let uniform = this._uniforms[name]; - if (!uniform) { - uniform = { - dirty: true, - value: value, - }; - } else { - uniform.dirty = true; - uniform.value = value; - } - this._uniforms[name] = uniform; - } - - /** - * @method setPrimitiveType - * @param {PT_*} type - */ - setPrimitiveType(type) { - this._next.primitiveType = type; - } - - /** - * @method draw - * @param {Number} base - * @param {Number} count - */ - draw(base, count) { - const gl = this._gl; - let cur = this._current; - let next = this._next; - - // commit blend - _commitBlendStates(gl, cur, next); - - // commit depth - _commitDepthStates(gl, cur, next); - - // commit stencil - _commitStencilStates(gl, cur, next); - - // commit cull - _commitCullMode(gl, cur, next); - - // commit vertex-buffer - _commitVertexBuffers(this, gl, cur, next); - - // commit index-buffer - if (cur.indexBuffer !== next.indexBuffer) { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, next.indexBuffer ? next.indexBuffer._glID : null); - } - - // commit program - let programDirty = false; - if (cur.program !== next.program) { - if (next.program._linked) { - gl.useProgram(next.program._glID); - } - programDirty = true; - } - - // commit texture/sampler - _commitTextures(gl, cur, next); - - // commit uniforms - for (let i = 0; i < next.program._uniforms.length; ++i) { - let uniformInfo = next.program._uniforms[i]; - let uniform = this._uniforms[uniformInfo.name]; - if (!uniform) { - // console.warn(`Can not find uniform ${uniformInfo.name}`); - continue; - } - - if (!programDirty && !uniform.dirty) { - continue; - } - - uniform.dirty = false; - - // TODO: please consider array uniform: uniformInfo.size > 0 - - let commitFunc = (uniformInfo.size === undefined) ? _type2uniformCommit[uniformInfo.type] : _type2uniformArrayCommit[uniformInfo.type]; - if (!commitFunc) { - console.warn(`Can not find commit function for uniform ${uniformInfo.name}`); - continue; - } - - commitFunc(gl, uniformInfo.location, uniform.value); - } - - // drawPrimitives - if (next.indexBuffer) { - gl.drawElements( - this._next.primitiveType, - count, - next.indexBuffer._format, - base * next.indexBuffer._bytesPerIndex - ); - } else { - gl.drawArrays( - this._next.primitiveType, - base, - count - ); - } - - // TODO: autogen mipmap for color buffer - // if (this._framebuffer && this._framebuffer.colors[0].mipmap) { - // gl.bindTexture(this._framebuffer.colors[i]._target, colors[i]._glID); - // gl.generateMipmap(this._framebuffer.colors[i]._target); - // } - - // update stats - this._stats.drawcalls += 1; - - // reset states - cur.set(next); - next.reset(); - } -} diff --git a/cocos/renderer/gfx/enums.js b/cocos/renderer/gfx/enums.js deleted file mode 100644 index 16e34dfc7a..0000000000 --- a/cocos/renderer/gfx/enums.js +++ /dev/null @@ -1,336 +0,0 @@ -const GL_NEAREST = 9728; // gl.NEAREST -const GL_LINEAR = 9729; // gl.LINEAR -const GL_NEAREST_MIPMAP_NEAREST = 9984; // gl.NEAREST_MIPMAP_NEAREST -const GL_LINEAR_MIPMAP_NEAREST = 9985; // gl.LINEAR_MIPMAP_NEAREST -const GL_NEAREST_MIPMAP_LINEAR = 9986; // gl.NEAREST_MIPMAP_LINEAR -const GL_LINEAR_MIPMAP_LINEAR = 9987; // gl.LINEAR_MIPMAP_LINEAR - -// const GL_BYTE = 5120; // gl.BYTE -const GL_UNSIGNED_BYTE = 5121; // gl.UNSIGNED_BYTE -// const GL_SHORT = 5122; // gl.SHORT -const GL_UNSIGNED_SHORT = 5123; // gl.UNSIGNED_SHORT -const GL_UNSIGNED_INT = 5125; // gl.UNSIGNED_INT -const GL_FLOAT = 5126; // gl.FLOAT -const GL_UNSIGNED_SHORT_5_6_5 = 33635; // gl.UNSIGNED_SHORT_5_6_5 -const GL_UNSIGNED_SHORT_4_4_4_4 = 32819; // gl.UNSIGNED_SHORT_4_4_4_4 -const GL_UNSIGNED_SHORT_5_5_5_1 = 32820; // gl.UNSIGNED_SHORT_5_5_5_1 -const GL_HALF_FLOAT_OES = 36193; // gl.HALF_FLOAT_OES - -const GL_DEPTH_COMPONENT = 6402; // gl.DEPTH_COMPONENT - -const GL_ALPHA = 6406; // gl.ALPHA -const GL_RGB = 6407; // gl.RGB -const GL_RGBA = 6408; // gl.RGBA -const GL_LUMINANCE = 6409; // gl.LUMINANCE -const GL_LUMINANCE_ALPHA = 6410; // gl.LUMINANCE_ALPHA - -const GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0; // ext.COMPRESSED_RGB_S3TC_DXT1_EXT -const GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1; // ext.COMPRESSED_RGBA_S3TC_DXT1_EXT -const GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2; // ext.COMPRESSED_RGBA_S3TC_DXT3_EXT -const GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3; // ext.COMPRESSED_RGBA_S3TC_DXT5_EXT - -const GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00; // ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG -const GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01; // ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG -const GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02; // ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG -const GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03; // ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG - -const GL_COMPRESSED_RGB_ETC1_WEBGL = 0x8D64; // ext.COMPRESSED_RGB_ETC1_WEBGL - -const _filterGL = [ - [ GL_NEAREST, GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR ], - [ GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_LINEAR ], -]; - -const _textureFmtGL = [ - // TEXTURE_FMT_RGB_DXT1: 0 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_S3TC_DXT1_EXT, pixelType: null }, - - // TEXTURE_FMT_RGBA_DXT1: 1 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixelType: null }, - - // TEXTURE_FMT_RGBA_DXT3: 2 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, pixelType: null }, - - // TEXTURE_FMT_RGBA_DXT5: 3 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, pixelType: null }, - - // TEXTURE_FMT_RGB_ETC1: 4 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_ETC1_WEBGL, pixelType: null }, - - // TEXTURE_FMT_RGB_PVRTC_2BPPV1: 5 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_RGBA_PVRTC_2BPPV1: 6 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_RGB_PVRTC_4BPPV1: 7 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_RGBA_PVRTC_4BPPV1: 8 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_A8: 9 - { format: GL_ALPHA, internalFormat: GL_ALPHA, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_L8: 10 - { format: GL_LUMINANCE, internalFormat: GL_LUMINANCE, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_L8_A8: 11 - { format: GL_LUMINANCE_ALPHA, internalFormat: GL_LUMINANCE_ALPHA, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_R5_G6_B5: 12 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_UNSIGNED_SHORT_5_6_5 }, - - // TEXTURE_FMT_R5_G5_B5_A1: 13 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_SHORT_5_5_5_1 }, - - // TEXTURE_FMT_R4_G4_B4_A4: 14 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_SHORT_4_4_4_4 }, - - // TEXTURE_FMT_RGB8: 15 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_RGBA8: 16 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_RGB16F: 17 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_HALF_FLOAT_OES }, - - // TEXTURE_FMT_RGBA16F: 18 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_HALF_FLOAT_OES }, - - // TEXTURE_FMT_RGB32F: 19 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_FLOAT }, - - // TEXTURE_FMT_RGBA32F: 20 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_FLOAT }, - - // TEXTURE_FMT_R32F: 21 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_111110F: 22 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_SRGB: 23 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_SRGBA: 24 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_D16: 25 - { format: GL_DEPTH_COMPONENT, internalFormat: GL_DEPTH_COMPONENT, pixelType: GL_UNSIGNED_SHORT }, - - // TEXTURE_FMT_D32: 26 - { format: GL_DEPTH_COMPONENT, internalFormat: GL_DEPTH_COMPONENT, pixelType: GL_UNSIGNED_INT }, - - // TEXTURE_FMT_D24S8: 27 - { format: null, internalFormat: null, pixelType: null }, -]; - -/** - * enums - */ -export const enums = { - // buffer usage - USAGE_STATIC: 35044, // gl.STATIC_DRAW - USAGE_DYNAMIC: 35048, // gl.DYNAMIC_DRAW - USAGE_STREAM: 35040, // gl.STREAM_DRAW - - // index buffer format - INDEX_FMT_UINT8: 5121, // gl.UNSIGNED_BYTE - INDEX_FMT_UINT16: 5123, // gl.UNSIGNED_SHORT - INDEX_FMT_UINT32: 5125, // gl.UNSIGNED_INT (OES_element_index_uint) - - // vertex attribute semantic - ATTR_POSITION: 'a_position', - ATTR_NORMAL: 'a_normal', - ATTR_TANGENT: 'a_tangent', - ATTR_BITANGENT: 'a_bitangent', - ATTR_WEIGHTS: 'a_weights', - ATTR_JOINTS: 'a_joints', - ATTR_COLOR: 'a_color', - ATTR_COLOR0: 'a_color0', - ATTR_COLOR1: 'a_color1', - ATTR_UV: 'a_uv', - ATTR_UV0: 'a_uv0', - ATTR_UV1: 'a_uv1', - ATTR_UV2: 'a_uv2', - ATTR_UV3: 'a_uv3', - ATTR_UV4: 'a_uv4', - ATTR_UV5: 'a_uv5', - ATTR_UV6: 'a_uv6', - ATTR_UV7: 'a_uv7', - - // vertex attribute type - ATTR_TYPE_INT8: 5120, // gl.BYTE - ATTR_TYPE_UINT8: 5121, // gl.UNSIGNED_BYTE - ATTR_TYPE_INT16: 5122, // gl.SHORT - ATTR_TYPE_UINT16: 5123, // gl.UNSIGNED_SHORT - ATTR_TYPE_INT32: 5124, // gl.INT - ATTR_TYPE_UINT32: 5125, // gl.UNSIGNED_INT - ATTR_TYPE_FLOAT32: 5126, // gl.FLOAT - - // texture filter - FILTER_NEAREST: 0, - FILTER_LINEAR: 1, - - // texture wrap mode - WRAP_REPEAT: 10497, // gl.REPEAT - WRAP_CLAMP: 33071, // gl.CLAMP_TO_EDGE - WRAP_MIRROR: 33648, // gl.MIRRORED_REPEAT - - // texture format - // compress formats - TEXTURE_FMT_RGB_DXT1: 0, - TEXTURE_FMT_RGBA_DXT1: 1, - TEXTURE_FMT_RGBA_DXT3: 2, - TEXTURE_FMT_RGBA_DXT5: 3, - TEXTURE_FMT_RGB_ETC1: 4, - TEXTURE_FMT_RGB_PVRTC_2BPPV1: 5, - TEXTURE_FMT_RGBA_PVRTC_2BPPV1: 6, - TEXTURE_FMT_RGB_PVRTC_4BPPV1: 7, - TEXTURE_FMT_RGBA_PVRTC_4BPPV1: 8, - - // normal formats - TEXTURE_FMT_A8: 9, - TEXTURE_FMT_L8: 10, - TEXTURE_FMT_L8_A8: 11, - TEXTURE_FMT_R5_G6_B5: 12, - TEXTURE_FMT_R5_G5_B5_A1: 13, - TEXTURE_FMT_R4_G4_B4_A4: 14, - TEXTURE_FMT_RGB8: 15, - TEXTURE_FMT_RGBA8: 16, - TEXTURE_FMT_RGB16F: 17, - TEXTURE_FMT_RGBA16F: 18, - TEXTURE_FMT_RGB32F: 19, - TEXTURE_FMT_RGBA32F: 20, - TEXTURE_FMT_R32F: 21, - TEXTURE_FMT_111110F: 22, - TEXTURE_FMT_SRGB: 23, - TEXTURE_FMT_SRGBA: 24, - - // depth formats - TEXTURE_FMT_D16: 25, - TEXTURE_FMT_D32: 26, - TEXTURE_FMT_D24S8: 27, - - // depth and stencil function - DS_FUNC_NEVER: 512, // gl.NEVER - DS_FUNC_LESS: 513, // gl.LESS - DS_FUNC_EQUAL: 514, // gl.EQUAL - DS_FUNC_LEQUAL: 515, // gl.LEQUAL - DS_FUNC_GREATER: 516, // gl.GREATER - DS_FUNC_NOTEQUAL: 517, // gl.NOTEQUAL - DS_FUNC_GEQUAL: 518, // gl.GEQUAL - DS_FUNC_ALWAYS: 519, // gl.ALWAYS - - // render-buffer format - RB_FMT_RGBA4: 32854, // gl.RGBA4 - RB_FMT_RGB5_A1: 32855, // gl.RGB5_A1 - RB_FMT_RGB565: 36194, // gl.RGB565 - RB_FMT_D16: 33189, // gl.DEPTH_COMPONENT16 - RB_FMT_S8: 36168, // gl.STENCIL_INDEX8 - RB_FMT_D24S8: 34041, // gl.DEPTH_STENCIL - - // blend-equation - BLEND_FUNC_ADD: 32774, // gl.FUNC_ADD - BLEND_FUNC_SUBTRACT: 32778, // gl.FUNC_SUBTRACT - BLEND_FUNC_REVERSE_SUBTRACT: 32779, // gl.FUNC_REVERSE_SUBTRACT - - // blend - BLEND_ZERO: 0, // gl.ZERO - BLEND_ONE: 1, // gl.ONE - BLEND_SRC_COLOR: 768, // gl.SRC_COLOR - BLEND_ONE_MINUS_SRC_COLOR: 769, // gl.ONE_MINUS_SRC_COLOR - BLEND_DST_COLOR: 774, // gl.DST_COLOR - BLEND_ONE_MINUS_DST_COLOR: 775, // gl.ONE_MINUS_DST_COLOR - BLEND_SRC_ALPHA: 770, // gl.SRC_ALPHA - BLEND_ONE_MINUS_SRC_ALPHA: 771, // gl.ONE_MINUS_SRC_ALPHA - BLEND_DST_ALPHA: 772, // gl.DST_ALPHA - BLEND_ONE_MINUS_DST_ALPHA: 773, // gl.ONE_MINUS_DST_ALPHA - BLEND_CONSTANT_COLOR: 32769, // gl.CONSTANT_COLOR - BLEND_ONE_MINUS_CONSTANT_COLOR: 32770, // gl.ONE_MINUS_CONSTANT_COLOR - BLEND_CONSTANT_ALPHA: 32771, // gl.CONSTANT_ALPHA - BLEND_ONE_MINUS_CONSTANT_ALPHA: 32772, // gl.ONE_MINUS_CONSTANT_ALPHA - BLEND_SRC_ALPHA_SATURATE: 776, // gl.SRC_ALPHA_SATURATE - - // stencil operation - STENCIL_OP_KEEP: 7680, // gl.KEEP - STENCIL_OP_ZERO: 0, // gl.ZERO - STENCIL_OP_REPLACE: 7681, // gl.REPLACE - STENCIL_OP_INCR: 7682, // gl.INCR - STENCIL_OP_INCR_WRAP: 34055, // gl.INCR_WRAP - STENCIL_OP_DECR: 7683, // gl.DECR - STENCIL_OP_DECR_WRAP: 34056, // gl.DECR_WRAP - STENCIL_OP_INVERT: 5386, // gl.INVERT - - // cull - CULL_NONE: 0, - CULL_FRONT: 1028, - CULL_BACK: 1029, - CULL_FRONT_AND_BACK: 1032, - - // primitive type - PT_POINTS: 0, // gl.POINTS - PT_LINES: 1, // gl.LINES - PT_LINE_LOOP: 2, // gl.LINE_LOOP - PT_LINE_STRIP: 3, // gl.LINE_STRIP - PT_TRIANGLES: 4, // gl.TRIANGLES - PT_TRIANGLE_STRIP: 5, // gl.TRIANGLE_STRIP - PT_TRIANGLE_FAN: 6, // gl.TRIANGLE_FAN -}; - -/** - * @method attrTypeBytes - * @param {ATTR_TYPE_*} attrType - */ -export function attrTypeBytes(attrType) { - if (attrType === enums.ATTR_TYPE_INT8) { - return 1; - } else if (attrType === enums.ATTR_TYPE_UINT8) { - return 1; - } else if (attrType === enums.ATTR_TYPE_INT16) { - return 2; - } else if (attrType === enums.ATTR_TYPE_UINT16) { - return 2; - } else if (attrType === enums.ATTR_TYPE_INT32) { - return 4; - } else if (attrType === enums.ATTR_TYPE_UINT32) { - return 4; - } else if (attrType === enums.ATTR_TYPE_FLOAT32) { - return 4; - } - - console.warn(`Unknown ATTR_TYPE: ${attrType}`); - return 0; -} - -/** - * @method glFilter - * @param {WebGLContext} gl - * @param {FILTER_*} filter - * @param {FILTER_*} mipFilter - */ -export function glFilter(gl, filter, mipFilter = -1) { - let result = _filterGL[filter][mipFilter+1]; - if (result === undefined) { - console.warn(`Unknown FILTER: ${filter}`); - return mipFilter === -1 ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR; - } - - return result; -} - -/** - * @method glTextureFmt - * @param {TEXTURE_FMT_*} fmt - */ -export function glTextureFmt(fmt) { - let result = _textureFmtGL[fmt]; - if (result === undefined) { - console.warn(`Unknown TEXTURE_FMT: ${fmt}`); - return _textureFmtGL[enums.TEXTURE_FMT_RGBA8]; - } - - return result; -} \ No newline at end of file diff --git a/cocos/renderer/gfx/frame-buffer.js b/cocos/renderer/gfx/frame-buffer.js deleted file mode 100644 index bd43954818..0000000000 --- a/cocos/renderer/gfx/frame-buffer.js +++ /dev/null @@ -1,41 +0,0 @@ -export default class FrameBuffer { - /** - * @constructor - * @param {Device} device - * @param {Number} width - * @param {Number} height - * @param {Object} options - * @param {Array} options.colors - * @param {RenderBuffer|Texture2D|TextureCube} options.depth - * @param {RenderBuffer|Texture2D|TextureCube} options.stencil - * @param {RenderBuffer|Texture2D|TextureCube} options.depthStencil - */ - constructor(device, width, height, options) { - this._device = device; - this._width = width; - this._height = height; - - this._colors = options.colors || []; - this._depth = options.depth || null; - this._stencil = options.stencil || null; - this._depthStencil = options.depthStencil || null; - - this._glID = device._gl.createFramebuffer(); - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === null) { - console.error('The frame-buffer already destroyed'); - return; - } - - const gl = this._device._gl; - - gl.deleteFramebuffer(this._glID); - - this._glID = null; - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/index-buffer.js b/cocos/renderer/gfx/index-buffer.js deleted file mode 100644 index 029a5f0b28..0000000000 --- a/cocos/renderer/gfx/index-buffer.js +++ /dev/null @@ -1,134 +0,0 @@ -import { enums } from './enums'; - -class IndexBuffer { - /** - * @constructor - * @param {Device} device - * @param {INDEX_FMT_*} format - * @param {USAGE_*} usage - * @param {ArrayBuffer | Uint8Array} data - * @param {Number} numIndices - */ - constructor(device, format, usage, data, numIndices) { - this._device = device; - this._format = format; - this._usage = usage; - this._numIndices = numIndices; - this._bytesPerIndex = 0; - - // calculate bytes - if (format === enums.INDEX_FMT_UINT8) { - this._bytesPerIndex = 1; - } else if (format === enums.INDEX_FMT_UINT16) { - this._bytesPerIndex = 2; - } else if (format === enums.INDEX_FMT_UINT32) { - this._bytesPerIndex = 4; - } - this._bytes = this._bytesPerIndex * numIndices; - - // update - this._glID = device._gl.createBuffer(); - this.update(0, data); - - // stats - device._stats.ib += this._bytes; - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === -1) { - console.error('The buffer already destroyed'); - return; - } - - let gl = this._device._gl; - gl.deleteBuffer(this._glID); - this._device._stats.ib -= this.bytes; - - this._glID = -1; - } - - /** - * @method update - * @param {Number} offset - * @param {ArrayBuffer} data - */ - update(offset, data) { - if (this._glID === -1) { - console.error('The buffer is destroyed'); - return; - } - - if (data && data.byteLength + offset > this._bytes) { - console.error('Failed to update data, bytes exceed.'); - return; - } - - /** @type{WebGLRenderingContext} */ - let gl = this._device._gl; - let glUsage = this._usage; - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glID); - if (!data) { - if (this._bytes) { - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._bytes, glUsage); - } else { - console.warn('bufferData should not submit 0 bytes data'); - } - } else { - if (offset) { - gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, offset, data); - } else { - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, glUsage); - } - } - this._device._restoreIndexBuffer(); - } - - get count () { - return this._numIndices; - } -} - -if (CC_EDITOR) { - let _type2fn = { - [enums.ATTR_TYPE_INT8]: 'getInt8', - [enums.ATTR_TYPE_UINT8]: 'getUint8', - [enums.ATTR_TYPE_INT16]: 'getInt16', - [enums.ATTR_TYPE_UINT16]: 'getUint16', - [enums.ATTR_TYPE_INT32]: 'getInt32', - [enums.ATTR_TYPE_UINT32]: 'getUint32', - [enums.ATTR_TYPE_FLOAT32]: 'getFloat32' - }; - let littleEndian = (function() { - let buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - let createCache = function(ib, data) { - if (!data) return []; - let icount = data.byteLength / ib._bytesPerIndex; - let result = new Array(icount); - for (let i = 0; i < icount; i++) { - let fname = _type2fn[ib._format]; - result[i] = data[fname](i * ib._bytesPerIndex, littleEndian); - } - return result; - }; - IndexBuffer.prototype.do_update = IndexBuffer.prototype.update; - IndexBuffer.prototype.update = function(offset, data) { - this.do_update(offset, data); - // don't need to create for IA pools - if (data && this._bytes !== data.byteLength) return; - if (data instanceof ArrayBuffer) - data = new DataView(data); - else if (ArrayBuffer.isView(data) && !(data instanceof DataView)) - data = new DataView(data.buffer, data.byteOffset, data.byteLength); - this._data = createCache(this, data); - }; -} - -export default IndexBuffer; diff --git a/cocos/renderer/gfx/index.js b/cocos/renderer/gfx/index.js deleted file mode 100644 index 7687de6774..0000000000 --- a/cocos/renderer/gfx/index.js +++ /dev/null @@ -1,40 +0,0 @@ -import { - enums, - attrTypeBytes, - glFilter, - glTextureFmt, -} from './enums'; - -import VertexFormat from './vertex-format'; -import IndexBuffer from './index-buffer'; -import VertexBuffer from './vertex-buffer'; -import Program from './program'; -import Texture from './texture'; -import Texture2D from './texture-2d'; -import TextureCube from './texture-cube'; -import RenderBuffer from './render-buffer'; -import FrameBuffer from './frame-buffer'; -import Device from './device'; - -let gfx = { - // classes - VertexFormat, - IndexBuffer, - VertexBuffer, - Program, - Texture, - Texture2D, - TextureCube, - RenderBuffer, - FrameBuffer, - Device, - - // functions - attrTypeBytes, - glFilter, - glTextureFmt, -}; -Object.assign(gfx, enums); - -export default gfx; -cc.gfx = gfx; diff --git a/cocos/renderer/gfx/misc.js b/cocos/renderer/gfx/misc.js deleted file mode 100644 index 9825541ea8..0000000000 --- a/cocos/renderer/gfx/misc.js +++ /dev/null @@ -1,3 +0,0 @@ -export function isPow2(v) { - return !(v & (v - 1)) && (!!v); -} \ No newline at end of file diff --git a/cocos/renderer/gfx/program.js b/cocos/renderer/gfx/program.js deleted file mode 100644 index 6961b73372..0000000000 --- a/cocos/renderer/gfx/program.js +++ /dev/null @@ -1,176 +0,0 @@ -let _genID = 0; - -function _parseError(out, type, errorLog) { - errorLog.split('\n').forEach(msg => { - if (msg.length < 5) { - return; - } - - let parts = /^ERROR:\s+(\d+):(\d+):\s*(.*)$/.exec(msg); - if (parts) { - out.push({ - type: type, - fileID: parts[1] | 0, - line: parts[2] | 0, - message: parts[3].trim() - }); - } else if (msg.length > 0) { - out.push({ - type: type, - fileID: -1, - line: 0, - message: msg - }); - } - }); -} - -export default class Program { - /** - * @param {ef.GraphicsDevice} device - graphic device - * @param {object} options - shader definition - * @param {string} options.vert - vertex shader source code - * @param {string} options.frag - fragment shader shader source code - * @example - * let prog = new Program(device, { - * vert: ` - * attribute vec3 a_position; - * void main() { - * gl_Position = vec4( a_position, 1.0 ); - * } - * `, - * frag: ` - * precision mediump float; - * void main() { - * gl_FragColor = vec4( 1.0, 1.0, 1.0, 1.0 ); - * } - * ` - * }); - */ - constructor(device, options) { - this._device = device; - - // stores gl information: { location, type } - this._attributes = []; - this._uniforms = []; - this._samplers = []; - this._errors = []; - this._linked = false; - this._vertSource = options.vert; - this._fragSource = options.frag; - this._glID = null; - this._id = _genID++; - } - - get id() { - return this._id; - } - - link() { - if (this._linked) { - return; - } - - let gl = this._device._gl; - - let vertShader = _createShader(gl, gl.VERTEX_SHADER, this._vertSource); - let fragShader = _createShader(gl, gl.FRAGMENT_SHADER, this._fragSource); - - let program = gl.createProgram(); - gl.attachShader(program, vertShader); - gl.attachShader(program, fragShader); - gl.linkProgram(program); - - let failed = false; - let errors = this._errors; - - if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { - _parseError(errors, 'vs', gl.getShaderInfoLog(vertShader)); - failed = true; - } - - if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { - _parseError(errors, 'fs', gl.getShaderInfoLog(fragShader)); - failed = true; - } - - gl.deleteShader(vertShader); - gl.deleteShader(fragShader); - - if (failed) { - errors.forEach(err => { - console.error(`Failed to compile ${err.type} ${err.fileID} (ln ${err.line}): ${err.message}`); - }); - return; - } - - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { - console.error(`Failed to link shader program: ${gl.getProgramInfoLog(program)}`); - failed = true; - } - - if (failed) { - return; - } - - this._glID = program; - - // parse attribute - let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (let i = 0; i < numAttributes; ++i) { - let info = gl.getActiveAttrib(program, i); - let location = gl.getAttribLocation(program, info.name); - - this._attributes.push({ - name: info.name, - location: location, - type: info.type, - }); - } - - // parse uniform - let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (let i = 0; i < numUniforms; ++i) { - let info = gl.getActiveUniform(program, i); - let name = info.name; - let location = gl.getUniformLocation(program, name); - let isArray = name.substr(name.length - 3) === '[0]'; - if (isArray) { - name = name.substr(0, name.length - 3); - } - - let uniform = { - name: name, - location: location, - type: info.type, - size: isArray ? info.size : undefined, // used when uniform is an array - }; - this._uniforms.push(uniform); - } - - this._linked = true; - } - - destroy() { - let gl = this._device._gl; - gl.deleteProgram(this._glID); - - this._linked = false; - this._glID = null; - this._attributes = []; - this._uniforms = []; - this._samplers = []; - } -} - -// ==================== -// internal -// ==================== - -function _createShader(gl, type, src) { - let shader = gl.createShader(type); - gl.shaderSource(shader, src); - gl.compileShader(shader); - - return shader; -} \ No newline at end of file diff --git a/cocos/renderer/gfx/render-buffer.js b/cocos/renderer/gfx/render-buffer.js deleted file mode 100644 index ca7c3d2733..0000000000 --- a/cocos/renderer/gfx/render-buffer.js +++ /dev/null @@ -1,42 +0,0 @@ -export default class RenderBuffer { - /** - * @constructor - * @param {Device} device - * @param {RB_FMT_*} format - * @param {Number} width - * @param {Number} height - */ - constructor(device, format, width, height) { - this._device = device; - this._format = format; - - this._glID = device._gl.createRenderbuffer(); - this.update(width, height); - } - - update(width, height) { - this._width = width; - this._height = height; - const gl = this._device._gl; - gl.bindRenderbuffer(gl.RENDERBUFFER, this._glID); - gl.renderbufferStorage(gl.RENDERBUFFER, this._format, width, height); - gl.bindRenderbuffer(gl.RENDERBUFFER, null); - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === null) { - console.error('The render-buffer already destroyed'); - return; - } - - const gl = this._device._gl; - - gl.bindRenderbuffer(gl.RENDERBUFFER, null); - gl.deleteRenderbuffer(this._glID); - - this._glID = null; - } -} diff --git a/cocos/renderer/gfx/state.js b/cocos/renderer/gfx/state.js deleted file mode 100644 index 747ed4a7b9..0000000000 --- a/cocos/renderer/gfx/state.js +++ /dev/null @@ -1,133 +0,0 @@ -import { enums } from './enums'; - -const _default = { - // blend - blend: false, - blendSep: false, - blendColor: 0xffffffff, - blendEq: enums.BLEND_FUNC_ADD, - blendAlphaEq: enums.BLEND_FUNC_ADD, - blendSrc: enums.BLEND_ONE, - blendDst: enums.BLEND_ZERO, - blendSrcAlpha: enums.BLEND_ONE, - blendDstAlpha: enums.BLEND_ZERO, - - // depth - depthTest: false, - depthWrite: false, - depthFunc: enums.DS_FUNC_LESS, - - // stencil - stencilTest: false, - stencilSep: false, - stencilFuncFront: enums.DS_FUNC_ALWAYS, - stencilRefFront: 0, - stencilMaskFront: 0xff, - stencilFailOpFront: enums.STENCIL_OP_KEEP, - stencilZFailOpFront: enums.STENCIL_OP_KEEP, - stencilZPassOpFront: enums.STENCIL_OP_KEEP, - stencilWriteMaskFront: 0xff, - stencilFuncBack: enums.DS_FUNC_ALWAYS, - stencilRefBack: 0, - stencilMaskBack: 0xff, - stencilFailOpBack: enums.STENCIL_OP_KEEP, - stencilZFailOpBack: enums.STENCIL_OP_KEEP, - stencilZPassOpBack: enums.STENCIL_OP_KEEP, - stencilWriteMaskBack: 0xff, - - // cull-mode - cullMode: enums.CULL_BACK, - - // primitive-type - primitiveType: enums.PT_TRIANGLES, - - // bindings - maxStream: -1, - vertexBuffers: [], - vertexBufferOffsets: [], - indexBuffer: null, - maxTextureSlot: -1, - textureUnits: [], - program: null, -}; - -export default class State { - constructor(device) { - // bindings - this.vertexBuffers = new Array(device._caps.maxVertexStreams); - this.vertexBufferOffsets = new Array(device._caps.maxVertexStreams); - this.textureUnits = new Array(device._caps.maxTextureUnits); - - this.set(_default); - } - - static initDefault(device) { - _default.vertexBuffers = new Array(device._caps.maxVertexStreams); - _default.vertexBufferOffsets = new Array(device._caps.maxVertexStreams); - _default.textureUnits = new Array(device._caps.maxTextureUnits); - } - - reset () { - this.set(_default); - } - - set (cpy) { - // blending - this.blend = cpy.blend; - this.blendSep = cpy.blendSep; - this.blendColor = cpy.blendColor; - this.blendEq = cpy.blendEq; - this.blendAlphaEq = cpy.blendAlphaEq; - this.blendSrc = cpy.blendSrc; - this.blendDst = cpy.blendDst; - this.blendSrcAlpha = cpy.blendSrcAlpha; - this.blendDstAlpha = cpy.blendDstAlpha; - - // depth - this.depthTest = cpy.depthTest; - this.depthWrite = cpy.depthWrite; - this.depthFunc = cpy.depthFunc; - - // stencil - this.stencilTest = cpy.stencilTest; - this.stencilSep = cpy.stencilSep; - this.stencilFuncFront = cpy.stencilFuncFront; - this.stencilRefFront = cpy.stencilRefFront; - this.stencilMaskFront = cpy.stencilMaskFront; - this.stencilFailOpFront = cpy.stencilFailOpFront; - this.stencilZFailOpFront = cpy.stencilZFailOpFront; - this.stencilZPassOpFront = cpy.stencilZPassOpFront; - this.stencilWriteMaskFront = cpy.stencilWriteMaskFront; - this.stencilFuncBack = cpy.stencilFuncBack; - this.stencilRefBack = cpy.stencilRefBack; - this.stencilMaskBack = cpy.stencilMaskBack; - this.stencilFailOpBack = cpy.stencilFailOpBack; - this.stencilZFailOpBack = cpy.stencilZFailOpBack; - this.stencilZPassOpBack = cpy.stencilZPassOpBack; - this.stencilWriteMaskBack = cpy.stencilWriteMaskBack; - - // cull-mode - this.cullMode = cpy.cullMode; - - // primitive-type - this.primitiveType = cpy.primitiveType; - - // buffer bindings - this.maxStream = cpy.maxStream; - for (let i = 0; i < cpy.vertexBuffers.length; ++i) { - this.vertexBuffers[i] = cpy.vertexBuffers[i]; - } - for (let i = 0; i < cpy.vertexBufferOffsets.length; ++i) { - this.vertexBufferOffsets[i] = cpy.vertexBufferOffsets[i]; - } - this.indexBuffer = cpy.indexBuffer; - - // texture bindings - this.maxTextureSlot = cpy.maxTextureSlot; - for (let i = 0; i < cpy.textureUnits.length; ++i) { - this.textureUnits[i] = cpy.textureUnits[i]; - } - - this.program = cpy.program; - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/texture-2d.js b/cocos/renderer/gfx/texture-2d.js deleted file mode 100644 index 3a732514ed..0000000000 --- a/cocos/renderer/gfx/texture-2d.js +++ /dev/null @@ -1,333 +0,0 @@ -// @ts-check -import Texture from './texture'; -import { enums, glFilter, glTextureFmt } from './enums'; -import { isPow2 } from './misc'; - -/** - * @typedef {HTMLImageElement | HTMLCanvasElement} HTMLImageSource - * @typedef {HTMLImageSource | ArrayBufferView} ImageSource - * @typedef {{width?: number, height?: number, minFilter?: number, magFilter?: number, mipFilter?: number, wrapS?: number, wrapT?: number, format?: number, mipmap?: boolean, images?: ImageSource[], image?: ImageSource, flipY?: boolean, premultiplyAlpha?: boolean, anisotropy?: number}} TextureUpdateOpts - * @typedef {import("../gfx/device").default} Device - */ - -export default class Texture2D extends Texture { - /** - * @constructor - * @param {Device} device - * @param {TextureUpdateOpts} options - */ - constructor(device, options) { - super(device); - - let gl = this._device._gl; - this._target = gl.TEXTURE_2D; - this._glID = gl.createTexture(); - - // always alloc texture in GPU when we create it. - options.images = options.images || [null]; - this.update(options); - } - - /** - * @method update - * @param {TextureUpdateOpts} options - */ - update(options) { - let gl = this._device._gl; - let genMipmap = this._hasMipmap; - - if (options) { - if (options.width !== undefined) { - this._width = options.width; - } - if (options.height !== undefined) { - this._height = options.height; - } - if (options.anisotropy !== undefined) { - this._anisotropy = options.anisotropy; - } - if (options.minFilter !== undefined) { - this._minFilter = options.minFilter; - } - if (options.magFilter !== undefined) { - this._magFilter = options.magFilter; - } - if (options.mipFilter !== undefined) { - this._mipFilter = options.mipFilter; - } - if (options.wrapS !== undefined) { - this._wrapS = options.wrapS; - } - if (options.wrapT !== undefined) { - this._wrapT = options.wrapT; - } - if (options.format !== undefined) { - this._format = options.format; - this._compressed = ( - this._format >= enums.TEXTURE_FMT_RGB_DXT1 && - this._format <= enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1 - ); - } - - // check if generate mipmap - if (options.mipmap !== undefined) { - this._hasMipmap = options.mipmap; - genMipmap = options.mipmap; - } - - if (options.images !== undefined) { - if (options.images.length > 1) { - genMipmap = false; - let maxLength = options.width > options.height ? options.width : options.height; - if (maxLength >> (options.images.length - 1) !== 1) { - console.error('texture-2d mipmap is invalid, should have a 1x1 mipmap.'); - } - } - } - } - - // NOTE: get pot after this._width, this._height has been assigned. - let pot = isPow2(this._width) && isPow2(this._height); - if (!pot) { - genMipmap = false; - } - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this._glID); - if (options.images !== undefined && options.images.length > 0) { - this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); - if (options.images.length > 1) this._hasMipmap = true; - } - if (genMipmap) { - gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); - gl.generateMipmap(gl.TEXTURE_2D); - this._hasMipmap = true; - } - - this._setTexInfo(); - this._device._restoreTexture(0); - } - - /** - * @method updateSubImage - * @param {Object} options - * @param {Number} options.x - * @param {Number} options.y - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateSubImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this._glID); - this._setSubImage(glFmt, options); - this._device._restoreTexture(0); - } - - /** - * @method updateImage - * @param {Object} options - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this._glID); - this._setImage(glFmt, options); - this._device._restoreTexture(0); - } - - _setSubImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let img = options.image; - - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - gl.texSubImage2D(gl.TEXTURE_2D, options.level, options.x, options.y, glFmt.format, glFmt.pixelType, img); - } else { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - if (this._compressed) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - img - ); - } else { - gl.texSubImage2D( - gl.TEXTURE_2D, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - _setImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let img = options.image; - - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - gl.texImage2D( - gl.TEXTURE_2D, - options.level, - glFmt.internalFormat, - glFmt.format, - glFmt.pixelType, - img - ); - } else { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - if (this._compressed) { - gl.compressedTexImage2D( - gl.TEXTURE_2D, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - img - ); - } else { - gl.texImage2D( - gl.TEXTURE_2D, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - _setMipmap(images, flipY, premultiplyAlpha) { - let glFmt = glTextureFmt(this._format); - let options = { - width: this._width, - height: this._height, - flipY: flipY, - premultiplyAlpha: premultiplyAlpha, - level: 0, - image: null - }; - - for (let i = 0; i < images.length; ++i) { - options.level = i; - options.width = this._width >> i; - options.height = this._height >> i; - options.image = images[i]; - this._setImage(glFmt, options); - } - } - - _setTexInfo() { - let gl = this._device._gl; - let pot = isPow2(this._width) && isPow2(this._height); - - // WebGL1 doesn't support all wrap modes with NPOT textures - if (!pot && (this._wrapS !== enums.WRAP_CLAMP || this._wrapT !== enums.WRAP_CLAMP)) { - console.warn('WebGL1 doesn\'t support all wrap modes with NPOT textures'); - this._wrapS = enums.WRAP_CLAMP; - this._wrapT = enums.WRAP_CLAMP; - } - - let mipFilter = this._hasMipmap ? this._mipFilter : -1; - if (!pot && mipFilter !== -1) { - console.warn('NPOT textures do not support mipmap filter'); - mipFilter = -1; - } - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilter(gl, this._minFilter, mipFilter)); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilter(gl, this._magFilter, -1)); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT); - - let ext = this._device.ext('EXT_texture_filter_anisotropic'); - if (ext) { - gl.texParameteri(gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); - } - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/texture-cube.js b/cocos/renderer/gfx/texture-cube.js deleted file mode 100644 index c5d9f5c6a2..0000000000 --- a/cocos/renderer/gfx/texture-cube.js +++ /dev/null @@ -1,346 +0,0 @@ -import Texture from './texture'; -import { enums, glFilter, glTextureFmt } from './enums'; -import { isPow2 } from './misc'; - -export default class TextureCube extends Texture { - /** - * @constructor - * @param {Device} device - * @param {Object} options - * @param {Array} options.images - * @param {Boolean} options.mipmap - * @param {Number} options.width - * @param {Number} options.height - * @param {TEXTURE_FMT_*} options.format - * @param {Number} options.anisotropy - * @param {FILTER_*} options.minFilter - * @param {FILTER_*} options.magFilter - * @param {FILTER_*} options.mipFilter - * @param {WRAP_*} options.wrapS - * @param {WRAP_*} options.wrapT - * @param {WRAP_*} options.wrapR - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - constructor(device, options) { - super(device); - let gl = this._device._gl; - this._target = gl.TEXTURE_CUBE_MAP; - this._glID = gl.createTexture(); - this.update(options); - } - - /** - * @method update - * @param {Object} options - * @param {Array} options.images - * @param {Boolean} options.mipmap - * @param {Number} options.width - * @param {Number} options.height - * @param {TEXTURE_FMT_*} options.format - * @param {Number} options.anisotropy - * @param {FILTER_*} options.minFilter - * @param {FILTER_*} options.magFilter - * @param {FILTER_*} options.mipFilter - * @param {WRAP_*} options.wrapS - * @param {WRAP_*} options.wrapT - * @param {WRAP_*} options.wrapR - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - update(options) { - let gl = this._device._gl; - let genMipmap = this._hasMipmap; - - if (options) { - if (options.width !== undefined) { - this._width = options.width; - } - if (options.height !== undefined) { - this._height = options.height; - } - if (options.anisotropy !== undefined) { - this._anisotropy = options.anisotropy; - } - if (options.minFilter !== undefined) { - this._minFilter = options.minFilter; - } - if (options.magFilter !== undefined) { - this._magFilter = options.magFilter; - } - if (options.mipFilter !== undefined) { - this._mipFilter = options.mipFilter; - } - if (options.wrapS !== undefined) { - this._wrapS = options.wrapS; - } - if (options.wrapT !== undefined) { - this._wrapT = options.wrapT; - } - // wrapR available in webgl2 - // if (options.wrapR !== undefined) { - // this._wrapR = options.wrapR; - // } - if (options.format !== undefined) { - this._format = options.format; - this._compressed = ( - this._format >= enums.TEXTURE_FMT_RGB_DXT1 && - this._format <= enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1 - ); - } - - // check if generate mipmap - if (options.mipmap !== undefined) { - this._hasMipmap = options.mipmap; - genMipmap = options.mipmap; - } - - if (options.images !== undefined) { - if (options.images.length > 1) { - genMipmap = false; - if (options.width !== options.height) { - console.warn('texture-cube width and height should be identical.'); - } - if (options.width >> (options.images.length - 1) !== 1) { - console.error('texture-cube mipmap is invalid. please set mipmap as 1x1, 2x2, 4x4 ... nxn'); - } - } - } - } - - // NOTE: get pot after this._width, this._height has been assigned. - let pot = isPow2(this._width) && isPow2(this._height); - if (!pot) { - genMipmap = false; - } - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); - if (options.images !== undefined && options.images.length > 0) { - this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); - if (options.images.length > 1) this._hasMipmap = true; - } - if (genMipmap) { - gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); - gl.generateMipmap(gl.TEXTURE_CUBE_MAP); - this._hasMipmap = true; - } - - this._setTexInfo(); - - this._device._restoreTexture(0); - } - - /** - * @method updateSubImage - * @param {Object} options - * @param {Number} options.x - * @param {Number} options.y - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {Number} options.faceIndex - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateSubImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); - this._setSubImage(glFmt, options); - - this._device._restoreTexture(0); - } - - /** - * @method updateImage - * @param {Object} options - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {Number} options.faceIndex - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); - this._setImage(glFmt, options); - this._device._restoreTexture(0); - } - - _setSubImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let faceIndex = options.faceIndex; - let img = options.image; - - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, options.x, options.y, glFmt.format, glFmt.pixelType, img); - } else { - if (this._compressed) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - img - ); - } else { - gl.texSubImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - _setImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let faceIndex = options.faceIndex; - let img = options.image; - - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - gl.texImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - glFmt.internalFormat, - glFmt.format, - glFmt.pixelType, - img - ); - } else { - if (this._compressed) { - gl.compressedTexImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - img - ); - } else { - gl.texImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - // levelImages = [imagePosX, imageNegX, imagePosY, imageNegY, imagePosZ, imageNegz] - // images = [levelImages0, levelImages1, ...] - _setMipmap(images, flipY, premultiplyAlpha) { - let glFmt = glTextureFmt(this._format); - let options = { - width: this._width, - height: this._height, - faceIndex: 0, - flipY: flipY, - premultiplyAlpha: premultiplyAlpha, - level: 0, - image: null - }; - - for (let i = 0; i < images.length; ++i) { - let levelImages = images[i]; - options.level = i; - options.width = this._width >> i; - options.height = this._height >> i; - - for (let face = 0; face < 6; ++face) { - options.faceIndex = face; - options.image = levelImages[face]; - this._setImage(glFmt, options); - } - } - } - - _setTexInfo() { - let gl = this._device._gl; - let pot = isPow2(this._width) && isPow2(this._height); - - // WebGL1 doesn't support all wrap modes with NPOT textures - if (!pot && (this._wrapS !== enums.WRAP_CLAMP || this._wrapT !== enums.WRAP_CLAMP)) { - console.warn('WebGL1 doesn\'t support all wrap modes with NPOT textures'); - this._wrapS = enums.WRAP_CLAMP; - this._wrapT = enums.WRAP_CLAMP; - } - - let mipFilter = this._hasMipmap ? this._mipFilter : -1; - if (!pot && mipFilter !== -1) { - console.warn('NPOT textures do not support mipmap filter'); - mipFilter = -1; - } - - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, glFilter(gl, this._minFilter, mipFilter)); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, glFilter(gl, this._magFilter, -1)); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, this._wrapS); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, this._wrapT); - // wrapR available in webgl2 - // gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_R, this._wrapR); - - let ext = this._device.ext('EXT_texture_filter_anisotropic'); - if (ext) { - gl.texParameteri(gl.TEXTURE_CUBE_MAP, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); - } - } -} diff --git a/cocos/renderer/gfx/texture.js b/cocos/renderer/gfx/texture.js deleted file mode 100644 index fc26054d4d..0000000000 --- a/cocos/renderer/gfx/texture.js +++ /dev/null @@ -1,52 +0,0 @@ -import { enums } from './enums'; - -/** - * @type {WebGLTexture} - */ -const _nullWebGLTexture = null; - -/** - * @typedef {import("../gfx/device").default} Device - */ - -export default class Texture { - /** - * @param {Device} device - */ - constructor(device) { - this._device = device; - - this._width = 4; - this._height = 4; - this._hasMipmap = false; - this._compressed = false; - - this._anisotropy = 1; - this._minFilter = enums.FILTER_LINEAR; - this._magFilter = enums.FILTER_LINEAR; - this._mipFilter = enums.FILTER_LINEAR; - this._wrapS = enums.WRAP_REPEAT; - this._wrapT = enums.WRAP_REPEAT; - // wrapR available in webgl2 - // this._wrapR = enums.WRAP_REPEAT; - this._format = enums.TEXTURE_FMT_RGBA8; - - this._target = -1; - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === _nullWebGLTexture) { - console.error('The texture already destroyed'); - return; - } - - let gl = this._device._gl; - gl.deleteTexture(this._glID); - - this._device._stats.tex -= this.bytes; - this._glID = _nullWebGLTexture; - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/vertex-buffer.js b/cocos/renderer/gfx/vertex-buffer.js deleted file mode 100644 index 64f377db79..0000000000 --- a/cocos/renderer/gfx/vertex-buffer.js +++ /dev/null @@ -1,154 +0,0 @@ -import { enums } from './enums'; - -class VertexBuffer { - /** - * @constructor - * @param {Device} device - * @param {VertexFormat} format - * @param {USAGE_*} usage - * @param {ArrayBuffer | Uint8Array} data - * @param {Number} numVertices - */ - constructor(device, format, usage, data, numVertices) { - this._device = device; - this._format = format; - this._usage = usage; - this._numVertices = numVertices; - - // calculate bytes - this._bytes = this._format._bytes * numVertices; - - // update - this._glID = device._gl.createBuffer(); - this.update(0, data); - - // stats - device._stats.vb += this._bytes; - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === -1) { - console.error('The buffer already destroyed'); - return; - } - - let gl = this._device._gl; - gl.deleteBuffer(this._glID); - this._device._stats.vb -= this.bytes; - - this._glID = -1; - } - - /** - * @method update - * @param {Number} offset - * @param {ArrayBuffer} data - */ - update(offset, data) { - if (this._glID === -1) { - console.error('The buffer is destroyed'); - return; - } - - if (data && data.byteLength + offset > this._bytes) { - console.error('Failed to update data, bytes exceed.'); - return; - } - - let gl = this._device._gl; - let glUsage = this._usage; - - gl.bindBuffer(gl.ARRAY_BUFFER, this._glID); - if (!data) { - if (this._bytes) { - gl.bufferData(gl.ARRAY_BUFFER, this._bytes, glUsage); - } else { - console.warn('bufferData should not submit 0 bytes data'); - } - } else { - if (offset) { - gl.bufferSubData(gl.ARRAY_BUFFER, offset, data); - } else { - gl.bufferData(gl.ARRAY_BUFFER, data, glUsage); - } - } - gl.bindBuffer(gl.ARRAY_BUFFER, null); - } - - get count () { - return this._numVertices; - } -} - -if (CC_EDITOR) { - let _typeMap = { - [enums.ATTR_TYPE_INT8]: 'Int8', - [enums.ATTR_TYPE_UINT8]: 'Uint8', - [enums.ATTR_TYPE_INT16]: 'Int16', - [enums.ATTR_TYPE_UINT16]: 'Uint16', - [enums.ATTR_TYPE_INT32]: 'Int32', - [enums.ATTR_TYPE_UINT32]: 'Uint32', - [enums.ATTR_TYPE_FLOAT32]: 'Float32' - }; - let littleEndian = (function() { - let buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - let createAttrCache = function(fmt, data) { - if (!data) return []; - let vcount = data.byteLength / fmt.stride; - let bytes = fmt.bytes / fmt.num; - let fname = `get${_typeMap[fmt.type]}`; - let result = new Array(vcount * fmt.num); - for (let i = 0; i < vcount; i++) { - let offset = i * fmt.stride + fmt.offset; - for (let j = 0; j < fmt.num; j++) - result[i * fmt.num + j] = data[fname](offset + j * bytes, littleEndian); - } - return result; - }; - let writeAttrBack = function(fmt, attrData, data) { - let vcount = attrData.length / fmt.num; - let bytes = fmt.bytes / fmt.num; - let fname =`set${_typeMap[fmt.type]}`; - for (let i = 0; i < vcount; i++) { - let offset = i * fmt.stride + fmt.offset; - for (let j = 0; j < fmt.num; j++) { - data[fname](offset + j * bytes, attrData[i * fmt.num + j], littleEndian); - } - } - }; - VertexBuffer.getAttrAt = function(data, idx, fmt, out = []) { - let offset = idx * fmt.stride + fmt.offset; - let bytes = fmt.bytes / fmt.num; - let fname = `get${_typeMap[fmt.type]}`; - for (let i = 0; i < fmt.num; i++) { - out[i] = data[fname](offset + i * bytes, littleEndian); - } - return out; - }; - VertexBuffer.prototype.do_update = VertexBuffer.prototype.update; - VertexBuffer.prototype.update = function(offset, data) { - this.do_update(offset, data); - // don't need to create for IA pools - if (data && this._bytes !== data.byteLength) return; - if (data instanceof ArrayBuffer) - data = new DataView(data); - else if (ArrayBuffer.isView(data) && !(data instanceof DataView)) - data = new DataView(data.buffer, data.byteOffset, data.byteLength); - this.data = data; this.offset = offset; - this[enums.ATTR_POSITION] = createAttrCache(this._format.element(enums.ATTR_POSITION), data); - }; - VertexBuffer.prototype.updateAttr = function(attr, data) { - if (!data) data = this[attr]; - writeAttrBack(this._format.element(attr), data, this.data); - this.do_update(this.offset, this.data); - }; -} - -export default VertexBuffer; diff --git a/cocos/renderer/gfx/vertex-format.js b/cocos/renderer/gfx/vertex-format.js deleted file mode 100644 index 8f3fc4981a..0000000000 --- a/cocos/renderer/gfx/vertex-format.js +++ /dev/null @@ -1,56 +0,0 @@ -import { attrTypeBytes } from './enums'; - -// ==================== -// exports -// ==================== - -export default class VertexFormat { - /** - * @constructor - * @param {Array} infos - * - * @example - * let vertexFmt = new VertexFormat([ - * { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, - * { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, - * { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4, normalize: true }, - * ]) - */ - constructor(infos) { - this._attr2el = {}; - this._elements = []; - this._bytes = 0; - - for (let i = 0, len = infos.length; i < len; ++i) { - let info = infos[i]; - let el = { - name: info.name, - offset: this._bytes, - stride: 0, - stream: -1, - type: info.type, - num: info.num, - normalize: (info.normalize === undefined) ? false : info.normalize, - bytes: info.num * attrTypeBytes(info.type), - }; - - this._attr2el[el.name] = el; - this._elements.push(el); - - this._bytes += el.bytes; - } - - for (let i = 0, len = this._elements.length; i < len; ++i) { - let el = this._elements[i]; - el.stride = this._bytes; - } - } - - /** - * @method element - * @param {string} attrName - */ - element(attrName) { - return this._attr2el[attrName]; - } -} \ No newline at end of file diff --git a/cocos/renderer/index.js b/cocos/renderer/index.js deleted file mode 100644 index f5b185aceb..0000000000 --- a/cocos/renderer/index.js +++ /dev/null @@ -1,58 +0,0 @@ -import enums from './enums'; -import { createIA } from './utils'; -import config from './config'; - -import { RenderQueue, PassStage } from './core/constants'; -import Pass from './core/pass'; -import Technique from './core/technique'; -import Effect from './core/effect'; -import InputAssembler from './core/input-assembler'; -import View from './core/view'; - -import Light from './scene/light'; -import Camera from './scene/camera'; -import Model from './scene/model'; -import Scene from './scene/scene'; - -import LineBatchModel from './models/line-batch-model'; -import SpriteBatchModel from './models/sprite-batch-model'; -import ParticleBatchModel from './models/particle-batch-model'; -import SkinningModel from './models/skinning-model'; - -import ForwardRenderer from './renderers/forward-renderer'; - -let renderer = { - // config - addStage: config.addStage, - - // utils - createIA, - - // core - RenderQueue, - PassStage, - Pass, - Technique, - Effect, - InputAssembler, - View, - - // scene - Light, - Camera, - Model, - Scene, - - // models - LineBatchModel, - SpriteBatchModel, - ParticleBatchModel, - SkinningModel, - - // renderers - ForwardRenderer, -}; -Object.assign(renderer, enums); - -export { renderer }; -cc.renderer = renderer; diff --git a/cocos/renderer/index.ts b/cocos/renderer/index.ts new file mode 100644 index 0000000000..b1cd8bc636 --- /dev/null +++ b/cocos/renderer/index.ts @@ -0,0 +1,18 @@ +export { createIA } from './utils'; +import config from './config'; + +const addStage = config.addStage; +export { addStage }; + +export { RenderQueue, PassStage } from './core/constants'; +export { Pass } from './core/pass'; +export { Effect } from './core/effect'; + +export { Light } from './scene/light'; +export { Camera } from './scene/camera'; +export { Model } from './scene/model'; + +export { default as LineBatchModel } from './models/line-batch-model'; +export { default as SpriteBatchModel } from './models/sprite-batch-model'; +export { default as ParticleBatchModel } from './models/particle-batch-model'; +export { SkinningModel } from './models/skinning-model'; diff --git a/cocos/renderer/models/line-batch-model.js b/cocos/renderer/models/line-batch-model.js index cd414ba457..4f531e4221 100644 --- a/cocos/renderer/models/line-batch-model.js +++ b/cocos/renderer/models/line-batch-model.js @@ -3,7 +3,7 @@ import { vec3, color3 } from '../../core/vmath'; import { RecyclePool } from '../../3d/memop'; -import Model from '../scene/model'; +import { Model } from '../scene/model'; export default class LineBatchModel extends Model { constructor() { diff --git a/cocos/renderer/models/model-uniforms.ts b/cocos/renderer/models/model-uniforms.ts new file mode 100644 index 0000000000..dc7fc83596 --- /dev/null +++ b/cocos/renderer/models/model-uniforms.ts @@ -0,0 +1,20 @@ +import { GFXType } from '../../gfx/define'; +import { GFXUniformBlock, GFXUniformSampler } from '../../gfx/shader'; + +export class SkinningUBO { + public static MAT_JOINT_OFFSET: number = 0; + public static JOINTS_TEXTURE_SIZE_OFFSET: number = SkinningUBO.MAT_JOINT_OFFSET + 128 * 16; + public static COUNT: number = SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET + 4; + public static SIZE: number = SkinningUBO.COUNT * 4; + + public static BLOCK: GFXUniformBlock = { + binding: 29, name: 'CCSkinning', members: [ + { name: 'cc_matJoint', type: GFXType.MAT4, count: 128 }, + { name: 'cc_jointsTextureSize', type: GFXType.FLOAT4, count: 1 }, + ], + }; + + public static JOINT_TEXTURE: GFXUniformSampler = { + binding: 28, name: 'cc_jointsTexture', type: GFXType.SAMPLER2D, count: 1, + }; +} diff --git a/cocos/renderer/models/particle-batch-model.js b/cocos/renderer/models/particle-batch-model.js deleted file mode 100644 index 690f1ad5a3..0000000000 --- a/cocos/renderer/models/particle-batch-model.js +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; -import InputAssembler from '../core/input-assembler'; - -import Model from '../scene/model'; - -function _createInputAssembler(out) { - let vb = new gfx.VertexBuffer( - out._device, - new gfx.VertexFormat(out._vertAttrs), - gfx.USAGE_DYNAMIC, - null, - out._capacity * 4 - ); - - let indices = new Array(out._capacity); - let dst = 0; - for (let i = 0; i < out._capacity; ++i) { - let baseIdx = 4 * i; - indices[dst++] = baseIdx; - indices[dst++] = baseIdx + 1; - indices[dst++] = baseIdx + 2; - indices[dst++] = baseIdx + 3; - indices[dst++] = baseIdx + 2; - indices[dst++] = baseIdx + 1; - } - let ib = new gfx.IndexBuffer( - out._device, - gfx.INDEX_FMT_UINT16, - gfx.USAGE_STATIC, - new Uint16Array(indices), - indices.length - ); - - out._ia = new InputAssembler(vb, ib); -} - -export default class ParticleBatchModel extends Model { - constructor(device, capacity, vertAttrs) { - super(); - - this._type = 'particle-batch'; - this._device = device; - this._capacity = capacity; - this.setVertexAttributes(vertAttrs); - } - - setVertexAttributes(attrs) { - this._vertAttrs = attrs; - // rebuid - _createInputAssembler(this); - this._vertAttrsSize = this._ia._vertexBuffer._format._bytes / 4; // number of float - this._vBuffer = new ArrayBuffer(this._capacity * this._ia._vertexBuffer._format._bytes); - this._vdataF32 = new Float32Array(this._vBuffer); - this._vdataUint32 = new Uint32Array(this._vBuffer); - } - - enableStretchedBillboard() { - if (this._vertAttrs.find(attr => attr.name === gfx.ATTR_COLOR0) === undefined) { - this._vertAttrs.push({ name: gfx.ATTR_COLOR0, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - this.setVertexAttributes(this._vertAttrs); - } - } - - disableStretchedBillboard() { - if (this._vertAttrs.find(attr => attr.name === gfx.ATTR_COLOR0) !== undefined) { - this._vertAttrs.pop(); - this.setVertexAttributes(this._vertAttrs); - } - } - - setParticleRenderer(r) { - this._renderer = r; - } - - addParticleVertexData(index, pvdata) { - // if (pvdata.length !== this._vertAttrs.length) { - // console.error('particle vertex stream data not match.'); - // } - let offset = index * this._vertAttrsSize; - for (let i = 0; i < this._vertAttrs.length; ++i) { - let curAttr = this._vertAttrs[i]; - if (curAttr.num === 1) { - this._vdataF32[offset] = pvdata[i]; // if not a single float? - offset++; - } else if (curAttr.num === 2) { - this._vdataF32[offset] = pvdata[i].x; - this._vdataF32[offset + 1] = pvdata[i].y; - offset += 2; - } else if (curAttr.num === 3) { - this._vdataF32[offset] = pvdata[i].x; - this._vdataF32[offset + 1] = pvdata[i].y; - this._vdataF32[offset + 2] = pvdata[i].z; - offset += 3; - } else if (curAttr.index === gfx.ATTR_INDEX_COLOR) { - this._vdataUint32[offset] = pvdata[i]; - offset += 1; - } else { - console.error('particle vertex attribute format not support'); - } - } - } - - updateIA(count) { - this._ia._count = count; - this._ia._vertexBuffer.update(0, this._vdataF32); - } - - clear() { - this._ia._count = 0; - } - - destroy() { - this._vdataF32 = null; - this._ia._vertexBuffer.destroy(); - this._ia._indexBuffer.destroy(); - } -} diff --git a/cocos/renderer/models/particle-batch-model.ts b/cocos/renderer/models/particle-batch-model.ts new file mode 100644 index 0000000000..689c56b2ef --- /dev/null +++ b/cocos/renderer/models/particle-batch-model.ts @@ -0,0 +1,189 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { IRenderingSubmesh } from '../../3d/assets/mesh'; +import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../gfx/buffer'; +import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, + GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; +import { IGFXInputAttribute } from '../../gfx/input-assembler'; +import { Node } from '../../scene-graph'; +import { Model } from '../scene/model'; +import { RenderScene } from '../scene/render-scene'; + +export default class ParticleBatchModel extends Model { + + private _capacity: number; + private _vertAttrs: IGFXInputAttribute[] | null; + private _vertSize: number; + private _vBuffer: ArrayBuffer | null; + private _vertAttrsFloatCount: number; + private _vdataF32: Float32Array | null; + private _vdataUint32: Uint32Array | null; + private _iaInfo: IGFXIndirectBuffer; + private _iaInfoBuffer: GFXBuffer; + private _subMeshData: IRenderingSubmesh | null; + + constructor (scene: RenderScene, node: Node) { + super(scene, node); + + this._type = 'particle-batch'; + this._capacity = 0; + this._vertAttrs = null; + this._vertSize = 0; + this._vBuffer = null; + this._vertAttrsFloatCount = 0; + this._vdataF32 = null; + this._vdataUint32 = null; + this._iaInfo = { + drawInfos: [{ + vertexCount: 0, + firstVertex: 0, + indexCount: 0, + firstIndex: 0, + vertexOffset: 0, + instanceCount: 0, + firstInstance: 0, + }], + }; + this._iaInfoBuffer = this._device.createBuffer({ + usage: GFXBufferUsageBit.INDIRECT, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: GFX_DRAW_INFO_SIZE, + stride: 1, + }); + this._subMeshData = null; + } + + public setCapacity (capacity: number) { + this._capacity = capacity; + } + + public setVertexAttributes (attrs: IGFXInputAttribute[]) { + this._vertAttrs = attrs; + this._vertSize = 0; + for (const a of this._vertAttrs) { + this._vertSize += GFXFormatInfos[a.format].size; + } + // rebuid + this._vBuffer = this._createSubMeshData(); + this._vertAttrsFloatCount = this._vertSize / 4; // number of float + this._vBuffer = new ArrayBuffer(this._capacity * this._vertSize * 4); + this._vdataF32 = new Float32Array(this._vBuffer); + this._vdataUint32 = new Uint32Array(this._vBuffer); + } + + public _createSubMeshData (): ArrayBuffer { + if (this._subMeshData) { + this.destroySubMeshData(); + } + const vertexBuffer = this._device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: this._vertSize * this._capacity * 4, + stride: this._vertSize, + }); + const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertSize * this._capacity * 4); + vertexBuffer.update(vBuffer); + + const indices: Uint16Array = new Uint16Array(this._capacity * 6); + let dst = 0; + for (let i = 0; i < this._capacity; ++i) { + const baseIdx = 4 * i; + indices[dst++] = baseIdx; + indices[dst++] = baseIdx + 1; + indices[dst++] = baseIdx + 2; + indices[dst++] = baseIdx + 3; + indices[dst++] = baseIdx + 2; + indices[dst++] = baseIdx + 1; + } + + const indexBuffer = this._device.createBuffer({ + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: this._capacity * 6 * Uint16Array.BYTES_PER_ELEMENT, + stride: Uint16Array.BYTES_PER_ELEMENT, + }); + + indexBuffer.update(indices); + + this._iaInfo.drawInfos[0].vertexCount = this._capacity * 4; + this._iaInfo.drawInfos[0].indexCount = this._capacity * 6; + this._iaInfoBuffer.update(this._iaInfo); + + this._subMeshData = { + vertexBuffers: [vertexBuffer], + indexBuffer, + indirectBuffer: this._iaInfoBuffer, + attributes: this._vertAttrs!, + primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST, + }; + this.setSubModelMesh(0, this._subMeshData); + return vBuffer; + } + + public enableStretchedBillboard () { + if (this._vertAttrs!.find((attr) => attr.name === GFXAttributeName.ATTR_COLOR1) === undefined) { + this._vertAttrs!.push({ name: GFXAttributeName.ATTR_COLOR1, format: GFXFormat.RGB32F }); + this.setVertexAttributes(this._vertAttrs!); + } + } + + public disableStretchedBillboard () { + if (this._vertAttrs!.find((attr) => attr.name === GFXAttributeName.ATTR_COLOR1) !== undefined) { + this._vertAttrs!.pop(); + this.setVertexAttributes(this._vertAttrs!); + } + } + + public addParticleVertexData (index: number, pvdata: any[]) { + // if (pvdata.length !== this._vertAttrs.length) { + // console.error('particle vertex stream data not match.'); + // } + let offset: number = index * this._vertAttrsFloatCount; + for (let i = 0; i < this._vertAttrs!.length; ++i) { + const curAttr: IGFXInputAttribute = this._vertAttrs![i]; + if (curAttr.format === GFXFormat.R32F) { + this._vdataF32![offset] = pvdata[i]; // if not a single float? + offset++; + } else if (curAttr.format === GFXFormat.RG32F) { + this._vdataF32![offset] = pvdata[i].x; + this._vdataF32![offset + 1] = pvdata[i].y; + offset += 2; + } else if (curAttr.format === GFXFormat.RGB32F) { + this._vdataF32![offset] = pvdata[i].x; + this._vdataF32![offset + 1] = pvdata[i].y; + this._vdataF32![offset + 2] = pvdata[i].z; + offset += 3; + } else if (curAttr.format === GFXFormat.RGBA8) { + this._vdataUint32![offset] = pvdata[i]; + offset += 1; + } else { + console.error('particle vertex attribute format not support'); + } + } + } + + public updateIA (count: number) { + this.getSubModel(0).inputAssembler!.vertexBuffers[0].update(this._vdataF32!); + this.getSubModel(0).inputAssembler!.indexCount = count; + this.getSubModel(0).inputAssembler!.extractDrawInfo(this._iaInfo.drawInfos[0]); + this._iaInfoBuffer.update(this._iaInfo); + } + + public clear () { + this.getSubModel(0).inputAssembler!.indexCount = 0; + } + + public destroy () { + super.destroy(); + this._vdataF32 = null; + this.destroySubMeshData(); + this._iaInfoBuffer.destroy(); + } + + private destroySubMeshData () { + for (const vb of this._subMeshData!.vertexBuffers) { + vb.destroy(); + } + this._subMeshData!.indexBuffer.destroy(); + } +} diff --git a/cocos/renderer/models/skinning-model.js b/cocos/renderer/models/skinning-model.js deleted file mode 100644 index 10fc84f14b..0000000000 --- a/cocos/renderer/models/skinning-model.js +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import Model from '../scene/model'; - -export default class SkinningModel extends Model { - constructor() { - super(); - - this._type = 'skinning'; - this._jointsTexture = null; - this._jointsMatrixArray = null; - } - - setJointsTexture(texture) { - this._jointsTexture = texture; - } - - setJointsMatrixArray(a) { - this._jointsMatrixArray = a; - } -} \ No newline at end of file diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts new file mode 100644 index 0000000000..14e7e0a9a7 --- /dev/null +++ b/cocos/renderer/models/skinning-model.ts @@ -0,0 +1,162 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import Skeleton from '../../3d/assets/skeleton'; +import { Texture2D } from '../../assets/texture-2d'; +import { mat4 } from '../../core/vmath'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXFeature } from '../../gfx/device'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { Node } from '../../scene-graph/node'; +import { Model } from '../scene/model'; +import { RenderScene } from '../scene/render-scene'; +import { SkinningUBO } from './model-uniforms'; +import { PixelFormat, Filter, WrapMode } from '../../assets/texture-base'; + +const textureSizeBuffer = new Float32Array(4); + +interface IJointTextureStorage { + nativeData: Float32Array; + texture: Texture2D; +} + +interface IJointUniformsStorage { + nativeData: Float32Array; +} + +type JointStorage = IJointTextureStorage | IJointUniformsStorage; + +function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { + return 'texture' in storage; +} + +function isUniformStorage (storage: JointStorage): storage is IJointUniformsStorage { + return !('texture' in storage); +} + +export const __FORCE_USE_UNIFORM_STORAGE__ = false; + +export class SkinningModel extends Model { + private _jointStorage: JointStorage | null = null; + private _skinningUBO: GFXBuffer; + + constructor (scene: RenderScene, node: Node) { + super(scene, node); + this._type = 'skinning'; + this._skinningUBO = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: SkinningUBO.SIZE, + stride: SkinningUBO.SIZE, + }); + } + + public bindSkeleton (skeleton: Skeleton) { + this._destroyJointStorage(); + + if (!__FORCE_USE_UNIFORM_STORAGE__ && this._device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { + const jointsTexture = _createJointsTexture(skeleton); + textureSizeBuffer[0] = jointsTexture.width; + this._skinningUBO.update( + textureSizeBuffer, SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET, textureSizeBuffer.byteLength); + this._jointStorage = { + texture: jointsTexture, + nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), + } as IJointTextureStorage; + } else { + this._jointStorage = { + nativeData: new Float32Array(skeleton.joints.length * 16), + } as IJointUniformsStorage; + } + } + + public updateJointMatrix (iMatrix: number, matrix: mat4) { + if (!this._jointStorage) { + return; + } + _setJointMatrix(this._jointStorage.nativeData, iMatrix, matrix); + } + + public commitJointMatrices () { + if (!this._jointStorage) { + return; + } + if (isUniformStorage(this._jointStorage)) { + this._skinningUBO.update(this._jointStorage.nativeData, SkinningUBO.MAT_JOINT_OFFSET); + } else if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.directUpdate(this._jointStorage.nativeData.buffer); + } + } + + protected _onCreatePSO (pso: GFXPipelineState) { + super._onCreatePSO(pso); + pso.pipelineLayout.layouts[0].bindBuffer(SkinningUBO.BLOCK.binding, this._skinningUBO); + if (this._jointStorage && isTextureStorage(this._jointStorage)) { + const jointTexture = this._jointStorage.texture; + const view = jointTexture.getGFXTextureView(); + const sampler = jointTexture.getGFXSampler(); + if (view && sampler) { + pso.pipelineLayout.layouts[0].bindTextureView(SkinningUBO.JOINT_TEXTURE.binding, view); + pso.pipelineLayout.layouts[0].bindSampler(SkinningUBO.JOINT_TEXTURE.binding, sampler); + } + } + } + + private _destroyJointStorage () { + if (!this._jointStorage) { + return; + } + if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.destroy(); + } + this._jointStorage = null; + } +} + +function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { + out[16 * iMatrix + 0] = matrix.m00; + out[16 * iMatrix + 1] = matrix.m01; + out[16 * iMatrix + 2] = matrix.m02; + out[16 * iMatrix + 3] = matrix.m03; + out[16 * iMatrix + 4] = matrix.m04; + out[16 * iMatrix + 5] = matrix.m05; + out[16 * iMatrix + 6] = matrix.m06; + out[16 * iMatrix + 7] = matrix.m07; + out[16 * iMatrix + 8] = matrix.m08; + out[16 * iMatrix + 9] = matrix.m09; + out[16 * iMatrix + 10] = matrix.m10; + out[16 * iMatrix + 11] = matrix.m11; + out[16 * iMatrix + 12] = matrix.m12; + out[16 * iMatrix + 13] = matrix.m13; + out[16 * iMatrix + 14] = matrix.m14; + out[16 * iMatrix + 15] = matrix.m15; +} + +function _createJointsTexture (skinning: { joints: any[]; }) { + const jointCount = skinning.joints.length; + + // Set jointsTexture. + // A squared texture with side length N(N > 1) multiples of 2 can store + // 2 ^ (2 * N - 2) matrices. + // We support most 1024 joints. + let size = 0; + if (jointCount > 1024) { + throw new Error('To many joints(more than 1024).'); + } else if (jointCount > 256) { + size = 64; + } else if (jointCount > 64) { + size = 32; + } else if (jointCount > 16) { + size = 16; + } else if (jointCount > 4) { + size = 8; + } else { + size = 4; + } + + const texture = new Texture2D(); + texture.create(size, size, PixelFormat.RGBA32F); + texture.setFilters(Filter.NEAREST, Filter.NEAREST); + texture.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + return texture; +} \ No newline at end of file diff --git a/cocos/renderer/models/sprite-batch-model.js b/cocos/renderer/models/sprite-batch-model.js index 3eabd2740d..4c4525d714 100644 --- a/cocos/renderer/models/sprite-batch-model.js +++ b/cocos/renderer/models/sprite-batch-model.js @@ -2,7 +2,7 @@ import { RecyclePool } from '../../3d/memop'; -import Model from '../scene/model'; +import { Model } from '../scene/model'; export default class SpriteBatchModel extends Model { constructor() { diff --git a/cocos/renderer/renderers/forward-renderer.js b/cocos/renderer/renderers/forward-renderer.js deleted file mode 100644 index d27f320fc4..0000000000 --- a/cocos/renderer/renderers/forward-renderer.js +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; -import { vec3, mat4 } from '../../core/vmath'; - -import BaseRenderer from '../core/base-renderer'; -import DynamicIAPool from '../core/dynamic-ia-pool'; -import enums from '../enums'; -import { PassStage } from '../core/constants'; - -// import GaussianBlur from './gaussian-blur'; - -let _camPos = vec3.create(0, 0, 0); -let _camFwd = vec3.create(0, 0, 0); - -let _a16_view = new Float32Array(16); -let _a16_proj = new Float32Array(16); -let _a16_viewProj = new Float32Array(16); -let _a16_lightViewProj = new Float32Array(16); -let _a3_camPos = new Float32Array(3); - -export default class ForwardRenderer extends BaseRenderer { - constructor(device, builtin) { - super(device, builtin); - this._directionalLights = []; - this._pointLights = []; - this._spotLights = []; - this._shadowLights = []; - this._sceneAmbient = new Float32Array([0.5, 0.5, 0.5]); - - this._registerStage(PassStage.SHADOWCAST, this._shadowStage.bind(this)); - this._registerStage(PassStage.DEFAULT, this._defaultStage.bind(this)); - this._registerStage(PassStage.FORWARD, this._forwardStage.bind(this)); - - this._registerModel('default', this._draw.bind(this)); - this._registerModel('line-batch', this._drawLineBatch.bind(this)); - this._registerModel('sprite-batch', this._drawSpriteBatch.bind(this)); - this._registerModel('particle-batch', this._drawParticleBatch.bind(this)); - this._registerModel('skinning', this._drawSkinning.bind(this)); - - // this._blur = new GaussianBlur(device, this._programLib); - - // lineIAs - this._lineIAs = new DynamicIAPool( - device, 2, - gfx.PT_LINES, - new gfx.VertexFormat([ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, - { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 3 } - ]), - 2000 - ); - - // spriteIAs - this._spriteIAs = new DynamicIAPool( - device, 2, - gfx.PT_TRIANGLES, - new gfx.VertexFormat([ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, - { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, - { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4 } - ]), - 2000, - gfx.INDEX_FMT_UINT16, - 2000 - ); - } - - updateLights(scene) { - this._directionalLights.length = 0; - this._pointLights.length = 0; - this._spotLights.length = 0; - this._shadowLights.length = 0; - let lights = scene._lights; - for (let i = 0; i < lights.length; ++i) { - let light = lights.data[i]; - light.update(this._device); - if (light.shadowType !== enums.SHADOW_NONE) { - this._shadowLights.push(light); - let view = this._requestView(); - light.extractView(view, PassStage.SHADOWCAST); - } - if (light._type === enums.LIGHT_DIRECTIONAL) { - this._directionalLights.push(light); - } else if (light._type === enums.LIGHT_POINT) { - this._pointLights.push(light); - } else { - this._spotLights.push(light); - } - } - } - - render(scene) { - this._reset(); - - const canvas = this._device._gl.canvas; - - // update lights, extract shadow view. - this.updateLights(scene); - - // extract views from cameras, lights and so on - if (scene._debugCamera) { - let view = this._requestView(); - scene._debugCamera.extractView(view, canvas.width, canvas.height); - } else { - for (let i = 0; i < scene._cameras.length; ++i) { - let view = this._requestView(); - scene._cameras.data[i].extractView(view, canvas.width, canvas.height); - } - } - - // render by cameras - this._viewPools.sort((a, b) => { - return (a._priority - b._priority); - }); - scene._views.sort((a, b) => { - return (a._priority - b._priority); - }); - for (let i = 0; i < this._viewPools.length; ++i) { - let view = this._viewPools.data[i]; - this._render(view, scene); - } - - // render by views (ui) - for (let i = 0; i < scene._views.length; ++i) { - let view = scene._views[i]; - this._render(view, scene); - } - } - - _submitLightUniforms() { - this._device.setUniform('_sceneAmbient', this._sceneAmbient); - - if (this._directionalLights.length > 0) { - for (let index = 0; index < this._directionalLights.length; ++index) { - let light = this._directionalLights[index]; - this._device.setUniform(`_dir_light${index}_direction`, light._directionUniform); - this._device.setUniform(`_dir_light${index}_color`, light._colorUniform); - } - } - if (this._pointLights.length > 0) { - for (let index = 0; index < this._pointLights.length; ++index) { - let light = this._pointLights[index]; - this._device.setUniform(`_point_light${index}_position`, light._positionUniform); - this._device.setUniform(`_point_light${index}_color`, light._colorUniform); - this._device.setUniform(`_point_light${index}_range`, light._range); - } - } - - if (this._spotLights.length > 0) { - for (let index = 0; index < this._spotLights.length; ++index) { - let light = this._spotLights[index]; - this._device.setUniform(`_spot_light${index}_position`, light._positionUniform); - this._device.setUniform(`_spot_light${index}_direction`, light._directionUniform); - this._device.setUniform(`_spot_light${index}_color`, light._colorUniform); - this._device.setUniform(`_spot_light${index}_range`, light._range); - this._device.setUniform(`_spot_light${index}_spot`, light._spotUniform); - } - } - } - - _submitShadowStageUniforms(view) { - let light = view._shadowLight; - this._device.setUniform('_minDepth', light.shadowMinDepth); - this._device.setUniform('_maxDepth', light.shadowMaxDepth); - this._device.setUniform('_bias', light.shadowBias); - this._device.setUniform('_depthScale', light.shadowDepthScale); - } - - _submitOtherStagesUniforms() { - for (let index = 0; index < this._shadowLights.length; ++index) { - let light = this._shadowLights[index]; - this._device.setUniform(`_lightViewProjMatrix_${index}`, mat4.array(_a16_lightViewProj, light.viewProjMatrix)); - this._device.setUniform(`_minDepth_${index}`, light.shadowMinDepth); - this._device.setUniform(`_maxDepth_${index}`, light.shadowMaxDepth); - this._device.setUniform(`_bias_${index}`, light.shadowBias); - this._device.setUniform(`_depthScale_${index}`, light.shadowDepthScale); - this._device.setUniform(`_darkness_${index}`, light.shadowDarkness); - this._device.setUniform(`_frustumEdgeFalloff_${index}`, light.frustumEdgeFalloff); - this._device.setUniform(`_texelSize_${index}`, new Float32Array([1.0 / light.shadowResolution, 1.0 / light.shadowResolution])); - } - } - - _updateShaderDefines(item) { - // for (let i = 0; i < items.length; ++i) { - // let item = items.data[i]; - let defines = item.defines; - - defines['_NUM_DIR_LIGHTS'] = Math.min(4, this._directionalLights.length); - defines['_NUM_POINT_LIGHTS'] = Math.min(4, this._pointLights.length); - defines['_NUM_SPOT_LIGHTS'] = Math.min(4, this._spotLights.length); - - defines['_NUM_SHADOW_LIGHTS'] = Math.min(4, this._shadowLights.length); - // } - } - - _shadowStage(item) { - this._device.setUniform('_lightViewProjMatrix', mat4.array(_a16_viewProj, this._currentView._matViewProj)); - - // update rendering - // this._submitLightUniforms(); - this._submitShadowStageUniforms(this._currentView); - this._updateShaderDefines(item); - - - // draw it - - if (item.model._castShadow) { - this._drawPass(item); - } - - } - - _defaultStage(item) { - this._drawPass(item); - } - - _forwardStage(item) { - - // update rendering - this._submitLightUniforms(); - this._submitOtherStagesUniforms(); - this._updateShaderDefines(item); - - - for (let index = 0; index < this._shadowLights.length; ++index) { - let light = this._shadowLights[index]; - this._device.setTexture(`_shadowMap_${index}`, light.shadowMap, this._allocTextureUnit()); - } - - this._drawPass(item); - } - - - - _drawSkinning(item) { - let { model, defines } = item; - - defines['_USE_SKINNING'] = true; - if (model._jointsTexture != null) { - defines['_USE_JOINTS_TEXTURE'] = true; - this._device.setTexture('_u_jointsTexture', model._jointsTexture, this._allocTextureUnit()); - this._device.setUniform('_u_jointsTextureSize', model._jointsTexture._width); - } else if (model._jointsMatrixArray != null) { - defines['_USE_JOINTS_TEXTURE'] = false; - this._device.setUniform("_u_jointMatrices", model._jointsMatrixArray); - } - - this._draw(item); - } - - _drawLineBatch(item) { - let model = item.model; - let curVertCount = 0; - let vdata = this._lineIAs.requestVData(model.vertCount); - let vdataF32 = vdata.float32View; - - for (let i = model.lineCount - 1; i >= 0; --i) { - let line = model.getLine(i); - - // flush when verts exceeds - if (curVertCount + 2 >= this._lineIAs.maxVerts) { - let ia = this._lineIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._start = 0; - ia._count = curVertCount; - - item.ia = ia; - this._draw(item); - curVertCount = 0; - } - - // - let idx = curVertCount * 6; - vdataF32[idx] = line.start.x; - vdataF32[idx + 1] = line.start.y; - vdataF32[idx + 2] = line.start.z; - vdataF32[idx + 3] = line.color.r; - vdataF32[idx + 4] = line.color.g; - vdataF32[idx + 5] = line.color.b; - - vdataF32[idx + 6] = line.end.x; - vdataF32[idx + 7] = line.end.y; - vdataF32[idx + 8] = line.end.z; - vdataF32[idx + 9] = line.color.r; - vdataF32[idx + 10] = line.color.g; - vdataF32[idx + 11] = line.color.b; - - curVertCount += 2; - } - - // flush rest verts - if (curVertCount > 0) { - let ia = this._lineIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._start = 0; - ia._count = curVertCount; - - item.ia = ia; - this._draw(item); - } - } - - _drawSpriteBatch(item) { - let model = item.model; - let curVertOffset = 0; - let curVertCount = 0; - let curIndexCount = 0; - let vdata = this._spriteIAs.requestVData(model.vertCount); - let idata = this._spriteIAs.requestIData(model.indexCount); - let vdataF32 = vdata.float32View; - let idataU16 = idata.uint16View; - - for (let i = 0; i < model.spriteCount; ++i) { - let sprite = model.getSprite(i); - let vcount = sprite.refPositions.length; - let icount = sprite.refIndices.length; - - // flush when verts exceeds - if ( - curVertCount + vcount >= this._spriteIAs.maxVerts || - curIndexCount + icount >= this._spriteIAs.maxIndices - ) { - let ia = this._spriteIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._indexBuffer.update(0, idataU16); - - ia._start = 0; - ia._count = curIndexCount; - - item.ia = ia; - this._draw(item); - - curVertOffset = 0; - curVertCount = 0; - curIndexCount = 0; - } - - // - for (let j = 0; j < vcount; ++j) { - let idx = curVertCount * 9; - - vdataF32[idx] = sprite.refPositions[j].x; - vdataF32[idx + 1] = sprite.refPositions[j].y; - vdataF32[idx + 2] = sprite.refPositions[j].z; - vdataF32[idx + 3] = sprite.refUVs[j].x; - vdataF32[idx + 4] = sprite.refUVs[j].y; - vdataF32[idx + 5] = sprite.refColor.r; - vdataF32[idx + 6] = sprite.refColor.g; - vdataF32[idx + 7] = sprite.refColor.b; - vdataF32[idx + 8] = sprite.refColor.a; - - curVertCount += 1; - } - - for (let j = 0; j < icount; ++j) { - let idx = curIndexCount; - - idataU16[idx] = curVertOffset + sprite.refIndices[j]; - - curIndexCount += 1; - } - - curVertOffset += vcount; - } - - // flush rest verts & indices - if (curIndexCount > 0) { - let ia = this._spriteIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._indexBuffer.update(0, idataU16); - ia._start = 0; - ia._count = curIndexCount; - - item.ia = ia; - this._draw(item); - } - } - - _drawParticleBatch(item) { - item.ia = item.model._ia; - if (item.model._renderer) { - item.model._renderer.updateShaderUniform(); - } - this._draw(item); - } -} diff --git a/cocos/renderer/renderers/gaussian-blur.js b/cocos/renderer/renderers/gaussian-blur.js deleted file mode 100644 index 251d8d93ea..0000000000 --- a/cocos/renderer/renderers/gaussian-blur.js +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../../gfx'; - -export default class GaussianBlur { - constructor(device, proglib) { - this._device = device; - this._width = 1024; - this._height = 1024; - this._XBlurFrameBuffer = null; - this._XBluredTexture = null; - this._YBlurFrameBuffer = null; - this._YBluredTexture = null; - this._sourceTexture = null; - this._programLib = proglib; - } - - setupBlur(tex) { - this._sourceTexture = tex; - this._width = tex._width; - this._height = tex._height; - if (!this._XBlurFrameBuffer || !this._YBlurFrameBuffer) { - this._XBluredTexture = new gfx.Texture2D(this._device, { - width: this._width, - height: this._height, - format: gfx.TEXTURE_FMT_RGBA8, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - }); - this._XBlurFrameBuffer = new gfx.FrameBuffer(this._device, this._width, this._height, { - colors: [this._XBluredTexture], - }); - this._YBluredTexture = new gfx.Texture2D(this._device, { - width: this._width, - height: this._height, - format: gfx.TEXTURE_FMT_RGBA8, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - }); - this._YBlurFrameBuffer = new gfx.FrameBuffer(this._device, this._width, this._height, { - colors: [this._YBluredTexture], - }); - } - } - - processBlur() { - // position.xy uv - let verts = [ - -1, 1, 0, 1, - -1, -1, 0, 0, - 1, -1, 1, 0, - -1, 1, 0, 1, - 1, -1, 1, 0, - 1, 1, 1, 1 - ]; - let vfmt = [ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, - { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 } - ]; - let vb = new gfx.VertexBuffer( - this._device, - new gfx.VertexFormat(vfmt), - gfx.USAGE_STATIC, - new Float32Array(verts), - 6 - ); - // x-blur - this._device.setFrameBuffer(this._XBlurFrameBuffer); - this._device.setViewport(0, 0, this._width, this._height); - this._device.clear({ - color: [0, 0, 0, 1] - }); - this._device.setTexture('texture', this._sourceTexture, 0); - this._device.setUniform('pixelSize',new Float32Array([1.0 / this._width, 0.0])); - this._device.setVertexBuffer(0, vb); - this._device.setProgram(this._programLib.getProgram('gaussian-blur')); - this._device.draw(0, 6); - // y-blur - this._device.setFrameBuffer(this._YBlurFrameBuffer); - this._device.clear({ - color: [0, 0, 0, 1] - }); - this._device.setTexture('texture', this._XBluredTexture, 0); - this._device.setUniform('pixelSize',new Float32Array([0.0, 1.0 / this._height])); - this._device.setVertexBuffer(0, vb); - this._device.setProgram(this._programLib.getProgram('gaussian-blur')); - this._device.draw(0, 6); - this._device.setFrameBuffer(null); - } - - getBluredTexture() { - // TODO: should support only x-blur or y-blur ? - return this._YBluredTexture; - } - -} \ No newline at end of file diff --git a/cocos/renderer/scene/camera.js b/cocos/renderer/scene/camera.js deleted file mode 100644 index 898800c409..0000000000 --- a/cocos/renderer/scene/camera.js +++ /dev/null @@ -1,465 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { color4, vec3, mat4, lerp } from '../../core/vmath'; -import { ray } from '../../3d/geom-utils'; -import enums from '../enums'; - -let _matView = mat4.create(); -let _matProj = mat4.create(); -let _matViewProj = mat4.create(); -let _matInvViewProj = mat4.create(); -let _tmp_v3 = vec3.create(); -let _tmp2_v3 = vec3.create(); - -/** - * A representation of a camera instance - */ -export default class Camera { - /** - * Setup a default perspective camera - */ - constructor() { - this._poolID = -1; - this._node = null; - - // - this._projection = enums.PROJ_PERSPECTIVE; - - // priority. the smaller one will be rendered first - this._priority = 0; - - // clear options - this._color = color4.create(); - this._depth = 1; - this._stencil = 0; - this._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; - this._clearModel = null; - - // stages & framebuffer - this._stages = 0; - this._framebuffer = null; - - // projection properties - this._near = 0.01; - this._far = 1000.0; - this._fov = Math.PI/4.0; // vertical fov - this._rect = { - x: 0, y: 0, w: 1, h: 1 - }; - - // ortho properties - this._orthoHeight = 10; - } - - /** - * Get the hosting node of this camera - * @returns {Node} the hosting node - */ - getNode() { - return this._node; - } - - /** - * Set the hosting node of this camera - * @param {Node} node the hosting node - */ - setNode(node) { - this._node = node; - } - - /** - * Get the projection type of the camera - * @returns {number} camera projection type - */ - getType() { - return this._projection; - } - - /** - * Set the projection type of the camera - * @param {number} type camera projection type - */ - setType(type) { - this._projection = type; - } - - /** - * Get the priority of the camera - * @returns {number} camera priority - */ - getPriority() { - return this._priority; - } - - /** - * Set the priority of the camera - * @param {number} priority camera priority - */ - setPriority(priority) { - this._priority = priority; - } - - /** - * Get the orthogonal height of the camera - * @returns {number} camera height - */ - getOrthoHeight() { - return this._orthoHeight; - } - - /** - * Set the orthogonal height of the camera - * @param {number} val camera height - */ - setOrthoHeight(val) { - this._orthoHeight = val; - } - - /** - * Get the field of view of the camera - * @returns {number} camera field of view - */ - getFov() { - return this._fov; - } - - /** - * Set the field of view of the camera - * @param {number} fov camera field of view - */ - setFov(fov) { - this._fov = fov; - } - - /** - * Get the near clipping distance of the camera - * @returns {number} camera near clipping distance - */ - getNear() { - return this._near; - } - - /** - * Set the near clipping distance of the camera - * @param {number} near camera near clipping distance - */ - setNear(near) { - this._near = near; - } - - /** - * Get the far clipping distance of the camera - * @returns {number} camera far clipping distance - */ - getFar() { - return this._far; - } - - /** - * Set the far clipping distance of the camera - * @param {number} far camera far clipping distance - */ - setFar(far) { - this._far = far; - } - - /** - * Get the clear color of the camera - * @returns {color4} out the receiving color vector - */ - getColor(out) { - return color4.copy(out, this._color); - } - - /** - * Set the clear color of the camera - * @param {number} r red channel of camera clear color - * @param {number} g green channel of camera clear color - * @param {number} b blue channel of camera clear color - * @param {number} a alpha channel of camera clear color - */ - setColor(r, g, b, a) { - color4.set(this._color, r, g, b, a); - } - - /** - * Get the clear depth of the camera - * @returns {number} camera clear depth - */ - getDepth() { - return this._depth; - } - - /** - * Set the clear depth of the camera - * @param {number} depth camera clear depth - */ - setDepth(depth) { - this._depth = depth; - } - - /** - * Get the clearing stencil value of the camera - * @returns {number} camera clearing stencil value - */ - getStencil() { - return this._stencil; - } - - /** - * Set the clearing stencil value of the camera - * @param {number} stencil camera clearing stencil value - */ - setStencil(stencil) { - this._stencil = stencil; - } - - /** - * Get the clearing flags of the camera - * @returns {number} camera clearing flags - */ - getClearFlags() { - return this._clearFlags; - } - - /** - * Set the clearing flags of the camera - * @param {number} flags camera clearing flags - */ - setClearFlags(flags) { - this._clearFlags = flags; - } - - /** - * Get the rect of the camera - * @param {Object} out the receiving object - * @returns {Object} camera rect - */ - getRect(out) { - out.x = this._rect.x; - out.y = this._rect.y; - out.w = this._rect.w; - out.h = this._rect.h; - - return out; - } - - /** - * Set the rect of the camera - * @param {Number} x - [0,1] - * @param {Number} y - [0,1] - * @param {Number} w - [0,1] - * @param {Number} h - [0,1] - */ - setRect(x, y, w, h) { - this._rect.x = x; - this._rect.y = y; - this._rect.w = w; - this._rect.h = h; - } - - /** - * Get the stages of the camera - * @returns {string[]} camera stages - */ - getStages() { - return this._stages; - } - - /** - * Set the stages of the camera - * @param {number} stages camera stages - */ - setStages(stages) { - this._stages = stages; - } - - /** - * Get the framebuffer of the camera - * @returns {FrameBuffer} camera framebuffer - */ - getFramebuffer() { - return this._framebuffer; - } - - /** - * Set the framebuffer of the camera - * @param {FrameBuffer} framebuffer camera framebuffer - */ - setFramebuffer(framebuffer) { - this._framebuffer = framebuffer; - } - - _calcMatrices(width, height) { - // view matrix - this._node.getWorldRT(_matView); - mat4.invert(_matView, _matView); - - // projection matrix - let aspect = width / height; - if (this._projection === enums.PROJ_PERSPECTIVE) { - mat4.perspective(_matProj, - this._fov, - aspect, - this._near, - this._far - ); - } else { - let x = this._orthoHeight * aspect; - let y = this._orthoHeight; - mat4.ortho(_matProj, - -x, x, -y, y, this._near, this._far - ); - } - - // view-projection - mat4.mul(_matViewProj, _matProj, _matView); - // inv view-projection - mat4.invert(_matInvViewProj, _matViewProj); - } - - /** - * extract a view of this camera - * @param {View} out the receiving view - * @param {number} width framebuffer width - * @param {number} height framebuffer height - */ - extractView(out, width, height) { - if (this._framebuffer) { - width = this._framebuffer._width; - height = this._framebuffer._height; - } - - // priority - out._priority = this._priority; - - // rect - out._rect.x = this._rect.x * width; - out._rect.y = this._rect.y * height; - out._rect.w = this._rect.w * width; - out._rect.h = this._rect.h * height; - - // clear opts - out._color = this._color; - out._depth = this._depth; - out._stencil = this._stencil; - out._clearFlags = this._clearFlags; - out._clearModel = this._clearModel; - - // stages & framebuffer - out._stages = this._stages; - out._framebuffer = this._framebuffer; - - this._calcMatrices(width, height); - mat4.copy(out._matView, _matView); - mat4.copy(out._matProj, _matProj); - mat4.copy(out._matViewProj, _matViewProj); - mat4.copy(out._matInvViewProj, _matInvViewProj); - - // update view's frustum - out._frustum.update(_matViewProj, _matInvViewProj); - } - - /** - * transform a screen position to a world space ray - * @param {number} x the screen x position to be transformed - * @param {number} y the screen y position to be transformed - * @param {number} width framebuffer width - * @param {number} height framebuffer height - * @param {ray} out the resulting ray - * @returns {Ray} the resulting ray - */ - screenPointToRay(x, y, width, height, out) { - out = out || ray.create(); - this._calcMatrices(width, height); - - let cx = this._rect.x * width; - let cy = this._rect.y * height; - let cw = this._rect.w * width; - let ch = this._rect.h * height; - - // far plane intersection - vec3.set(_tmp2_v3, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, 1); - vec3.transformMat4(_tmp2_v3, _tmp2_v3, _matInvViewProj); - - if (this._projection === enums.PROJ_PERSPECTIVE) { - // camera origin - this._node.getWorldPosition(_tmp_v3); - } else { - // near plane intersection - vec3.set(_tmp_v3, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); - vec3.transformMat4(_tmp_v3, _tmp_v3, _matInvViewProj); - } - - return ray.fromPoints(out, _tmp_v3, _tmp2_v3); - } - - /** - * transform a screen position to world space - * @param {vec3} out the resulting vector - * @param {vec3} screenPos the screen position to be transformed - * @param {number} width framebuffer width - * @param {number} height framebuffer height - * @returns {vec3} the resulting vector - */ - screenToWorld(out, screenPos, width, height) { - this._calcMatrices(width, height); - - let cx = this._rect.x * width; - let cy = this._rect.y * height; - let cw = this._rect.w * width; - let ch = this._rect.h * height; - - if (this._projection === enums.PROJ_PERSPECTIVE) { - // calculate screen pos in far clip plane - vec3.set(out, - (screenPos.x - cx) / cw * 2 - 1, - (screenPos.y - cy) / ch * 2 - 1, - 1.0 - ); - - // transform to world - vec3.transformMat4(out, out, _matInvViewProj); - - // lerp to depth z - this._node.getWorldPosition(_tmp_v3); - - vec3.lerp(out, _tmp_v3, out, lerp(this._near / this._far, 1, screenPos.z)); - } else { - vec3.set(out, - (screenPos.x - cx) / cw * 2 - 1, - (screenPos.y - cy) / ch * 2 - 1, - screenPos.z * 2 - 1 - ); - - // transform to world - vec3.transformMat4(out, out, _matInvViewProj); - } - - return out; - } - - /** - * transform a world space position to screen space - * @param {vec3} out the resulting vector - * @param {vec3} worldPos the world space position to be transformed - * @param {number} width framebuffer width - * @param {number} height framebuffer height - * @returns {vec3} the resulting vector - */ - worldToScreen(out, worldPos, width, height) { - this._calcMatrices(width, height); - - let cx = this._rect.x * width; - let cy = this._rect.y * height; - let cw = this._rect.w * width; - let ch = this._rect.h * height; - - vec3.transformMat4(out, worldPos, _matViewProj); - out.x = cx + (out.x + 1) * 0.5 * cw; - out.y = cy + (out.y + 1) * 0.5 * ch; - out.z = out.z * 0.5 + 0.5; - - return out; - } -} diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts new file mode 100644 index 0000000000..31698dab1d --- /dev/null +++ b/cocos/renderer/scene/camera.ts @@ -0,0 +1,379 @@ +import { frustum, ray } from '../../3d/geom-utils'; +import { Color, Mat4, Rect, Vec3 } from '../../core/value-types'; +import { color4, lerp, mat4, toRadian, vec3 } from '../../core/vmath'; +import { GFXClearFlag, IGFXColor } from '../../gfx/define'; +import { RenderView, RenderViewPriority } from '../../pipeline/render-view'; +import { Node } from '../../scene-graph/node'; +import { RenderScene } from './render-scene'; + +export enum CameraProjection { + ORTHO, + PERSPECTIVE, +} + +export interface ICameraInfo { + name: string; + node: Node; + projection: number; + fov: number; + orthoHeight: number; + near: number; + far: number; + color: Color; + depth: number; + stencil: number; + clearFlags: GFXClearFlag; + rect: Rect; + targetDisplay: number; + isUI?: boolean; +} + +const v_a = cc.v3(); +const v_b = cc.v3(); + +export class Camera { + + private _scene: RenderScene; + private _name: string; + private _proj: CameraProjection; + private _isWindowSize: boolean = true; + private _width: number; + private _height: number; + private _aspect: number; + private _orthoHeight: number; + private _fov: number; + private _nearClip: number; + private _farClip: number; + private _clearStencil: number; + private _clearDepth: number; + private _clearFlag: GFXClearFlag; + private _clearColor: IGFXColor = {r: 0, g: 0, b: 0, a: 0}; + private _viewport: Rect = new Rect(0, 0, 1, 1); + private _matView: Mat4 = new Mat4(); + private _matProj: Mat4 = new Mat4(); + private _matViewProj: Mat4 = new Mat4(); + private _matViewProjInv: Mat4 = new Mat4(); + private _frustum: frustum = new frustum(); + private _forward: Vec3 = new Vec3(); + private _position: Vec3 = new Vec3(); + private _node: Node | null = null; + private _view: RenderView; + private _visibility: number = 0; + + constructor (scene: RenderScene, info: ICameraInfo) { + this._scene = scene; + this._name = info.name; + this._node = info.node; + this._proj = info.projection; + this._fov = toRadian(info.fov); + this._orthoHeight = info.orthoHeight; + this._nearClip = info.near; + this._farClip = info.far; + this._viewport = info.rect; + + const c = info.color; + color4.set(this._clearColor, c.r / 255, c.g / 255, c.b / 255, c.a / 255); + this._clearDepth = info.depth; + this._clearStencil = info.stencil; + this._clearFlag = info.clearFlags; + + this._aspect = this._width = this._height = 1; + + this._view = scene.root.createView({ + camera: this, + name: this._name, + priority: RenderViewPriority.GENERAL, + isUI: (info.isUI !== undefined? info.isUI : false), + }); + + this.changeTargetDisplay(info.targetDisplay); + } + + public resize (width: number, height: number) { + this._width = width; + this._height = height; + this._aspect = this._width / this._height; + } + + public setFixedSize (width: number, height: number) { + this._width = width; + this._height = height; + this._aspect = this._width / this._height; + this._isWindowSize = false; + } + + public update () { + if (!this._node) { + return; + } + + // view matrix + this.node.getWorldRT(this._matView); + mat4.invert(this._matView, this._matView); + + // projection matrix + if (this._proj === CameraProjection.PERSPECTIVE) { + mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip); + } else { + const x = this._orthoHeight * this._aspect; + const y = this._orthoHeight; + mat4.ortho(this._matProj, -x, x, -y, y, this._nearClip, this._farClip); + } + + // view-projection + mat4.mul(this._matViewProj, this._matProj, this._matView); + mat4.invert(this._matViewProjInv, this._matViewProj); + + vec3.set( + this._forward, + -this._matView.m02, + -this._matView.m06, + -this._matView.m10, + ); + this._node.getWorldPosition(this._position); + + this._frustum.update(this._matViewProj, this._matViewProjInv); + } + + get view (): RenderView { + return this._view; + } + + set node (val: Node) { + this._node = val; + } + + get node (): Node { + return this._node!; + } + + get isWindowSize (): boolean { + return this._isWindowSize; + } + + set orthoHeight (val) { + this._orthoHeight = val; + } + + get orthoHeight () { + return this._orthoHeight; + } + + set projectionType (val) { + this._proj = val; + } + + get projectionType () { + return this._proj; + } + + set viewport (v) { + this._viewport = v; + } + + get viewport () { + return this._viewport; + } + + set fov (fov) { + this._fov = fov; + } + + get fov () { + return this._fov; + } + + set nearClip (nearClip) { + this._nearClip = nearClip; + } + + get nearClip () { + return this._nearClip; + } + + set farClip (farClip) { + this._farClip = farClip; + } + + get farClip () { + return this._farClip; + } + + set clearColor (val) { + this._clearColor = val; + } + + get clearColor () { + return this._clearColor; + } + + set clearDepth (val) { + this._clearDepth = val; + } + + get clearDepth () { + return this._clearDepth; + } + + set clearStencil (val) { + this._clearStencil = val; + } + + get clearStencil () { + return this._clearStencil; + } + + set clearFlag (val) { + this._clearFlag = val; + } + + get clearFlag () { + return this._clearFlag; + } + + get scene () { + return this._scene; + } + + get name () { + return this._name; + } + + get width () { + return this._width; + } + + get height () { + return this._height; + } + + get aspect () { + return this._aspect; + } + + get matView () { + return this._matView; + } + + get matProj () { + return this._matProj; + } + + get matViewProj () { + return this._matViewProj; + } + + get matViewProjInv () { + return this._matViewProjInv; + } + + get frustum () { + return this._frustum; + } + + get forward () { + return this._forward; + } + + get position () { + return this._position; + } + + set visibility (vis) { + this._visibility = vis; + } + get visibility () { + return this._visibility; + } + + public changeTargetDisplay (val: number) { + const scene = this._scene; + const win = scene.root.windows[val] || scene.root.mainWindow; + if (win) { + this._width = win.width; + this._height = win.height; + this._view.window = win; + } + this._aspect = this._width / this._height; + } + + /** + * transform a screen position to a world space ray + */ + public screenPointToRay (out: ray, x: number, y: number): ray { + const cx = this._viewport.x * this._width; + const cy = this._viewport.y * this._height; + const cw = this._viewport.width * this._width; + const ch = this._viewport.height * this._height; + + // far plane intersection + vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, 1); + vec3.transformMat4(v_a, v_a, this._matViewProjInv); + + if (this._proj === CameraProjection.PERSPECTIVE) { + // camera origin + if (this._node) { this._node.getWorldPosition(v_b); } + } else { + // near plane intersection + vec3.set(v_b, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); + vec3.transformMat4(v_b, v_b, this._matViewProjInv); + } + + return ray.fromPoints(out, v_b, v_a); + } + + /** + * transform a screen position to world space + */ + public screenToWorld (out: vec3, screenPos: vec3): vec3 { + const cx = this._viewport.x * this._width; + const cy = this._viewport.y * this._height; + const cw = this._viewport.width * this._width; + const ch = this._viewport.height * this._height; + + if (this._proj === CameraProjection.PERSPECTIVE) { + // calculate screen pos in far clip plane + vec3.set(out, + (screenPos.x - cx) / cw * 2 - 1, + (screenPos.y - cy) / ch * 2 - 1, + 1.0, + ); + + // transform to world + vec3.transformMat4(out, out, this._matViewProjInv); + + // lerp to depth z + if (this._node) { this._node.getWorldPosition(v_a); } + + vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z)); + } else { + vec3.set(out, + (screenPos.x - cx) / cw * 2 - 1, + (screenPos.y - cy) / ch * 2 - 1, + screenPos.z * 2 - 1, + ); + + // transform to world + vec3.transformMat4(out, out, this.matViewProjInv); + } + + return out; + } + + /** + * transform a world space position to screen space + */ + public worldToScreen (out: vec3, worldPos: vec3): vec3 { + const cx = this._viewport.x * this._width; + const cy = this._viewport.y * this._height; + const cw = this._viewport.width * this._width; + const ch = this._viewport.height * this._height; + + vec3.transformMat4(out, worldPos, this.matViewProj); + out.x = cx + (out.x + 1) * 0.5 * cw; + out.y = cy + (out.y + 1) * 0.5 * ch; + out.z = out.z * 0.5 + 0.5; + + return out; + } +} diff --git a/cocos/renderer/scene/directional-light.ts b/cocos/renderer/scene/directional-light.ts new file mode 100644 index 0000000000..4b254c3b4e --- /dev/null +++ b/cocos/renderer/scene/directional-light.ts @@ -0,0 +1,29 @@ +import { Vec3, Quat } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { Light, LightType } from './light'; +import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; + +const _forward = new Vec3(0, 0, -1); +const _v3 = new Vec3(); +const _qt = new Quat(); + +export class DirectionalLight extends Light { + protected _direction = Float32Array.from([0, 0, 1, 0]); + + set direction (val: Vec3) { + vec3.array(this._direction, val); + } + get directionArray () { + return this._direction; + } + + constructor (scene: RenderScene, node: Node, name: string) { + super(scene, node, name); + this._type = LightType.DIRECTIONAL; + } + + public update () { + this.direction = vec3.transformQuat(_v3, _forward, this._node.getWorldRotation(_qt)); + } +} diff --git a/cocos/renderer/scene/light.js b/cocos/renderer/scene/light.js deleted file mode 100644 index 2fe1e5070f..0000000000 --- a/cocos/renderer/scene/light.js +++ /dev/null @@ -1,499 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { color3, color4, mat4, mat3, vec3, toRadian } from '../../core/vmath'; -import gfx from '../gfx'; - -import enums from '../enums'; - -const _forward = vec3.create(0, 0, -1); - -let _m4_tmp = mat4.create(); -let _m3_tmp = mat3.create(); -let _transformedLightDirection = vec3.create(0, 0, 0); - -// compute light viewProjMat for shadow. -function _computeSpotLightViewProjMatrix(light, outView, outProj) { - // view matrix - light._node.getWorldRT(outView); - mat4.invert(outView, outView); - - // proj matrix - mat4.perspective(outProj, light._spotAngle * light._spotAngleScale, 1, light._shadowMinDepth, light._shadowMaxDepth); -} - -function _computeDirectionalLightViewProjMatrix(light, outView, outProj) { - // view matrix - light._node.getWorldRT(outView); - mat4.invert(outView, outView); - - // TODO: should compute directional light frustum based on rendered meshes in scene. - // proj matrix - let halfSize = light._shadowFrustumSize / 2; - mat4.ortho(outProj, -halfSize, halfSize, -halfSize, halfSize, light._shadowMinDepth, light._shadowMaxDepth); -} - -function _computePointLightViewProjMatrix(light, outView, outProj) { - // view matrix - light._node.getWorldRT(outView); - mat4.invert(outView, outView); - - // The transformation from Cartesian to polar coordinates is not a linear function, - // so it cannot be achieved by means of a fixed matrix multiplication. - // Here we just use a nearly 180 degree perspective matrix instead. - mat4.perspective(outProj, toRadian(179), 1, light._shadowMinDepth, light._shadowMaxDepth); -} - -/** - * A representation of a light source. - * Could be a point light, a spot light or a directional light. - */ -export default class Light { - /** - * Setup a default directional light with no shadows - */ - constructor() { - this._poolID = -1; - this._node = null; - - this._type = enums.LIGHT_DIRECTIONAL; - - this._color = color3.create(1, 1, 1); - this._clearColor = color4.create(1, 1, 1, 1); - this._intensity = 1; - - // used for spot and point light - this._range = 1; - // used for spot light, default to 60 degrees - this._spotAngle = toRadian(60); - this._spotExp = 1; - // cached for uniform - this._directionUniform = new Float32Array(3); - this._positionUniform = new Float32Array(3); - this._colorUniform = new Float32Array([this._color.r * this._intensity, this._color.g * this._intensity, this._color.b * this._intensity]); - this._spotUniform = new Float32Array([Math.cos(this._spotAngle * 0.5), this._spotExp]); - - // shadow params - this._shadowType = enums.SHADOW_NONE; - this._shadowFrameBuffer = null; - this._shadowMap = null; - this._shadowMapDirty = false; - this._shadowDepthBuffer = null; - this._shadowResolution = 1024; - this._shadowBias = 0.0005; - this._shadowDarkness = 1; - this._shadowMinDepth = 1; - this._shadowMaxDepth = 1000; - this._shadowDepthScale = 50; // maybe need to change it if the distance between shadowMaxDepth and shadowMinDepth is small. - this._frustumEdgeFalloff = 0; // used by directional and spot light. - this._viewProjMatrix = mat4.create(); - this._spotAngleScale = 1; // used for spot light. - this._shadowFrustumSize = 50; // used for directional light. - } - - /** - * Get the hosting node of this camera - * @returns {Node} the hosting node - */ - getNode() { - return this._node; - } - - /** - * Set the hosting node of this camera - * @param {Node} node the hosting node - */ - setNode(node) { - this._node = node; - } - - /** - * set the color of the light source - * @param {number} r red channel of the light color - * @param {number} g green channel of the light color - * @param {number} b blue channel of the light color - */ - setColor(r, g, b) { - color3.set(this._color, r, g, b); - this._colorUniform[0] = r * this._intensity; - this._colorUniform[1] = g * this._intensity; - this._colorUniform[2] = b * this._intensity; - } - - /** - * get the color of the light source - * @returns {color3} the light color - */ - get color() { - return this._color; - } - - /** - * set the intensity of the light source - * @param {number} val the light intensity - */ - setIntensity(val) { - this._intensity = val; - this._colorUniform[0] = val * this._color.r; - this._colorUniform[1] = val * this._color.g; - this._colorUniform[2] = val * this._color.b; - } - - /** - * get the intensity of the light source - * @returns {number} the light intensity - */ - get intensity() { - return this._intensity; - } - - /** - * set the type of the light source - * @param {number} type light source type - */ - setType(type) { - this._type = type; - } - - /** - * get the type of the light source - * @returns {number} light source type - */ - get type() { - return this._type; - } - - /** - * set the spot light angle - * @param {number} val spot light angle - */ - setSpotAngle(val) { - this._spotAngle = val; - this._spotUniform[0] = Math.cos(this._spotAngle * 0.5); - } - - /** - * get the spot light angle - * @returns {number} spot light angle - */ - get spotAngle() { - return this._spotAngle; - } - - /** - * set the spot light exponential - * @param {number} val spot light exponential - */ - setSpotExp(val) { - this._spotExp = val; - this._spotUniform[1] = val; - } - - /** - * get the spot light exponential - * @returns {number} spot light exponential - */ - get spotExp() { - return this._spotExp; - } - - /** - * set the range of the light source - * @param {number} val light source range - */ - setRange(val) { - this._range = val; - } - - /** - * get the range of the light source - * @returns {number} range of the light source - */ - get range() { - return this._range; - } - - /** - * set the shadow type of the light source - * @param {number} type light source shadow type - */ - setShadowType(type) { - if (this._shadowType === enums.SHADOW_NONE && type !== enums.SHADOW_NONE) { - this._shadowMapDirty = true; - } - this._shadowType = type; - } - - /** - * get the shadow type of the light source - * @returns {number} light source shadow type - */ - get shadowType() { - return this._shadowType; - } - - /** - * get the shadowmap of the light source - * @returns {Texture2D} light source shadowmap - */ - get shadowMap() { - return this._shadowMap; - } - - /** - * get the view-projection matrix of the light source - * @returns {mat4} light source view-projection matrix - */ - get viewProjMatrix() { - return this._viewProjMatrix; - } - - /** - * set the shadow resolution of the light source - * @param {number} val light source shadow resolution - */ - setShadowResolution(val) { - if (this._shadowResolution !== val) { - this._shadowMapDirty = true; - } - this._shadowResolution = val; - } - - /** - * get the shadow resolution of the light source - * @returns {number} light source shadow resolution - */ - get shadowResolution() { - return this._shadowResolution; - } - - /** - * set the shadow bias of the light source - * @param {number} val light source shadow bias - */ - setShadowBias(val) { - this._shadowBias = val; - } - - /** - * get the shadow bias of the light source - * @returns {number} light source shadow bias - */ - get shadowBias() { - return this._shadowBias; - } - - /** - * set the shadow darkness of the light source - * @param {number} val light source shadow darkness - */ - setShadowDarkness(val) { - this._shadowDarkness = val; - } - - /** - * get the shadow darkness of the light source - * @returns {number} light source shadow darkness - */ - get shadowDarkness() { - return this._shadowDarkness; - } - - /** - * set the shadow min depth of the light source - * @param {number} val light source shadow min depth - */ - setShadowMinDepth(val) { - this._shadowMinDepth = val; - } - - /** - * get the shadow min depth of the light source - * @returns {number} light source shadow min depth - */ - get shadowMinDepth() { - if (this._type === enums.LIGHT_DIRECTIONAL) { - return 1.0; - } - return this._shadowMinDepth; - } - - /** - * set the shadow max depth of the light source - * @param {number} val light source shadow max depth - */ - setShadowMaxDepth(val) { - this._shadowMaxDepth = val; - } - - /** - * get the shadow max depth of the light source - * @returns {number} light source shadow max depth - */ - get shadowMaxDepth() { - if (this._type === enums.LIGHT_DIRECTIONAL) { - return 1.0; - } - return this._shadowMaxDepth; - } - - /** - * set the shadow depth scale of the light source - * @param {number} val light source shadow depth scale - */ - setShadowDepthScale(val) { - this._shadowDepthScale = val; - } - - /** - * get the shadow depth scale of the light source - * @returns {number} light source shadow depth scale - */ - get shadowDepthScale() { - return this._shadowDepthScale; - } - - /** - * set the frustum edge falloff of the light source - * @param {number} val light source frustum edge falloff - */ - setFrustumEdgeFalloff(val) { - this._frustumEdgeFalloff = val; - } - - /** - * get the frustum edge falloff of the light source - * @returns {number} light source frustum edge falloff - */ - get frustumEdgeFalloff() { - return this._frustumEdgeFalloff; - } - - /** - * set the shadow frustum size of the light source - * @param {number} val light source shadow frustum size - */ - setShadowFrustumSize(val) { - this._shadowFrustumSize = val; - } - - /** - * get the shadow frustum size of the light source - * @returns {number} light source shadow frustum size - */ - get shadowFrustumSize() { - return this._shadowFrustumSize; - } - - /** - * extract a view of this light source - * @param {View} out the receiving view - * @param {string[]} stages the stages using the view - */ - extractView(out, stages) { - // TODO: view should not handle light. - out._shadowLight = this; - - // priority. TODO: use varying value for shadow view? - out._priority = -1; - - // rect - out._rect.x = 0; - out._rect.y = 0; - out._rect.w = this._shadowResolution; - out._rect.h = this._shadowResolution; - - // clear opts - out._color = this._clearColor; - out._depth = 1; - out._stencil = 1; - out._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; - - // stages & framebuffer - out._stages = stages; - out._framebuffer = this._shadowFrameBuffer; - - // view projection matrix - switch(this._type) { - case enums.LIGHT_SPOT: - _computeSpotLightViewProjMatrix(this, out._matView, out._matProj); - break; - - case enums.LIGHT_DIRECTIONAL: - _computeDirectionalLightViewProjMatrix(this, out._matView, out._matProj); - break; - - case enums.LIGHT_POINT: - _computePointLightViewProjMatrix(this, out._matView, out._matProj); - break; - - default: - console.warn('shadow of this light type is not supported'); - } - - // view-projection - mat4.mul(out._matViewProj, out._matProj, out._matView); - this._viewProjMatrix = out._matViewProj; - mat4.invert(out._matInvViewProj, out._matViewProj); - - // update view's frustum - out._frustum.update(out._matViewProj, out._matInvViewProj); - } - - _updateLightPositionAndDirection() { - this._node.getWorldMatrix(_m4_tmp); - mat3.fromMat4(_m3_tmp, _m4_tmp); - vec3.transformMat3(_transformedLightDirection, _forward, _m3_tmp); - vec3.array(this._directionUniform, _transformedLightDirection); - let pos = this._positionUniform; - pos[0] = _m4_tmp.m12; - pos[1] = _m4_tmp.m13; - pos[2] = _m4_tmp.m14; - } - - _generateShadowMap(device) { - this._shadowMap = new gfx.Texture2D(device, { - width: this._shadowResolution, - height: this._shadowResolution, - format: gfx.TEXTURE_FMT_RGBA8, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - }); - this._shadowDepthBuffer = new gfx.RenderBuffer(device, - gfx.RB_FMT_D16, - this._shadowResolution, - this._shadowResolution - ); - this._shadowFrameBuffer = new gfx.FrameBuffer(device, this._shadowResolution, this._shadowResolution, { - colors: [this._shadowMap], - depth: this._shadowDepthBuffer, - }); - } - - _destroyShadowMap() { - if (this._shadowMap) { - this._shadowMap.destroy(); - this._shadowDepthBuffer.destroy(); - this._shadowFrameBuffer.destroy(); - this._shadowMap = null; - this._shadowDepthBuffer = null; - this._shadowFrameBuffer = null; - } - } - - /** - * update the light source - * @param {Device} device the rendering device - */ - update(device) { - this._updateLightPositionAndDirection(); - - if (this._shadowType === enums.SHADOW_NONE) { - this._destroyShadowMap(); - } else if (this._shadowMapDirty) { - this._destroyShadowMap(); - this._generateShadowMap(device); - this._shadowMapDirty = false; - } - - } -} diff --git a/cocos/renderer/scene/light.ts b/cocos/renderer/scene/light.ts new file mode 100644 index 0000000000..a8678cce03 --- /dev/null +++ b/cocos/renderer/scene/light.ts @@ -0,0 +1,48 @@ +import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; + +export enum LightType { + DIRECTIONAL, + POINT, + SPOT, + UNKNOWN, +} + +export class Light { + protected _color = Float32Array.from([1, 1, 1, 1]); + protected _enabled = false; + protected _scene: RenderScene; + protected _node: Node; + protected _type: LightType; + protected _name: string; + + set enabled (val) { + this._enabled = val; + } + get enabled () { + return this._enabled; + } + + set color (val: number[]) { + this._color.set(val); + } + get colorData () { + return this._color; + } + + get type (): LightType { + return this._type; + } + get name (): string { + return this._name; + } + + public update () {} + + constructor (scene: RenderScene, node: Node, name: string) { + this._scene = scene; + this._node = node; + this._name = name; + this._type = LightType.UNKNOWN; + } +} diff --git a/cocos/renderer/scene/model.js b/cocos/renderer/scene/model.js deleted file mode 100644 index 91aef6f362..0000000000 --- a/cocos/renderer/scene/model.js +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { aabb } from '../../3d/geom-utils'; - -/** - * A representation of a model - */ -export default class Model { - /** - * Setup a default empty model - */ - constructor() { - this._type = 'default'; - this._poolID = -1; - this._node = null; - this._inputAssembler = null; - this._effect = null; - this._defines = {}; - this._dependencies = {}; - this._viewID = -1; - this._cameraID = -1; - this._userKey = -1; - this._castShadow = false; - this._boundingShape = null; - } - - _updateTransform() { - if (!this._node._hasChanged || !this._boundingShape) return; - this._node.updateWorldTransformFull(); - this._bsModelSpace.transform(this._node._mat, this._node._pos, - this._node._rot, this._node._scale, this._boundingShape); - } - - /** - * Create the bounding shape of this model - * @param {vec3} minPos the min position of the model - * @param {vec3} maxPos the max position of the model - */ - createBoundingShape(minPos, maxPos) { - if (!minPos || !maxPos) return; - this._bsModelSpace = aabb.fromPoints(aabb.create(), minPos, maxPos); - this._boundingShape = aabb.clone(this._bsModelSpace); - } - - /** - * Get the hosting node of this camera - * @returns {Node} the hosting node - */ - getNode() { - return this._node; - } - - /** - * Set the hosting node of this model - * @param {Node} node the hosting node - */ - setNode(node) { - this._node = node; - } - - /** - * Set the input assembler - * @param {InputAssembler} ia - */ - setInputAssembler(ia) { - this._inputAssembler = ia; - } - - /** - * Set the model effect - * @param {?Effect} effect the effect to use - */ - setEffect(effect) { - if (effect) { - this._effect = effect; - this._defines = effect.extractDefines(Object.create(null)); - this._dependencies = effect.extractDependencies(Object.create(null)); - } else { - this._effect = null; - this._defines = Object.create(null); - this._dependencies = Object.create(null); - } - } - - /** - * Set the user key - * @param {number} key - */ - setUserKey(key) { - this._userKey = key; - } - - /** - * Extract a drawing item - * @param {Object} out the receiving item - */ - extractDrawItem(out) { - out.model = this; - out.node = this._node; - out.ia = this._inputAssembler; - out.effect = this._effect; - out.defines = this._effect ? this._effect.extractDefines(this._defines) : this._defines; - out.dependencies = this._effect ? this._effect.extractDependencies(this._dependencies) : this._dependencies; - } -} diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts new file mode 100644 index 0000000000..6dec210677 --- /dev/null +++ b/cocos/renderer/scene/model.ts @@ -0,0 +1,280 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import { Material } from '../../3d/assets/material'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; +import { aabb } from '../../3d/geom-utils'; +import { RecyclePool } from '../../3d/memop'; +import { Vec3 } from '../../core/value-types'; +import { mat4 } from '../../core/vmath'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { UBOLocal } from '../../pipeline/render-pipeline'; +import { Node } from '../../scene-graph/node'; +import { RenderScene } from './render-scene'; +import { SubModel } from './submodel'; + +const _temp_floatx16 = new Float32Array(16); +const _temp_mat4 = mat4.create(); + +const _subMeshPool = new RecyclePool(() => { + return new SubModel(); +}, 32); + +/** + * A representation of a model + */ +export class Model { + + protected _type: string = 'default'; + protected _device: GFXDevice; + private _scene: RenderScene; + private _node: Node; + private _id: number; + private _isEnable: boolean = false; + private _viewID: number = -1; + private _cameraID: number = -1; + private _userKey: number = -1; + private _worldBounds: aabb | null = null; + private _modelBounds: aabb | null = null; + private _subModels: SubModel[] = []; + private _matPSORecord: Map; + private _matRefCount: Map; + private _uboLocal: UBOLocal; + private _localUBO: GFXBuffer | null; + + /** + * Setup a default empty model + */ + constructor (scene: RenderScene, node: Node) { + this._device = cc.director.root.device; + this._scene = scene; + this._node = node; + this._id = this._scene.generateModelId(); + + this._matPSORecord = new Map(); + this._matRefCount = new Map(); + this._uboLocal = new UBOLocal(); + this._localUBO = null; + } + + public destroy () { + for (const subModel of this._subModels) { + subModel.destroy(); + _subMeshPool.remove(subModel); + } + if (this._localUBO) { + this._localUBO.destroy(); + this._localUBO = null; + } + this._worldBounds = null; + this._modelBounds = null; + this._subModels.splice(0); + this._matPSORecord.clear(); + this._matRefCount.clear(); + } + + set scene (scene: RenderScene) { + this._scene = scene; + this._id = this._scene.generateModelId(); + } + + get scene () { + return this._scene; + } + + get id () { + return this._id; + } + + get subModelNum () { + return this._subModels.length; + } + + public getSubModel (idx: number) { + return this._subModels[idx]; + } + + public _updateTransform () { + if (this._node.hasChanged) { + this._node.updateWorldTransformFull(); + if (this._modelBounds) { + this._modelBounds.transform( + // @ts-ignore + this._node._mat, this._node._pos, this._node._rot, this._node._scale, + this._worldBounds); + } + } + } + + public updateUBOs () { + // @ts-ignore + mat4.array(_temp_floatx16, this._node._mat); + this._uboLocal.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); + // @ts-ignore + mat4.normalMatrix(_temp_mat4, this._node._mat); + mat4.array(_temp_floatx16, _temp_mat4); + this._uboLocal.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); + + if (this._localUBO) { + this._localUBO.update(this._uboLocal.view); + } + + for (const mat of this._matPSORecord.keys()) { + for (const pass of mat.passes) { + pass.update(); + } + for (const pso of this._matPSORecord.get(mat)!) { + pso.pipelineLayout.layouts[0].update(); + } + } + } + + /** + * Create the bounding shape of this model + * @param {vec3} minPos the min position of the model + * @param {vec3} maxPos the max position of the model + */ + public createBoundingShape (minPos?: Vec3, maxPos?: Vec3) { + if (!minPos || !maxPos) { return; } + this._modelBounds = aabb.fromPoints(aabb.create(), minPos, maxPos); + this._worldBounds = aabb.clone(this._modelBounds); + } + + set enabled (isEnable) { + this._isEnable = isEnable; + } + + get enabled () { + return this._isEnable; + } + + /** + * Get the hosting node of this camera + * @returns the hosting node + */ + get node () { + return this._node; + } + + /** + * Set the hosting node of this model + * @param {Node} node the hosting node + */ + set node (node: Node) { + this._node = node; + } + + get worldBounds () { + return this._worldBounds; + } + get modelBounds () { + return this._modelBounds; + } + + get viewID () { + return this._viewID; + } + + public initSubModel (idx: number, subMeshData: IRenderingSubmesh, mat: Material) { + if (this._subModels[idx] == null) { + this._subModels[idx] = _subMeshPool.add(); + } else { + const oldMat = this._subModels[idx].material; + this._subModels[idx].destroy(); + this.releasePSO(oldMat); + } + this.allocatePSO(mat); + this._subModels[idx].initialize(subMeshData, mat, this._matPSORecord.get(mat)!); + } + + public setSubModelMesh (idx: number, subMeshData: IRenderingSubmesh) { + if (this._subModels[idx] == null) { + this._subModels[idx] = _subMeshPool.add(); + } + this._subModels[idx].subMeshData = subMeshData; + } + + public setSubModelMaterial (idx: number, mat: Material | null) { + if (this._subModels[idx] == null) { + return; + } + if (this._subModels[idx].material === mat) { + if (mat) { + this.destroyPipelineState(mat!, this._matPSORecord.get(mat!)!); + this._matPSORecord.set(mat!, this.createPipelineState(mat!)); + } + } else { + if (this._subModels[idx].material) { + this.releasePSO(this._subModels[idx].material!); + } + if (mat) { + this.allocatePSO(mat); + } + } + this._subModels[idx]._psos = mat ? this._matPSORecord.get(mat)! : null; + this._subModels[idx].material = mat; + } + + protected createPipelineState (mat: Material): GFXPipelineState[] { + if (this._localUBO == null) { + this._localUBO = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: UBOLocal.SIZE, + stride: UBOLocal.SIZE, + }); + this._localUBO.update(this._uboLocal.view); + } + const ret = new Array(mat.passes.length); + for (let i = 0; i < ret.length; i++) { + ret[i] = mat.passes[i].createPipelineState()!; + this._onCreatePSO(ret[i]); + } + return ret; + } + + protected destroyPipelineState (mat: Material, pso: GFXPipelineState[]) { + for (let i = 0; i < mat.passes.length; i++) { + mat.passes[i].destroyPipelineState(pso[i]); + } + } + + private allocatePSO (mat: Material) { + if (this._matRefCount.get(mat) == null) { + this._matRefCount.set(mat, 1); + this._matPSORecord.set(mat, this.createPipelineState(mat)); + } else { + this._matRefCount.set(mat, this._matRefCount.get(mat)! + 1); + } + } + + private releasePSO (mat: Material) { + this._matRefCount.set(mat, this._matRefCount.get(mat)! - 1); + if (this._matRefCount.get(mat) === 0) { + this.destroyPipelineState(mat, this._matPSORecord.get(mat)!); + this._matPSORecord.delete(mat); + this._matRefCount.delete(mat); + } + } + + protected _onCreatePSO (pso: GFXPipelineState) { + pso.pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this.localUBO!); + } + + /** + * Set the user key + * @param {number} key + */ + set userKey (key: number) { + this._userKey = key; + } + + get uboLocal () { + return this._uboLocal; + } + + get localUBO () { + return this._localUBO; + } +} diff --git a/cocos/renderer/scene/point-light.ts b/cocos/renderer/scene/point-light.ts new file mode 100644 index 0000000000..a7b52f3c2d --- /dev/null +++ b/cocos/renderer/scene/point-light.ts @@ -0,0 +1,31 @@ +import { Vec3 } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { Light, LightType } from './light'; +import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; + +const _v3 = new Vec3(); + +export class PointLight extends Light { + protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); + + set position (val: Vec3) { + vec3.array(this._positionAndRange, val); + } + set range (val: number) { + this._positionAndRange[3] = val; + } + + get positionAndRange () { + return this._positionAndRange; + } + + constructor (scene: RenderScene, node: Node, name: string) { + super(scene, node, name); + this._type = LightType.POINT; + } + + public update () { + this.position = this._node.getWorldPosition(_v3); + } +} diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts new file mode 100644 index 0000000000..258c907ffc --- /dev/null +++ b/cocos/renderer/scene/render-scene.ts @@ -0,0 +1,299 @@ +import { IBArray } from '../../3d/assets/mesh'; +import { intersect, ray, triangle } from '../../3d/geom-utils'; +import { RecyclePool } from '../../3d/memop'; +import { Root } from '../../core/root'; +import { Mat4, Vec3 } from '../../core/value-types'; +import { mat4, vec3 } from '../../core/vmath'; +import { GFXPrimitiveMode } from '../../gfx/define'; +import { Node } from '../../scene-graph'; +import { Layers } from '../../scene-graph/layers'; +import { Camera, ICameraInfo } from './camera'; +import { DirectionalLight } from './directional-light'; +import { Light } from './light'; +import { Model } from './model'; +import { PointLight } from './point-light'; +import { SpotLight } from './spot-light'; +import { UBOGlobal } from '../../pipeline/render-pipeline'; + +export interface IRenderSceneInfo { + name: string; +} + +export interface ISceneNodeInfo { + name: string; + isStatic?: boolean; + // parent: Node; +} + +export interface IRaycastResult { + node: Node; + distance: number; +} + +export class RenderScene { + + get root (): Root { + return this._root; + } + + get name (): string { + return this._name; + } + + get cameras (): Camera[] { + return this._cameras; + } + + get directionalLights (): DirectionalLight[] { + return this._directionalLights; + } + + get pointLights (): PointLight[] { + return this._pointLights; + } + + get spotLights (): SpotLight[] { + return this._spotLights; + } + + get models (): Model[] { + return this._models; + } + + public static registerCreateFunc (root: Root) { + root._createSceneFun = (_root: Root): RenderScene => new RenderScene(_root); + } + + private _root: Root; + private _name: string = ''; + private _cameras: Camera[] = []; + private _pointLights: PointLight[] = []; + private _directionalLights: DirectionalLight[] = []; + private _spotLights: SpotLight[] = []; + private _models: Model[] = []; + private _modelId: number = 0; + + private constructor (root: Root) { + this._root = root; + } + + public initialize (info: IRenderSceneInfo): boolean { + this._name = info.name; + + return true; + } + + public destroy () { + this.destroyCameras(); + this.destroyPointLights(); + this.destroyModels(); + } + + public createCamera (info: ICameraInfo): Camera { + const camera = new Camera(this, info); + this._cameras.push(camera); + return camera; + } + + public destroyCamera (camera: Camera) { + for (let i = 0; i < this._cameras.length; ++i) { + if (this._cameras[i] === camera) { + this._cameras.splice(i, 1); + return; + } + } + } + + public destroyCameras () { + this._cameras = []; + } + + public getCamera (name: string): Camera | null { + for (const camera of this._cameras) { + if (camera.name === name) { + return camera; + } + } + + return null; + } + + public createPointLight (name: string, node: Node): Light | null { + if (this._pointLights.length >= UBOGlobal.MAX_POINT_LIGHTS) { return null; } + const light = new PointLight(this, node, name); + this._pointLights.push(light); + return light; + } + + public destroyPointLight (light: Light) { + for (let i = 0; i < this._pointLights.length; ++i) { + if (this._pointLights[i] === light) { + this._pointLights.splice(i, 1); + return; + } + } + } + + public createDirectionalLight (name: string, node: Node): Light | null { + if (this._directionalLights.length >= UBOGlobal.MAX_DIR_LIGHTS) { return null; } + const light = new DirectionalLight(this, node, name); + this._directionalLights.push(light); + return light; + } + + public destroyDirectionalLight (light: Light) { + for (let i = 0; i < this._directionalLights.length; ++i) { + if (this._directionalLights[i] === light) { + this._directionalLights.splice(i, 1); + return; + } + } + } + + public createSpotLight (name: string, node: Node): Light | null { + if (this._spotLights.length >= UBOGlobal.MAX_SPOT_LIGHTS) { return null; } + const light = new SpotLight(this, node, name); + this._spotLights.push(light); + return light; + } + + public destroySpotLight (light: Light) { + for (let i = 0; i < this._spotLights.length; ++i) { + if (this._spotLights[i] === light) { + this._spotLights.splice(i, 1); + return; + } + } + } + + public destroyPointLights () { + this._pointLights = []; + } + + public destroyDirectionalLights () { + this._directionalLights = []; + } + + public destroySpotLights () { + this._spotLights = []; + } + + public createModel (clazz: new (scene: RenderScene, node: Node) => T, node: Node): T { + const model = new clazz(this, node); + this._models.push(model); + return model; + } + + public destroyModel (model: Model) { + for (let i = 0; i < this._models.length; ++i) { + if (this._models[i] === model) { + this._models.splice(i, 1)[0].destroy(); + return; + } + } + } + + public destroyModels () { + for (const m of this._models) { + m.destroy(); + } + this._models = []; + } + + public generateModelId (): number { + return this._modelId++; + } + + /** + * Cast a ray into the scene, record all the intersected models in the result array + * @param worldRay - the testing ray + * @param mask - the layer mask to filter the models + * @returns the results array + */ + public raycast (worldRay: ray, mask: number = Layers.RaycastMask): IRaycastResult[] { + pool.reset(); + for (const m of this._models) { + const node = m.node; + if (!m.enabled || !cc.Layers.check(node.layer, mask) || !m.modelBounds) { continue; } + // transform ray back to model space + mat4.invert(m4, node.getWorldMatrix(m4)); + vec3.transformMat4(modelRay.o, worldRay.o, m4); + vec3.normalize(modelRay.d, vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); + // broadphase + distance = intersect.ray_aabb(modelRay, m.modelBounds); + if (distance <= 0) { continue; } + for (let i = 0; i < m.subModelNum; ++i) { + const subModel = m.getSubModel(i).subMeshData; + if (subModel && subModel.geometricInfo) { + const { positions: vb, indices: ib, doubleSided: sides } = subModel.geometricInfo; + narrowphase(vb, ib, subModel.primitiveMode, sides); + } + if (distance < Infinity) { + const r = pool.add(); + r.node = node; + // @ts-ignore + r.distance = distance * vec3.magnitude(vec3.mul(v3, modelRay.d, node._scale)); + results[pool.length - 1] = r; + } + } + } + results.length = pool.length; + return results; + } +} + +const modelRay = ray.create(); +const v3 = new Vec3(); +const m4 = new Mat4(); +let distance = Infinity; +const tri = triangle.create(); +const pool = new RecyclePool(() => { + return { node: null, distance: Infinity }; +}, 8); +const results: IRaycastResult[] = []; + +const narrowphase = (vb: Float32Array, ib: IBArray, pm: GFXPrimitiveMode, sides?: boolean) => { + distance = Infinity; + if (pm === GFXPrimitiveMode.TRIANGLE_LIST) { + const cnt = ib.length; + for (let j = 0; j < cnt; j += 3) { + const i0 = ib[j] * 3; + const i1 = ib[j + 1] * 3; + const i2 = ib[j + 2] * 3; + vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]); + vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); + vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); + const dist = intersect.ray_triangle(modelRay, tri, sides); + if (dist <= 0 || dist > distance) { continue; } + distance = dist; + } + } else if (pm === GFXPrimitiveMode.TRIANGLE_STRIP) { + const cnt = ib.length - 2; + let rev = 0; + for (let j = 0; j < cnt; j += 1) { + const i0 = ib[j - rev] * 3; + const i1 = ib[j + rev + 1] * 3; + const i2 = ib[j + 2] * 3; + vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]); + vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); + vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); + rev = ~rev; + const dist = intersect.ray_triangle(modelRay, tri, sides); + if (dist <= 0 || dist > distance) { continue; } + distance = dist; + } + } else if (pm === GFXPrimitiveMode.TRIANGLE_FAN) { + const cnt = ib.length - 1; + const i0 = ib[0] * 3; + vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]); + for (let j = 1; j < cnt; j += 1) { + const i1 = ib[j] * 3; + const i2 = ib[j + 1] * 3; + vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); + vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); + const dist = intersect.ray_triangle(modelRay, tri, sides); + if (dist <= 0 || dist > distance) { continue; } + distance = dist; + } + } +}; diff --git a/cocos/renderer/scene/scene.js b/cocos/renderer/scene/scene.js deleted file mode 100644 index 8d68d51083..0000000000 --- a/cocos/renderer/scene/scene.js +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { FixedArray, RecyclePool } from '../../3d/memop'; -import { ray, triangle, intersect } from '../../3d/geom-utils'; -import Layers from '../../scene-graph/layers'; -import { vec3, mat4 } from '../../core/vmath'; -import gfx from '../../renderer/gfx'; - -/** - * A representation of the scene - */ -class Scene { - /** - * Setup a default empty scene - */ - constructor() { - this._lights = new FixedArray(16); - this._models = new FixedArray(16); - this._cameras = new FixedArray(16); - this._debugCamera = null; - - // NOTE: we don't use pool for views (because it's less changed and it doesn't have poolID) - this._views = []; - } - - _add(pool, item) { - if (item._poolID !== -1) { - return; - } - - pool.push(item); - item._poolID = pool.length - 1; - } - - _remove(pool, item) { - if (item._poolID === -1) { - return; - } - - pool.data[pool.length-1]._poolID = item._poolID; - pool.fastRemove(item._poolID); - item._poolID = -1; - } - - /** - * update built-in bounding shapes if needed, - * used in the frustum culling process - */ - tick() { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models.data[i]; - model._updateTransform(); - } - } - - /** - * reset the model viewIDs - */ - reset() { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models.data[i]; - model._viewID = -1; - } - } - - /** - * Set the debug camera - * @param {Camera} cam the debug camera - */ - setDebugCamera(cam) { - this._debugCamera = cam; - } - - /** - * Get the debug camera - */ - getDebugCamera() { - return this._debugCamera; - } - - /** - * Get the count of registered cameras - * @returns {number} camera count - */ - getCameraCount() { - return this._cameras.length; - } - - /** - * Get the specified camera - * @param {number} idx camera index - * @returns {Camera} the specified camera - */ - getCamera(idx) { - return this._cameras.data[idx]; - } - - /** - * register a camera - * @param {Camera} camera the new camera - */ - addCamera(camera) { - this._add(this._cameras, camera); - } - - /** - * remove a camera - * @param {Camera} camera the camera to be removed - */ - removeCamera(camera) { - this._remove(this._cameras, camera); - } - - /** - * Get the count of registered model - * @returns {number} model count - */ - getModelCount() { - return this._models.length; - } - - /** - * Get the specified model - * @param {number} idx model index - * @returns {Model} the specified model - */ - getModel(idx) { - return this._models.data[idx]; - } - - /** - * register a model - * @param {Model} model the new model - */ - addModel(model) { - this._add(this._models, model); - } - - /** - * remove a model - * @param {Model} model the model to be removed - */ - removeModel(model) { - this._remove(this._models, model); - } - - /** - * Get the count of registered light - * @returns {number} light count - */ - getLightCount() { - return this._lights.length; - } - - /** - * Get the specified light - * @param {number} idx light index - * @returns {Light} the specified light - */ - getLight(idx) { - return this._lights.data[idx]; - } - - /** - * register a light - * @param {Light} light the new light - */ - addLight(light) { - this._add(this._lights, light); - } - - /** - * remove a light - * @param {Light} light the light to be removed - */ - removeLight(light) { - this._remove(this._lights, light); - } - - /** - * register a view - * @param {View} view the new view - */ - addView(view) { - if (this._views.indexOf(view) === -1) { - this._views.push(view); - } - } - - /** - * remove a view - * @param {View} view the view to be removed - */ - removeView(view) { - let idx = this._views.indexOf(view); - if (idx !== -1) { - this._views.splice(idx, 1); - } - } -} - -if (CC_EDITOR) { - /** - * Cast a ray into the scene, record all the intersected models in the result array - * @param {Ray} worldRay the testing ray - * @param {Object[]} results the results array - * @param {number} mask the layer mask to filter the models - * @return {Object[]} the results array - */ - Scene.prototype.raycast = (function() { - let modelRay = ray.create(); - let v3 = vec3.create(); - let m4 = mat4.create(); - let distance = Infinity; - let tri = triangle.create(); - let pool = new RecyclePool(() => { - return { node: null, distance: Infinity }; - }, 8); - let results = []; - return function(worldRay, mask = Layers.RaycastMask) { - pool.reset(); - for (let i = 0; i < this._models.length; i++) { - let m = this._models.data[i], node = m._node; - if (!cc.Layers.check(node.layer, mask) || !m._bsModelSpace) continue; - // transform ray back to model space - mat4.invert(m4, node.getWorldMatrix(m4)); - vec3.transformMat4(modelRay.o, worldRay.o, m4); - vec3.normalize(modelRay.d, vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); - // broadphase - if ((distance = intersect.ray_aabb(modelRay, m._bsModelSpace)) <= 0) continue; - let ia = m._inputAssembler; - if (ia._primitiveType == gfx.PT_TRIANGLES) { - // narrowphase - distance = Infinity; - let vb = ia._vertexBuffer[gfx.ATTR_POSITION]; - let ib = ia._indexBuffer._data, sides = ia.doubleSided; - for (let j = 0; j < ib.length; j += 3) { - let i0 = ib[j] * 3, i1 = ib[j + 1] * 3, i2 = ib[j + 2] * 3; - vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]); - vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); - vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); - let dist = intersect.ray_triangle(modelRay, tri, sides); - if (dist <= 0 || dist > distance) continue; - distance = dist; - } - } - if (distance < Infinity) { - let r = pool.add(); - r.node = node; - r.distance = distance * vec3.magnitude(vec3.mul(v3, modelRay.d, node._scale)); - results[pool.length - 1] = r; - } - } - results.length = pool.length; - return results; - }; - })(); -} - -export default Scene; diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/renderer/scene/spot-light.ts new file mode 100644 index 0000000000..805f540a9d --- /dev/null +++ b/cocos/renderer/scene/spot-light.ts @@ -0,0 +1,44 @@ +import { Vec3, Quat } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { Light, LightType } from './light'; +import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; + +const _forward = new Vec3(0, 0, -1); +const _v3 = new Vec3(); +const _qt = new Quat(); + +export class SpotLight extends Light { + protected _direction = Float32Array.from([0, 0, 1, Math.cos(Math.PI / 6)]); + protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); + + set position (val: Vec3) { + vec3.array(this._positionAndRange, val); + } + set range (val: number) { + this._positionAndRange[3] = val; + } + set direction (val: Vec3) { + vec3.array(this._direction, val); + } + set spotAngle (val: number) { + this._direction[3] = Math.cos(val * 0.5); + } + + get positionAndRange () { + return this._positionAndRange; + } + get directionArray () { + return this._direction; + } + + constructor (scene: RenderScene, node: Node, name: string) { + super(scene, node, name); + this._type = LightType.DIRECTIONAL; + } + + public update () { + this.position = this._node.getWorldPosition(_v3); + this.direction = vec3.transformQuat(_v3, _forward, this._node.getWorldRotation(_qt)); + } +} diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts new file mode 100644 index 0000000000..ecc5427ff8 --- /dev/null +++ b/cocos/renderer/scene/submodel.ts @@ -0,0 +1,159 @@ +import { Material } from '../../3d/assets/material'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXCommandBufferType, GFXStatus } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../../gfx/input-assembler'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { RenderPriority } from '../../pipeline/define'; +import { Pass } from '../core/pass'; + +export class SubModel { + protected _subMeshObject: IRenderingSubmesh | null; + protected _inputAssembler: GFXInputAssembler | null; + private _material: Material | null; + private _cmdBuffers: GFXCommandBuffer[]; + private _psos: GFXPipelineState[] | null; + private _castShadow: boolean; + private _priority: RenderPriority; + + constructor () { + this._subMeshObject = null; + this._material = null; + this._cmdBuffers = new Array(); + this._psos = null; + this._castShadow = false; + this._inputAssembler = null; + this._priority = RenderPriority.DEFAULT; + } + + public initialize (subMesh: IRenderingSubmesh, mat: Material, psos: GFXPipelineState[]) { + this._psos = psos; + this.subMeshData = subMesh; + + this.material = mat; + } + + public destroy () { + if (this._inputAssembler) { + this._inputAssembler.destroy(); + } + for (let i = 0; i < this.passes.length; i++) { + this.passes[i].destroyPipelineState(this._psos![i]); + } + for (const cmdBuffer of this._cmdBuffers) { + cmdBuffer.destroy(); + } + this._cmdBuffers.splice(0); + } + + set priority (val: RenderPriority) { + this._priority = val; + } + + get priority () { + return this._priority; + } + + set subMeshData (sm: IRenderingSubmesh) { + if (this._inputAssembler) { + this._inputAssembler.destroy(); + } + this._subMeshObject = sm; + const iaInfo = {} as IGFXInputAssemblerInfo; + iaInfo.attributes = this._subMeshObject!.attributes; + iaInfo.vertexBuffers = this._subMeshObject!.vertexBuffers; + if (this._subMeshObject!.indexBuffer) { + iaInfo.indexBuffer = this._subMeshObject!.indexBuffer; + } + if (this._subMeshObject!.indirectBuffer) { + iaInfo.indirectBuffer = this._subMeshObject!.indirectBuffer; + } + if (this._inputAssembler) { + this._inputAssembler.initialize(iaInfo); + } else { + this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(iaInfo); + } + } + + get subMeshData () { + return this._subMeshObject!; + } + + get psos (): GFXPipelineState[] { + return this._psos!; + } + + set psos (val: GFXPipelineState[]) { + this._psos = val; + } + + set material (material: Material | null) { + this._material = material; + if (material == null) { + return; + } + for (let i = 0; i < this._material!.passes.length; i++) { + if (this._material!.passes[i].primitive !== this._subMeshObject!.primitiveMode) { + cc.error(`the model(%d)'s primitive type doesn't match its pass's`, i); + } + this.recordCommandBuffer(i); + } + for (let i = this._cmdBuffers.length - 1; i >= this._material!.passes.length; i--) { + const cmdBuff = this._cmdBuffers.pop(); + if (cmdBuff) { + cmdBuff.destroy(); + } + } + } + + get material (): Material | null { + return this._material!; + } + + get inputAssembler (): GFXInputAssembler | null { + return this._inputAssembler; + } + + get castShadow (): boolean { + return this._castShadow; + } + + set castShadow (val: boolean) { + this._castShadow = val; + } + + private recordCommandBuffer (index: number) { + const device = cc.director.root.device as GFXDevice; + const pso = this._psos![index]; + if (this._cmdBuffers[index] == null) { + const cmdBufferInfo = { + allocator: device.commandAllocator, + type: GFXCommandBufferType.SECONDARY, + }; + this._cmdBuffers[index] = device.createCommandBuffer(cmdBufferInfo); + } else if (this._cmdBuffers[index].status == GFXStatus.UNREADY) { + this._cmdBuffers[index].initialize({ + allocator: device.commandAllocator, + type: GFXCommandBufferType.SECONDARY, + }); + } + const inputAssembler = this._inputAssembler as GFXInputAssembler; + + const cmdBuff = this._cmdBuffers[index]; + cmdBuff.begin(); + cmdBuff.bindPipelineState(pso); + cmdBuff.bindBindingLayout(pso.pipelineLayout.layouts[0]); + cmdBuff.bindInputAssembler(inputAssembler); + cmdBuff.draw(inputAssembler); + cmdBuff.end(); + } + + get passes (): Pass[] { + return this._material!.passes; + } + + get commandBuffers (): GFXCommandBuffer[] { + return this._cmdBuffers; + } +} diff --git a/cocos/renderer/ui/renderData.ts b/cocos/renderer/ui/renderData.ts new file mode 100644 index 0000000000..54a276b740 --- /dev/null +++ b/cocos/renderer/ui/renderData.ts @@ -0,0 +1,103 @@ + +import { Material } from '../../3d/assets/material'; +import RecyclePool from '../../3d/memop/recycle-pool'; +import { Color } from '../../core/value-types'; + +export class IRenderData { + public x: number = 0; + public y: number = 0; + public z: number = 0; + public u: number = 0; + public v: number = 0; + public color: Color = Color.WHITE; +} + +class BaseRenderData { + public material: Material | null = null; + public vertexCount: number = 0; + public indiceCount: number = 0; +} + +export class RenderData extends BaseRenderData { + + get dataLength () { + return this._datas.length; + } + + set dataLength (length: number) { + const data: IRenderData[] = this._datas; + if (data.length !== length) { + // // Free extra data + const value = data.length; + let i = 0; + for (i = value; i < length; i++) { + data[i] = _dataPool.add(); + } + for (i = value; i > length; i--) { + _dataPool.removeAt(i); + data.splice(i, 1); + } + } + } + + get datas () { + return this._datas; + } + + public static add () { + const data = _pool.add(); + return { + pooID: _pool.length - 1, + data, + }; + } + + public static remove (idx: number) { + _pool.data[idx].clear(); + _pool.removeAt(idx); + } + + public uvDirty: boolean = true; + public vertDirty: boolean = true; + private _datas: IRenderData[] = []; + private _indices: number[] = []; + private _pivotX: number = 0; + private _pivotY: number = 0; + private _width: number = 0; + private _height: number = 0; + + public updateSizeNPivot (width: number, height: number, pivotX: number, pivotY: number) { + if (width !== this._width || + height !== this._height || + pivotX !== this._pivotX || + pivotY !== this._pivotY) { + this._width = width; + this._height = height; + this._pivotX = pivotX; + this._pivotY = pivotY; + this.vertDirty = true; + } + } + + public clear () { + this._datas.length = 0; + this._indices.length = 0; + this._pivotX = 0; + this._pivotY = 0; + this._width = 0; + this._height = 0; + this.uvDirty = true; + this.vertDirty = true; + this.material = null; + this.vertexCount = 0; + this.indiceCount = 0; + } +} + +const _dataPool = new RecyclePool(() => { + return new IRenderData(); +}, 128); + +const _pool = new RecyclePool( () => { + return new RenderData(); +}, 32); diff --git a/cocos/renderer/ui/ui-batch-model.ts b/cocos/renderer/ui/ui-batch-model.ts new file mode 100644 index 0000000000..58997c7083 --- /dev/null +++ b/cocos/renderer/ui/ui-batch-model.ts @@ -0,0 +1,5 @@ +import { Model } from '../scene/model'; + +export class UIBatchModel extends Model { + +} diff --git a/cocos/renderer/ui/ui-material.ts b/cocos/renderer/ui/ui-material.ts new file mode 100644 index 0000000000..16ce74833c --- /dev/null +++ b/cocos/renderer/ui/ui-material.ts @@ -0,0 +1,56 @@ +import { Material } from '../../3d/assets/material'; +import { GFXBindingLayout } from '../../gfx/binding-layout'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { Pass } from '../core/pass'; + +export interface IUIMaterialInfo { + material: Material; +} + +export class UIMaterial { + + public get material (): Material { + return this._material!; + } + + public get pass (): Pass { + return this._pass!; + } + + public get pipelineState (): GFXPipelineState { + return this._pipelineState!; + } + + public get bindingLayout (): GFXBindingLayout { + return this._bindingLayout!; + } + + protected _material: Material | null = null; + protected _pass: Pass | null = null; + protected _pipelineState: GFXPipelineState | null = null; + protected _bindingLayout: GFXBindingLayout | null = null; + + constructor () { + } + + public initialize (info: IUIMaterialInfo): boolean { + + if (!info.material) { + return false; + } + + this._material = info.material; + + this._pass = this._material.passes[0]; + this._pipelineState = this._pass.createPipelineState(); + this._bindingLayout = this._pipelineState!.pipelineLayout.layouts[0]; + + return true; + } + + public destroy () { + this._bindingLayout = null; + this._pipelineState = null; + this._material = null; + } +} diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts new file mode 100644 index 0000000000..ce742c549a --- /dev/null +++ b/cocos/renderer/ui/ui.ts @@ -0,0 +1,549 @@ + +import { Material } from '../../3d/assets/material'; +import { builtinResMgr } from '../../3d/builtin'; +import RecyclePool from '../../3d/memop/recycle-pool'; +import { CanvasComponent } from '../../3d/ui/components/canvas-component'; +import { UIRenderComponent } from '../../3d/ui/components/ui-render-component'; +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 { mat4 } from '../../core/vmath'; +import { GFXBindingLayout } from '../../gfx/binding-layout'; +import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { + GFXBufferUsageBit, + GFXCommandBufferType, + GFXFormat, + GFXMemoryUsageBit, + GFXType, + IGFXRect, +} from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { GFXUniformBlock } from '../../gfx/shader'; +import { GFXTextureView } from '../../gfx/texture-view'; +import { vfmt } from '../../gfx/vertex-format-sample'; +import { Camera } from '../scene/camera'; +import { RenderScene } from '../scene/render-scene'; +import { IUIMaterialInfo, UIMaterial } from './ui-material'; +import { Node } from '../../scene-graph/node'; + +export class UBOUI { + public static MAT_VIEW_PROJ_OFFSET: number = 0; + public static COUNT: number = UBOUI.MAT_VIEW_PROJ_OFFSET + 16; + public static SIZE: number = UBOUI.COUNT * 4; + + public static BLOCK: GFXUniformBlock = { + binding: 30, name: 'CCUI', members: [ + { name: 'cc_matViewProj', type: GFXType.MAT4, count: 1 }, + ], + }; + + public view: Float32Array = new Float32Array(UBOUI.COUNT); +} + +const _mat4Array = new Float32Array(16); + +export class UIBufferBatch { + public vf32: Float32Array | null = null; + public vui16: Uint16Array | null = null; + public vb: GFXBuffer | null = null; + public ib: GFXBuffer | null = null; + public ia: GFXInputAssembler | null = null; + public vbSize: number = 0; + public ibSize: number = 0; +} + +export class UIDrawBatch { + public camera: Camera | null = null; + public bufferBatch: UIBufferBatch | null = null; + public uiMaterial: UIMaterial | null = null; + public texView: GFXTextureView | null = null; + public idxCount: number = 0; + + clear() { + this.camera = null; + this.bufferBatch = null; + this.uiMaterial = null; + this.texView = null; + this.idxCount = 0; + } +} + +export interface IUIRenderData { + meshBuffer: MeshBuffer; + material: Material; + texture: SpriteFrame; + priority: number; +} +export interface IUICanvas { + camera: Camera; + datas: IUIRenderData[]; +} + +export class UI { + private _commitUIRenderDataPool: RecyclePool = new RecyclePool(() => { + return new Object() as IUIRenderData; + }, 128); + + private _screens: CanvasComponent[] = []; + private _bufferPool: RecyclePool = new RecyclePool(() => { + return new MeshBuffer(); + }, 128); + private _bufferBatchPool: RecyclePool = new RecyclePool(() => { + return new UIBufferBatch(); + }, 128); + private _drawBatchPool: RecyclePool = new RecyclePool(() => { + return new UIDrawBatch(); + }, 128); + private _device: GFXDevice; + private _cmdBuff: GFXCommandBuffer | null = null; + private _renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 }; + private _scene: RenderScene; + private _attributes: IGFXInputAttribute[] = []; + private _bufferBatches: UIBufferBatch[] = []; + private _uiMaterial: UIMaterial | null = null; + private _uiMaterials: UIMaterial[] = []; + private _uboUI: UBOUI = new UBOUI(); + private _uiUBO: GFXBuffer | null = null; + private _batches: CachedArray; + private _bufferInitData: IMeshBufferInitData | null = null; + private _commitUIRenderDatas: IUIRenderData[] = []; + private _commitUICanvasDatas: IUICanvas[] = []; + private _sortChildList: RecyclePool = new RecyclePool(() => { + return []; + }, 128); + + constructor (private _root: Root) { + this._device = _root.device; + this._scene = this._root.createScene({ + name: 'GUIScene', + }); + + this._batches = new CachedArray(64); + this._bufferInitData = { + vertexCount: 0, + indiceCount: 0, + attributes: vfmt, + }; + } + + public initialize () { + + this._attributes = [ + { name: 'a_color', format: GFXFormat.RGBA32F }, + { name: 'a_position', format: GFXFormat.RGB32F }, + { name: 'a_texCoord', format: GFXFormat.RG32F }, + ]; + + this.createBufferBatch(); + + this._cmdBuff = this._device.createCommandBuffer({ + allocator: this._device.commandAllocator, + type: GFXCommandBufferType.PRIMARY, + }); + + this._uiMaterial = this.createUIMaterial({ material: builtinResMgr.get('sprite-material')}); + + this._uiUBO = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: UBOUI.SIZE, + }); + + return true; + } + + public destroy () { + this.destroyUIMaterials(); + + if (this._uiUBO) { + this._uiUBO.destroy(); + this._uiUBO = null; + } + + for (const buffBatch of this._bufferBatches) { + buffBatch.vb!.destroy(); + buffBatch.ib!.destroy(); + buffBatch.ia!.destroy(); + } + this._bufferBatches.splice(0); + + if (this._cmdBuff) { + this._cmdBuff.destroy(); + this._cmdBuff = null; + } + } + + public createUIMaterial (info: IUIMaterialInfo): UIMaterial | null { + const uiMtrl = new UIMaterial(); + if (uiMtrl.initialize(info)) { + this._uiMaterials.push(uiMtrl); + return uiMtrl; + } else { + return null; + } + } + + public destroyUIMaterial (uiMaterial: UIMaterial) { + for (let i = 0; i < this._uiMaterials.length; ++i) { + if (this._uiMaterials[i] === uiMaterial) { + uiMaterial.destroy(); + this._uiMaterials.splice(i); + return; + } + } + } + + public destroyUIMaterials () { + for (const uiMaterial of this._uiMaterials) { + uiMaterial.destroy(); + } + this._uiMaterials = []; + } + + public addScreen (comp) { + this._screens.push(comp); + } + + public getScreen(visibility: number) { + this._screens.forEach((screen) => { + if (screen.camera) { + if (screen.camera.visibility === visibility) { + return screen; + } + } + }) + return null; + } + + public removeScreen (comp) { + const idx = this._screens.indexOf(comp); + if (idx !== -1) { + this._screens.splice(idx, 1); + } + } + + public createBuffer (vertexCount: number, indiceCount: number) { + const buffer = this._bufferPool.add(); + this._bufferInitData!.vertexCount = vertexCount; + this._bufferInitData!.indiceCount = indiceCount; + buffer.initialize(this._bufferInitData as IMeshBufferInitData); + return buffer; + } + + public createUIRenderData () { + return this._commitUIRenderDataPool.add(); + } + + public addToQueue (uiRenderData: IUIRenderData) { + this._commitUIRenderDatas.push(uiRenderData); + } + + public update (dt: number) { + + for (let i = 0; i < this._batches.length; ++i) { + const batch = this._batches.array[i]; + batch.clear(); + this._drawBatchPool.remove(batch); + } + this._batches.clear(); + + // this._commitUIRenderDatas = []; + + this._renderScreens(); + + // Merge batch + if (this._commitUIRenderDatas.length) { + this.mergeBatches(); + + // update buffers + for (const bufferBatch of this._bufferBatches) { + if (bufferBatch.vbSize > bufferBatch.vb!.size) { + bufferBatch.vb!.resize(bufferBatch.vbSize); + } + bufferBatch.vb!.update(bufferBatch.vf32!); + + if (bufferBatch.ibSize > bufferBatch.ib!.size) { + bufferBatch.ib!.resize(bufferBatch.ibSize); + } + bufferBatch.ib!.update(bufferBatch.vui16!); + } + } + } + + public render () { + + const material = this._uiMaterial!; + + if (this._batches.length) { + const framebuffer = this._root.curWindow!.framebuffer; + const cmdBuff = this._cmdBuff!; + + cmdBuff.begin(); + + let curCamera: Camera | null = null; + + for (let i = 0; i < this._batches.length; ++i) { + const batch = this._batches.array[i]; + const camera = batch.camera!; + + if (curCamera !== camera) { + if (curCamera) { + cmdBuff.endRenderPass(); + } + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; + + camera.update(); + + // update ubo + mat4.array(_mat4Array, camera.matViewProj); + this._uboUI.view.set(_mat4Array, UBOUI.MAT_VIEW_PROJ_OFFSET); + + this._uiUBO!.update(this._uboUI.view); + + curCamera = camera; + + cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); + } + + material.bindingLayout.bindBuffer(0, this._uiUBO!); + material.bindingLayout.bindTextureView(1, batch.texView!); + material.bindingLayout.update(); + + let ia = batch.bufferBatch!.ia! + ia.indexCount = batch.idxCount; + + cmdBuff.bindPipelineState(material.pipelineState); + cmdBuff.bindBindingLayout(material.bindingLayout); + cmdBuff.bindInputAssembler(batch.bufferBatch!.ia!); + cmdBuff.draw(batch.bufferBatch!.ia!); + } + + cmdBuff.endRenderPass(); + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); + } + } + + // skip the first object + private _walk (renderComp, fn1, fn2, level = 0) { + let renderCompList; + if(level === 0){ + level+=1; + renderCompList = this._defineNodeOrder(renderComp.children); + renderCompList.forEach(comp => { + this._walk(comp, fn1, fn2, level); + }); + this._sortChildList.remove(renderCompList); + return; + } + + // const len = node.children.length; + fn1(renderComp); + + renderCompList = this._defineNodeOrder(renderComp.node.children); + for (const comp of renderCompList){ + this._walk(comp, fn1, fn2, level); + } + // for (let i = 0; i < len; ++i) { + // const child = node.children[i]; + // this._walk(child, fn1, fn2, level); + // } + + + this._sortChildList.remove(renderCompList); + fn2(renderComp); + level += 1; + } + + private _defineNodeOrder(childs: Node[]) { + let sortList = this._sortChildList.add(); + + childs.forEach((child) => { + let renderComp = child.getComponent(UIRenderComponent); + if (renderComp) { + sortList.push(renderComp); + } + }) + + sortList.sort((a, b) => { + return (a.priority - b.priority); + }); + + return sortList; + } + + private _renderScreens () { + this._reset(); + for (const screen of this._screens) { + if (!screen.enabledInHierarchy) { + continue; + } + // this._currScreen = screen; + this._commitUIRenderDatas.length = 0; + + this._walk(screen.node, (c: UIRenderComponent) => { + // const renderComponent = c.getComponent(UIRenderComponent); + if (c.enabledInHierarchy) { + this._commitComp(c); + } + }, (c: UIRenderComponent) => { + // const renderComponent = c.getComponent(UIRenderComponent); + if (c.enabledInHierarchy) { + this._postCommitComp(c); + } + }); + + this._commitUICanvasDatas.push({ camera: screen.camera!, datas: this._commitUIRenderDatas }); + } + } + + private _reset () { + this._bufferPool.reset(); + this._commitUIRenderDataPool.reset(); + this._commitUICanvasDatas.length = 0; + } + + private _commitComp (comp: UIRenderComponent) { + comp.updateAssembler(this); + // const canvasComp: CanvasComponent | null = this.getScreen(comp.viewID); + + // const renderDataFormat: IUIRenderData = this._commitUIRenderDataPool.add(); + // renderDataFormat.meshBuffer = buffer; + // renderDataFormat.material = comp.material as Material; + // renderDataFormat.camera = canvasComp!.camera!; + } + + private _postCommitComp (comp: UIRenderComponent) { + comp.postUpdateAssembler(); + } + + private mergeBatches () { + let curCamera: Camera | null = null; + let curTexView: GFXTextureView | null = null; + let bufferBatchIdx = 0; + let curBufferBatch: UIBufferBatch = this._bufferBatches[bufferBatchIdx++]; + let idxCount = 0; + let vertCount = 0; + + let vf32: Float32Array; + let vui16: Uint16Array; + let vbSize = 0; + let ibSize = 0; + let isNewBatch = false; + + for (const uiRenderData of this._commitUIRenderDatas) { + + if (idxCount + uiRenderData.meshBuffer.vData!.length > 65535) { + if (bufferBatchIdx >= this._bufferBatches.length) { + this.createBufferBatch(); + } + + curBufferBatch = this._bufferBatches[bufferBatchIdx++]; + vertCount = 0; + idxCount = 0; + isNewBatch = true; + } else { + isNewBatch = false; + } + + // merge vertices + vf32 = uiRenderData.meshBuffer.vData!; + vbSize = (vf32.length + vertCount) * 4; + if (vbSize > curBufferBatch.vbSize) { + curBufferBatch.vbSize = vbSize; + const lastVF32 = curBufferBatch.vf32; + curBufferBatch.vf32 = new Float32Array(vf32.length + vertCount); + curBufferBatch.vf32.set(lastVF32!, 0); + } + + curBufferBatch.vf32!.set(vf32, vertCount); + + // merge indices + vui16 = uiRenderData.meshBuffer.iData!; + ibSize = (vui16.length + idxCount) * 2; + if (ibSize > curBufferBatch.ibSize) { + curBufferBatch.ibSize = ibSize; + const lastVUI16 = curBufferBatch.vui16!; + curBufferBatch.vui16 = new Uint16Array(vui16.length + idxCount); + curBufferBatch.vui16.set(lastVUI16, 0); + } + + for (let n = 0; n < vui16.length; ++n) { + curBufferBatch.vui16![idxCount + n] = vui16[n] + vertCount; + } + + curBufferBatch.vui16!.set(vui16, idxCount); + + vertCount += vf32.length; + idxCount += vui16.length; + + if (curCamera !== uiRenderData.camera) { + isNewBatch = true; + curCamera = uiRenderData.camera; + } + + if (curTexView !== uiRenderData.texture.getGFXTextureView()) { + curTexView = uiRenderData.texture.getGFXTextureView(); + isNewBatch = true; + } + + if (isNewBatch) { + const batch = this._drawBatchPool.add(); + batch.camera = curCamera; + batch.bufferBatch = curBufferBatch; + batch.uiMaterial = this._uiMaterial!; + batch.texView = curTexView!; + batch.idxCount = idxCount; + + this._batches.push(batch); + } + } // for + } + + private createBufferBatch (): UIBufferBatch { + + const vbStride = Float32Array.BYTES_PER_ELEMENT * 9; + const vbCount = 128; + const varrCount = 128 * 9; + + const vb = this._device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: vbStride * vbCount, + stride: vbStride, + }); + + const ibStride = Uint16Array.BYTES_PER_ELEMENT; + const ibCount = 128; + + const ib = this._device.createBuffer({ + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: ibStride * ibCount, + stride: ibStride, + }); + + const ia = this._device.createInputAssembler({ + attributes: this._attributes, + vertexBuffers: [vb], + indexBuffer: ib, + }); + + const batch = this._bufferBatchPool.add(); + batch.vb = vb; + batch.ib = ib; + batch.ia = ia; + batch.vf32 = new Float32Array(varrCount); + batch.vui16 = new Uint16Array(ibCount); + batch.vbSize = vb.size; + batch.ibSize = ib.size; + this._bufferBatches.push(batch); + return batch; + } +} diff --git a/cocos/renderer/utils.js b/cocos/renderer/utils.js index 38b7e48345..cb372456d4 100644 --- a/cocos/renderer/utils.js +++ b/cocos/renderer/utils.js @@ -1,65 +1,63 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import gfx from './gfx'; -import InputAssembler from './core/input-assembler'; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat, GFXAttributeName } from '../gfx/define'; -/** - * @param {gfx.Device} device - * @param {Object} data - */ export function createIA(device, data) { - if (!data.positions) { - console.error('The data must have positions field'); - return null; - } + if (!data.positions) { + console.error('The data must have positions field'); + return null; + } - let verts = []; - let vcount = data.positions.length / 3; + let verts = []; + let vcount = data.positions.length / 3; - for (let i = 0; i < vcount; ++i) { - verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]); + for (let i = 0; i < vcount; ++i) { + verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]); + if (data.normals) { + verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]); + } + if (data.uvs) { + verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]); + } + if (data.colors) { + verts.push(data.colors[3 * i], data.uvs[3 * i + 1], data.colors[3 * i + 2]); + } + } + + let vfmt = []; + vfmt.push({ name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }); if (data.normals) { - verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]); + vfmt.push({ name: GFXAttributeName.ATTR_NORMAL, format: GFXFormat.RGB32F }); } if (data.uvs) { - verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]); + vfmt.push({ name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RG32F }); } if (data.colors) { - verts.push(data.colors[3 * i], data.uvs[3 * i + 1], data.colors[3 * i + 2]); + vfmt.push({ name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGB32F }); } - } - let vfmt = []; - vfmt.push({ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - if (data.normals) { - vfmt.push({ name: gfx.ATTR_NORMAL, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - } - if (data.uvs) { - vfmt.push({ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }); - } - if (data.colors) { - vfmt.push({ name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - } + let vb = device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: verts.length * 4, + stride: verts.length * 4 / vcount, + }); - let vb = new gfx.VertexBuffer( - device, - new gfx.VertexFormat(vfmt), - gfx.USAGE_STATIC, - new Float32Array(verts), - vcount - ); + vb.update(new Float32Array(verts)); - let ib = null; - if (data.indices) { - ib = new gfx.IndexBuffer( - device, - gfx.INDEX_FMT_UINT16, - gfx.USAGE_STATIC, - new Uint16Array(data.indices), - data.indices.length - ); - } + let ib = device.createBuffer({ + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: data.indices.length * 2, + stride: 2, + }); - return new InputAssembler(vb, ib, data.primitiveType); + ib.update(new Uint16Array(data.indices)); + + return device.createInputAssembler({ + attributes: vfmt, + vertexBuffers: [vb], + indexBuffer: ib, + }); } diff --git a/cocos/scene-graph/base-node-dev.js b/cocos/scene-graph/base-node-dev.js new file mode 100644 index 0000000000..6dca6202b4 --- /dev/null +++ b/cocos/scene-graph/base-node-dev.js @@ -0,0 +1,151 @@ + +import { CCObject } from '../core/data/object'; +import * as js from '../core/utils/js'; + +// @ts-ignore +const Destroying = CCObject.Flags.Destroying; + +export function baseNodePolyfill (BaseNode) { + if (CC_EDITOR) { + BaseNode.prototype._checkMultipleComp = function (ctor) { + const existing = this.getComponent(ctor._disallowMultiple); + if (existing) { + if (existing.constructor === ctor) { + cc.errorID(3805, js.getClassName(ctor), this._name); + } else { + cc.errorID(3806, js.getClassName(ctor), this._name, js.getClassName(existing)); + } + return false; + } + return true; + }; + + /** + * This api should only used by undo system + * @method _addComponentAt + * @param {Component} comp + * @param {Number} index + * @private + */ + BaseNode.prototype._addComponentAt = function (comp, index) { + if (this._objFlags & Destroying) { + return cc.error('isDestroying'); + } + if (!(comp instanceof cc.Component)) { + return cc.errorID(3811); + } + if (index > this._components.length) { + return cc.errorID(3812); + } + + // recheck attributes because script may changed + const ctor = comp.constructor; + if (ctor._disallowMultiple) { + if (!this._checkMultipleComp(ctor)) { + return; + } + } + const ReqComp = ctor._requireComponent; + if (ReqComp && !this.getComponent(ReqComp)) { + if (index === this._components.length) { + // If comp should be last component, increase the index because required component added + ++index; + } + const depended = this.addComponent(ReqComp); + if (!depended) { + // depend conflicts + return null; + } + } + + comp.node = this; + this._components.splice(index, 0, comp); + if ((CC_EDITOR || CC_TEST) && cc.engine && (this._id in cc.engine.attachedObjsForEditor)) { + cc.engine.attachedObjsForEditor[comp._id] = comp; + } + if (this._activeInHierarchy) { + cc.director._nodeActivator.activateComp(comp); + } + }; + + /** + * @method _getDependComponent + * @param {Component} depended + * @return {Component} + * @private + */ + BaseNode.prototype._getDependComponent = function (depended) { + for (let i = 0; i < this._components.length; i++) { + const comp = this._components[i]; + if (comp !== depended && comp.isValid && !cc.Object._willDestroy(comp)) { + const depend = comp.constructor._requireComponent; + if (depend && depended instanceof depend) { + return comp; + } + } + } + return null; + }; + + BaseNode.prototype.onRestore = function () { + // check activity state + const shouldActiveNow = this._active && !!(this._parent && this._parent._activeInHierarchy); + if (this._activeInHierarchy !== shouldActiveNow) { + cc.director._nodeActivator.activateNode(this, shouldActiveNow); + } + }; + + BaseNode.prototype._onPreDestroy = function () { + const destroyByParent = this._onPreDestroyBase(); + if (!destroyByParent) { + // ensure this node can reattach to scene by undo system + // (simulate some destruct logic to make undo system work correctly) + this._parent = null; + } + return destroyByParent; + }; + + BaseNode.prototype._onRestoreBase = BaseNode.prototype.onRestore; + } + + if (CC_EDITOR || CC_TEST) { + BaseNode.prototype._registerIfAttached = function (register) { + const attachedObjsForEditor = cc.engine.attachedObjsForEditor; + if (register) { + attachedObjsForEditor[this._id] = this; + for (const comp of this._components) { + attachedObjsForEditor[comp._id] = comp; + } + cc.engine.emit('node-attach-to-scene', this); + } else { + cc.engine.emit('node-detach-from-scene', this); + delete attachedObjsForEditor[this._id]; + for (const comp of this._components) { + delete attachedObjsForEditor[comp._id]; + } + } + const children = this._children; + for (let i = 0, len = children.length; i < len; ++i) { + const child = children[i]; + child._registerIfAttached(register); + } + }; + } + + if (CC_DEV) { + // promote debug info + js.get(BaseNode.prototype, ' INFO ', function () { + let path = ''; + let node = this; + while (node && !(node instanceof cc.Scene)) { + if (path) { + path = node.name + '/' + path; + } else { + path = node.name; + } + node = node._parent; + } + return this.name + ', path: ' + path; + }); + } +} \ No newline at end of file diff --git a/cocos/scene-graph/base-node.js b/cocos/scene-graph/base-node.ts similarity index 58% rename from cocos/scene-graph/base-node.js rename to cocos/scene-graph/base-node.ts index 181cf5aaab..e8c5d35b9d 100644 --- a/cocos/scene-graph/base-node.js +++ b/cocos/scene-graph/base-node.ts @@ -24,21 +24,28 @@ THE SOFTWARE. ****************************************************************************/ -import * as js from '../core/utils/js'; -import IdGenerator from '../core/utils/id-generator'; -import CCObject from '../core/data/object'; +import { Component } from '../components/component'; import { ccclass, property } from '../core/data/class-decorator'; +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'; +type Constructor = new (...args: any[]) => T; + +// @ts-ignore const Destroying = CCObject.Flags.Destroying; +// @ts-ignore const DontDestroy = CCObject.Flags.DontDestroy; +// @ts-ignore const Deactivating = CCObject.Flags.Deactivating; const CHILD_ADDED = 'child-added'; const CHILD_REMOVED = 'child-removed'; -var idGenerator = new IdGenerator('Node'); +const idGenerator = new IdGenerator('Node'); -function getConstructor(typeOrClassName) { +function getConstructor (typeOrClassName: string | Function): Function | null { if (!typeOrClassName) { cc.errorID(3804); return null; @@ -50,72 +57,6 @@ function getConstructor(typeOrClassName) { return typeOrClassName; } -function findComponent(node, constructor) { - if (constructor._sealed) { - for (let i = 0; i < node._components.length; ++i) { - let comp = node._components[i]; - if (comp.constructor === constructor) { - return comp; - } - } - } - else { - for (let i = 0; i < node._components.length; ++i) { - let comp = node._components[i]; - if (comp instanceof constructor) { - return comp; - } - } - } - return null; -} - -function findComponents(node, constructor, components) { - if (constructor._sealed) { - for (let i = 0; i < node._components.length; ++i) { - let comp = node._components[i]; - if (comp.constructor === constructor) { - components.push(comp); - } - } - } - else { - for (let i = 0; i < node._components.length; ++i) { - let comp = node._components[i]; - if (comp instanceof constructor) { - components.push(comp); - } - } - } -} - -function findChildComponent(children, constructor) { - for (var i = 0; i < children.length; ++i) { - var node = children[i]; - var comp = findComponent(node, constructor); - if (comp) { - return comp; - } - else if (node._children.length > 0) { - comp = findChildComponent(node._children, constructor); - if (comp) { - return comp; - } - } - } - return null; -} - -function findChildComponents(children, constructor, components) { - for (var i = 0; i < children.length; ++i) { - var node = children[i]; - findComponents(node, constructor, components); - if (node._children.length > 0) { - findChildComponents(node._children, constructor, components); - } - } -} - /** * A base node for CCNode, it will: * - maintain scene hierarchy and active logic @@ -131,44 +72,8 @@ function findChildComponents(children, constructor, components) { * @param {String} [name] * @private */ -@ccclass("cc._BaseNode") -export default class BaseNode extends CCObject { - @property - _parent = null; - - @property - _children = []; - - @property - _active = true; - - /** - * @property _level - * @type {Number} - * @default 0 - * @private - */ - @property - _level = 0; - - /** - * @property _components - * @type {Component[]} - * @default [] - * @readOnly - * @private - */ - @property - _components = []; - - /** - * The PrefabInfo object - * @property _prefab - * @type {PrefabInfo} - * @private - */ - @property - _prefab = null; +@ccclass('cc._BaseNode') +export class BaseNode extends CCObject { /** * If true, the node is an persist node which won't be destroyed during scene transition. @@ -179,14 +84,13 @@ export default class BaseNode extends CCObject { * @private */ @property - get _persistNode() { + get _persistNode () { return (this._objFlags & DontDestroy) > 0; } - set _persistNode(value) { + set _persistNode (value) { if (value) { this._objFlags |= DontDestroy; - } - else { + } else { this._objFlags &= ~DontDestroy; } } @@ -203,10 +107,10 @@ export default class BaseNode extends CCObject { * cc.log("Node Name: " + node.name); */ @property - get name() { + get name () { return this._name; } - set name(value) { + set name (value) { if (CC_DEV && value.indexOf('/') !== -1) { cc.errorID(1632); return; @@ -224,7 +128,7 @@ export default class BaseNode extends CCObject { * cc.log("Node Uuid: " + node.uuid); */ @property - get uuid() { + get uuid () { return this._id; } @@ -241,7 +145,7 @@ export default class BaseNode extends CCObject { * } */ @property - get children() { + get children () { return this._children; } @@ -256,7 +160,7 @@ export default class BaseNode extends CCObject { * cc.log("Node Children Count: " + count); */ @property - get childrenCount() { + get childrenCount () { return this._children.length; } @@ -264,7 +168,8 @@ export default class BaseNode extends CCObject { * !#en * The local active state of this node.
* Note that a Node may be inactive because a parent is not active, even if this returns true.
- * Use {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}} if you want to check if the Node is actually treated as active in the scene. + * Use {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}} + * if you want to check if the Node is actually treated as active in the scene. * !#zh * 当前节点的自身激活状态。
* 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。
@@ -276,18 +181,17 @@ export default class BaseNode extends CCObject { * node.active = false; */ @property - get active() { + get active () { return this._active; } - set active(value) { - value = !!value; - if (this._active !== value) { - this._active = value; - var parent = this._parent; + set active (isActive: boolean) { + if (this._active !== isActive) { + this._active = isActive; + const parent = this._parent; if (parent) { - var couldActiveInScene = parent._activeInHierarchy; + const couldActiveInScene = parent._activeInHierarchy; if (couldActiveInScene) { - cc.director._nodeActivator.activateNode(this, value); + cc.director._nodeActivator.activateNode(this, isActive); } } } @@ -302,65 +206,176 @@ export default class BaseNode extends CCObject { * cc.log("activeInHierarchy: " + node.activeInHierarchy); */ @property - get activeInHierarchy() { + get activeInHierarchy () { return this._activeInHierarchy; } + get parent () { + return this._parent; + } + set parent (value) { + this.setParent(value); + } + + public static _setScene (node: BaseNode) { + if (node instanceof cc.Scene) { + node._scene = node; + } else { + if (node._parent == null) { + cc.error('Node %s(%s) has not attached to a scene.', node.name, node.uuid); + } else { + node._scene = node._parent._scene; + } + } + } + + private static idGenerator = idGenerator; + + // For walk + private static _stacks: Array> = [[]]; + private static _stackId = 0; + + private static _findComponent (node: BaseNode, constructor: Function) { + // tslint:disable-next-line + if (constructor['_sealed']) { + for (const comp of node._components) { + if (comp.constructor === constructor) { + return comp; + } + } + } else { + for (const comp of node._components) { + if (comp instanceof constructor) { + return comp; + } + } + } + return null; + } + + private static _findComponents (node: BaseNode, constructor: Function, components: Component[]) { + // tslint:disable-next-line + if (constructor['_sealed']) { + for (const comp of node._components) { + if (comp.constructor === constructor) { + components.push(comp); + } + } + } else { + for (const comp of node._components) { + if (comp instanceof constructor) { + components.push(comp); + } + } + } + } + + private static _findChildComponent (children: BaseNode[], constructor) { + for (const node of children) { + let comp = BaseNode._findComponent(node, constructor); + if (comp) { + return comp; + } else if (node._children.length > 0) { + comp = BaseNode._findChildComponent(node._children, constructor); + if (comp) { + return comp; + } + } + } + return null; + } + + private static _findChildComponents (children: BaseNode[], constructor, components) { + for (const node of children) { + BaseNode._findComponents(node, constructor, components); + if (node._children.length > 0) { + BaseNode._findChildComponents(node._children, constructor, components); + } + } + } + + @property + protected _parent: this | null = null; + + @property + protected _children: this[] = []; + + @property + private _active = true; + + /** + * @default 0 + */ + @property + private _level = 0; + + /** + * @default [] + * @readOnly + */ + @property + private _components: Component[] = []; + + /** + * The PrefabInfo object + * @type {PrefabInfo} + */ + @property + private _prefab: any = null; + + /** + * !#en which scene this node belongs to. + * !#zh 此节点属于哪个场景。 + * @type {cc.Scene}} + */ + private _scene: any = null; + + private _activeInHierarchy = false; + + // TO DO + // @ts-ignore + private _id: string = CC_EDITOR ? Editor.Utils.UuidUtils.uuid() : idGenerator.getNewId(); + + /** + * Register all related EventTargets, + * all event callbacks will be removed in _onPreDestroy + * private __eventTargets: EventTarget[] = []; + */ + private __eventTargets: any[] = []; /** * @method constructor * @param {String} [name] */ - constructor (name) { + constructor (name?: string) { super(name); this._name = name !== undefined ? name : 'New Node'; - this._activeInHierarchy = false; - this._id = CC_EDITOR ? Editor.Utils.UuidUtils.uuid() : idGenerator.getNewId(); - cc.director._scheduler && cc.director._scheduler.enableForTarget(this); - - /** - * Register all related EventTargets, - * all event callbacks will be removed in _onPreDestroy - * @property __eventTargets - * @type {EventTarget[]} - * @private - */ - this.__eventTargets = []; + if (cc.director._scheduler) { + cc.director._scheduler.enableForTarget(this); + } } /** * !#en Get parent of the node. * !#zh 获取该节点的父节点。 - * @method getParent - * @return {Node} * @example * var parent = this.node.getParent(); */ - getParent () { - return this._parent; - } - get parent() { + public getParent () { return this._parent; } /** * !#en Set parent of the node. * !#zh 设置该节点的父节点。 - * @method setParent - * @param {Node} value * @example * node.setParent(newNode); */ - setParent (value) { + public setParent (value: this | null) { if (this._parent === value) { return; } - if (CC_EDITOR && cc.engine && !cc.engine.isPlaying) { - if (_Scene.DetectConflict.beforeAddChild(this)) { - return; - } - } - var oldParent = this._parent; + const oldParent = this._parent; if (CC_DEBUG && oldParent && (oldParent._objFlags & Deactivating)) { cc.errorID(3821); } @@ -374,23 +389,24 @@ export default class BaseNode extends CCObject { } this._level = value._level + 1; value._children.push(this); - value.emit && value.emit(CHILD_ADDED, this); + if (value.emit) { + value.emit(CHILD_ADDED, this); + } } if (oldParent) { if (!(oldParent._objFlags & Destroying)) { - var removeAt = oldParent._children.indexOf(this); + const removeAt = oldParent._children.indexOf(this); if (CC_DEV && removeAt < 0) { return cc.errorID(1633); } oldParent._children.splice(removeAt, 1); - oldParent.emit && oldParent.emit(CHILD_REMOVED, this); + if (oldParent.emit) { + oldParent.emit(CHILD_REMOVED, this); + } } } this._onHierarchyChanged(oldParent); } - set parent(value) { - this.setParent(value); - } // ABSTRACT INTERFACES @@ -401,13 +417,12 @@ export default class BaseNode extends CCObject { * when the setter of the node is available,
* the property will be set via setter function.
* !#zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 - * @method attr - * @param {Object} attrs - Properties to be set to node + * @param attrs - Properties to be set to node * @example * var attrs = { key: 0, num: 100 }; * node.attr(attrs); */ - attr (attrs) { + public attr (attrs: Object) { js.mixin(this, attrs); } @@ -416,22 +431,22 @@ export default class BaseNode extends CCObject { /** * !#en Returns a child from the container given its uuid. * !#zh 通过 uuid 获取节点的子节点。 - * @method getChildByUuid - * @param {String} uuid - The uuid to find the child node. - * @return {Node} a Node whose uuid equals to the input parameter + * @param uuid - The uuid to find the child node. + * @return a Node whose uuid equals to the input parameter * @example * var child = node.getChildByUuid(uuid); */ - getChildByUuid (uuid) { + public getChildByUuid (uuid: string) { if (!uuid) { - cc.log("Invalid uuid"); + cc.log('Invalid uuid'); return null; } - var locChildren = this._children; - for (var i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]._id === uuid) + const locChildren = this._children; + for (let i = 0, len = locChildren.length; i < len; i++) { + if (locChildren[i]._id === uuid) { return locChildren[i]; + } } return null; } @@ -439,22 +454,22 @@ export default class BaseNode extends CCObject { /** * !#en Returns a child from the container given its name. * !#zh 通过名称获取节点的子节点。 - * @method getChildByName - * @param {String} name - A name to find the child node. - * @return {Node} a CCNode object whose name equals to the input parameter + * @param name - A name to find the child node. + * @return a CCNode object whose name equals to the input parameter * @example * var child = node.getChildByName("Test Node"); */ - getChildByName (name) { + public getChildByName (name: string) { if (!name) { - cc.log("Invalid name"); + cc.log('Invalid name'); return null; } - var locChildren = this._children; - for (var i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]._name === name) + const locChildren = this._children; + for (let i = 0, len = locChildren.length; i < len; i++) { + if (locChildren[i]._name === name) { return locChildren[i]; + } } return null; } @@ -462,27 +477,27 @@ export default class BaseNode extends CCObject { /** * !#en Returns a child from the container given its path. * !#zh 通过路径获取节点的子节点。 - * @method getChildByPath - * @param {String} path - A path to find the child node. - * @return {Node} a CCNode object whose name equals to the input parameter + * @param path - A path to find the child node. + * @return a CCNode object whose name equals to the input parameter * @example * var child = node.getChildByPath("Test Node"); */ - getChildByPath (path) { + public getChildByPath (path: string) { const segments = path.split('/'); - let lastNode = this; + let lastNode: this = this; for (const segment of segments) { - lastNode = lastNode.children.find(childNode => childNode.name === segment); - if (!lastNode) { - break; + const next = lastNode.children.find((childNode) => childNode.name === segment); + if (!next) { + return null; } + lastNode = next; } return lastNode; } // composition: ADD - addChild (child) { + public addChild (child: this): void { if (CC_DEV && !(child instanceof cc._BaseNode)) { return cc.errorID(1634, cc.js.getClassName(child)); @@ -500,13 +515,12 @@ export default class BaseNode extends CCObject { * Inserts a child to the node at a specified index. * !#zh * 插入子节点到指定位置 - * @method insertChild - * @param {Node} child - the child node to be inserted - * @param {Number} siblingIndex - the sibling index to place the child in + * @param child - the child node to be inserted + * @param siblingIndex - the sibling index to place the child in * @example * node.insertChild(child, 2); */ - insertChild (child, siblingIndex) { + public insertChild (child: this, siblingIndex: number) { child.parent = this; child.setSiblingIndex(siblingIndex); } @@ -516,16 +530,13 @@ export default class BaseNode extends CCObject { /** * !#en Get the sibling index. * !#zh 获取同级索引。 - * @method getSiblingIndex - * @return {Number} * @example * var index = node.getSiblingIndex(); */ - getSiblingIndex () { + public getSiblingIndex () { if (this._parent) { return this._parent._children.indexOf(this); - } - else { + } else { return 0; } } @@ -533,12 +544,10 @@ export default class BaseNode extends CCObject { /** * !#en Set the sibling index of this node. * !#zh 设置节点同级索引。 - * @method setSiblingIndex - * @param {Number} index * @example * node.setSiblingIndex(1); */ - setSiblingIndex (index) { + public setSiblingIndex (index: number) { if (!this._parent) { return; } @@ -546,35 +555,34 @@ export default class BaseNode extends CCObject { cc.errorID(3821); return; } - var siblings = this._parent._children; + const siblings = this._parent._children; index = index !== -1 ? index : siblings.length - 1; - var oldIndex = siblings.indexOf(this); + const oldIndex = siblings.indexOf(this); if (index !== oldIndex) { siblings.splice(oldIndex, 1); if (index < siblings.length) { siblings.splice(index, 0, this); - } - else { + } else { siblings.push(this); } - this._onSiblingIndexChanged && this._onSiblingIndexChanged(index); + if (this._onSiblingIndexChanged) { + this._onSiblingIndexChanged(index); + } } } /** * !#en Walk though the sub children tree of the current node. - * Each node, including the current node, in the sub tree will be visited two times, before all children and after all children. + * Each node, including the current node, in the sub tree will be visited two times, + * before all children and after all children. * This function call is not recursive, it's based on stack. * Please don't walk any other node inside the walk process. * !#zh 遍历该节点的子树里的所有节点并按规则执行回调函数。 * 对子树中的所有节点,包含当前节点,会执行两次回调,prefunc 会在访问它的子节点之前调用,postfunc 会在访问所有子节点之后调用。 * 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。 * 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。 - * @method walk - * @param {Function} prefunc The callback to process node when reach the node for the first time - * @param {_BaseNode} prefunc.target The current visiting node - * @param {Function} postfunc The callback to process node when re-visit the node after walked all children in its sub tree - * @param {_BaseNode} postfunc.target The current visiting node + * @param prefunc The callback to process node when reach the node for the first time + * @param postfunc The callback to process node when re-visit the node after walked all children in its sub tree * @example * node.walk(function (target) { * console.log('Walked through node ' + target.name + ' for the first time'); @@ -582,11 +590,13 @@ export default class BaseNode extends CCObject { * console.log('Walked through node ' + target.name + ' after walked all children in its sub tree'); * }); */ - walk (prefunc, postfunc) { - var BaseNode = cc._BaseNode; - var index = 1; - var children, curr, i, afterChildren; - var stack = BaseNode._stacks[BaseNode._stackId]; + public walk (prefunc: (target: this) => void, postfunc?: (target: this) => void) { + // const BaseNode = cc._BaseNode; + let index = 1; + let children: this[] | null = null; + let curr: this | null = null; + let i = 0; + let stack = BaseNode._stacks[BaseNode._stackId]; if (!stack) { stack = []; BaseNode._stacks.push(stack); @@ -595,19 +605,18 @@ export default class BaseNode extends CCObject { stack.length = 0; stack[0] = this; - var parent = null; - afterChildren = false; + let parent: this | null = null; + let afterChildren = false; while (index) { index--; - curr = stack[index]; + curr = stack[index] as (this | null); if (!curr) { continue; } if (!afterChildren && prefunc) { // pre call prefunc(curr); - } - else if (afterChildren && postfunc) { + } else if (afterChildren && postfunc) { // post call postfunc(curr); } @@ -617,8 +626,7 @@ export default class BaseNode extends CCObject { // Do not repeatly visit child tree, just do post call and continue walk if (afterChildren) { afterChildren = false; - } - else { + } else { // Children not proceeded and has children, proceed to child tree if (curr._children.length > 0) { parent = curr; @@ -626,9 +634,7 @@ export default class BaseNode extends CCObject { i = 0; stack[index] = children[i]; index++; - } - // No children, then repush curr to be walked for post func - else { + } else { stack[index] = curr; index++; afterChildren = true; @@ -642,9 +648,7 @@ export default class BaseNode extends CCObject { if (children[i]) { stack[index] = children[i]; index++; - } - // No children any more in this sub tree, go upward - else if (parent) { + } else if (parent) { stack[index] = parent; index++; // Setup parent walk env @@ -653,8 +657,7 @@ export default class BaseNode extends CCObject { children = parent._parent._children; i = children.indexOf(parent); parent = parent._parent; - } - else { + } else { // At root parent = null; children = null; @@ -674,30 +677,32 @@ export default class BaseNode extends CCObject { /** * !#en * Remove itself from its parent node. If cleanup is `true`, then also remove all events and actions.
- * If the cleanup parameter is not passed, it will force a cleanup, so it is recommended that you always pass in the `false` parameter when calling this API.
+ * If the cleanup parameter is not passed, it will force a cleanup, + * so it is recommended that you always pass in the `false` parameter when calling this API.
* If the node orphan, then nothing happens. * !#zh * 从父节点中删除该节点。如果不传入 cleanup 参数或者传入 `true`,那么这个节点上所有绑定的事件、action 都会被删除。
* 因此建议调用这个 API 时总是传入 `false` 参数。
* 如果这个节点是一个孤节点,那么什么都不会发生。 - * @method removeFromParent - * @param {Boolean} [cleanup=true] - true if all actions and callbacks on this node should be removed, false otherwise. + * @param [cleanup=true] - true if all actions and callbacks on this node should be removed, false otherwise. * @see cc.Node#removeFromParentAndCleanup * @example * node.removeFromParent(); * node.removeFromParent(false); */ - removeFromParent (cleanup) { + public removeFromParent (cleanup?: boolean) { if (this._parent) { - if (cleanup === undefined) + if (cleanup === undefined) { cleanup = true; + } this._parent.removeChild(this, cleanup); } } /** * !#en - * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.

+ * Removes a child from the container. + * It will also cleanup all running actions depending on the cleanup parameter.

* If the cleanup parameter is not passed, it will force a cleanup.
* "remove" logic MUST only be on this method
* If a class wants to extend the 'removeChild' behavior it only needs
@@ -705,14 +710,14 @@ export default class BaseNode extends CCObject { * !#zh * 移除节点中指定的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。
* 如果 cleanup 参数不传入,默认为 true 表示清理。
- * @method removeChild - * @param {Node} child - The child node which will be removed. - * @param {Boolean} [cleanup=true] - true if all running actions and callbacks on the child node will be cleanup, false otherwise. + * @param child - The child node which will be removed. + * @param [cleanup=true] - true if all running actions and callbacks on the child node + * will be cleanup, false otherwise. * @example * node.removeChild(newNode); * node.removeChild(newNode, false); */ - removeChild (child, cleanup) { + public removeChild (child: this, cleanup?: boolean) { if (this._children.indexOf(child) > -1) { // If you don't do cleanup, the child's actions will not get removed and the if (cleanup || cleanup === undefined) { @@ -725,28 +730,31 @@ export default class BaseNode extends CCObject { /** * !#en - * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
+ * Removes all children from the container and + * do a cleanup all running actions depending on the cleanup parameter.
* If the cleanup parameter is not passed, it will force a cleanup. * !#zh * 移除节点所有的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。
* 如果 cleanup 参数不传入,默认为 true 表示清理。 - * @method removeAllChildren - * @param {Boolean} [cleanup=true] - true if all running actions on all children nodes should be cleanup, false otherwise. + * @param [cleanup=true] - true if all running actions on all children nodes + * should be cleanup, false otherwise. * @example * node.removeAllChildren(); * node.removeAllChildren(false); */ - removeAllChildren (cleanup) { + public removeAllChildren (cleanup?: boolean) { // not using detachChild improves speed here - var children = this._children; - if (cleanup === undefined) + const children = this._children; + if (cleanup === undefined) { cleanup = true; - for (var i = children.length - 1; i >= 0; i--) { - var node = children[i]; + } + for (let i = children.length - 1; i >= 0; i--) { + const node = children[i]; if (node) { // If you don't do cleanup, the node's actions will not get removed and the - if (cleanup) + if (cleanup) { node.cleanup(); + } node.parent = null; } @@ -757,14 +765,12 @@ export default class BaseNode extends CCObject { /** * !#en Is this node a child of the given node? * !#zh 是否是指定节点的子节点? - * @method isChildOf - * @param {Node} parent - * @return {Boolean} - Returns true if this node is a child, deep child or identical to the given node. + * @return True if this node is a child, deep child or identical to the given node. * @example * node.isChildOf(newNode); */ - isChildOf (parent) { - var child = this; + public isChildOf (parent: this) { + let child: this | null = this; do { if (child === parent) { return true; @@ -784,22 +790,29 @@ export default class BaseNode extends CCObject { * !#zh * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
* 传入参数也可以是脚本的名称。 - * @method getComponent - * @param {Function|String} typeOrClassName - * @return {Component | null} * @example * // get sprite component. * var sprite = node.getComponent(cc.Sprite); + */ + public getComponent (classConstructor: Constructor): T | null; + + /** + * !#en + * Returns the component of supplied type if the node has one attached, null if it doesn't.
+ * You can also get component in the node by passing in the name of the script. + * !#zh + * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
+ * 传入参数也可以是脚本的名称。 + * @example * // get custom test calss. * var test = node.getComponent("Test"); - * @typescript - * getComponent(type: {prototype: T}): T - * getComponent(className: string): any */ - getComponent (typeOrClassName) { - var constructor = getConstructor(typeOrClassName); + public getComponent (className: string): Component | null; + + public getComponent (typeOrClassName: string | Function) { + const constructor = getConstructor(typeOrClassName); if (constructor) { - return findComponent(this, constructor); + return BaseNode._findComponent(this, constructor); } return null; } @@ -807,20 +820,24 @@ export default class BaseNode extends CCObject { /** * !#en Returns all components of supplied type in the node. * !#zh 返回节点上指定类型的所有组件。 - * @method getComponents - * @param {Function|String} typeOrClassName - * @return {Component[]} * @example * var sprites = node.getComponents(cc.Sprite); - * var tests = node.getComponents("Test"); - * @typescript - * getComponents(type: {prototype: T}): T[] - * getComponents(className: string): any[] */ - getComponents (typeOrClassName) { - var constructor = getConstructor(typeOrClassName), components = []; + public getComponents (classConstructor: Constructor): T[]; + + /** + * !#en Returns all components of supplied type in the node. + * !#zh 返回节点上指定类型的所有组件。 + * @example + * var tests = node.getComponents("Test"); + */ + public getComponents (className: string): Component[]; + + public getComponents (typeOrClassName: string | Function) { + const constructor = getConstructor(typeOrClassName); + const components: Component[] = []; if (constructor) { - findComponents(this, constructor, components); + BaseNode._findComponents(this, constructor, components); } return components; } @@ -828,20 +845,23 @@ export default class BaseNode extends CCObject { /** * !#en Returns the component of supplied type in any of its children using depth first search. * !#zh 递归查找所有子节点中第一个匹配指定类型的组件。 - * @method getComponentInChildren - * @param {Function|String} typeOrClassName - * @return {Component} * @example * var sprite = node.getComponentInChildren(cc.Sprite); - * var Test = node.getComponentInChildren("Test"); - * @typescript - * getComponentInChildren(type: {prototype: T}): T - * getComponentInChildren(className: string): any */ - getComponentInChildren (typeOrClassName) { - var constructor = getConstructor(typeOrClassName); + public getComponentInChildren (classConstructor: Constructor): T | null; + + /** + * !#en Returns the component of supplied type in any of its children using depth first search. + * !#zh 递归查找所有子节点中第一个匹配指定类型的组件。 + * @example + * var Test = node.getComponentInChildren("Test"); + */ + public getComponentInChildren (className: string): Component | null; + + public getComponentInChildren (typeOrClassName: string | Function) { + const constructor = getConstructor(typeOrClassName); if (constructor) { - return findChildComponent(this._children, constructor); + return BaseNode._findChildComponent(this._children, constructor); } return null; } @@ -849,21 +869,25 @@ export default class BaseNode extends CCObject { /** * !#en Returns all components of supplied type in self or any of its children. * !#zh 递归查找自身或所有子节点中指定类型的组件 - * @method getComponentsInChildren - * @param {Function|String} typeOrClassName - * @return {Component[]} * @example * var sprites = node.getComponentsInChildren(cc.Sprite); - * var tests = node.getComponentsInChildren("Test"); - * @typescript - * getComponentsInChildren(type: {prototype: T}): T[] - * getComponentsInChildren(className: string): any[] */ - getComponentsInChildren (typeOrClassName) { - var constructor = getConstructor(typeOrClassName), components = []; + public getComponentsInChildren (classConstructor: Constructor): T[]; + + /** + * !#en Returns all components of supplied type in self or any of its children. + * !#zh 递归查找自身或所有子节点中指定类型的组件 + * @example + * var tests = node.getComponentsInChildren("Test"); + */ + public getComponentsInChildren (className: string): Component[]; + + public getComponentsInChildren (typeOrClassName: string | Function) { + const constructor = getConstructor(typeOrClassName); + const components: Component[] = []; if (constructor) { - findComponents(this, constructor, components); - findChildComponents(this._children, constructor, components); + BaseNode._findComponents(this, constructor, components); + BaseNode._findChildComponents(this._children, constructor, components); } return components; } @@ -871,17 +895,20 @@ export default class BaseNode extends CCObject { /** * !#en Adds a component class to the node. You can also add component to node by passing in the name of the script. * !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 - * @method addComponent - * @param {Function|String} typeOrClassName - The constructor or the class name of the component to add - * @return {Component} - The newly added component * @example * var sprite = node.addComponent(cc.Sprite); - * var test = node.addComponent("Test"); - * @typescript - * addComponent(type: {new(): T}): T - * addComponent(className: string): any */ - addComponent (typeOrClassName) { + public addComponent (classConstructor: Constructor): T | null; + + /** + * !#en Adds a component class to the node. You can also add component to node by passing in the name of the script. + * !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 + * @example + * var test = node.addComponent("Test"); + */ + public addComponent (className: string): Component | null; + + public addComponent (typeOrClassName: string | Function) { if (CC_EDITOR && (this._objFlags & Destroying)) { cc.error('isDestroying'); return null; @@ -889,7 +916,7 @@ export default class BaseNode extends CCObject { // get component - var constructor; + let constructor; if (typeof typeOrClassName === 'string') { constructor = js.getClassByName(typeOrClassName); if (!constructor) { @@ -899,8 +926,7 @@ export default class BaseNode extends CCObject { } return null; } - } - else { + } else { if (!typeOrClassName) { cc.errorID(3804); return null; @@ -920,16 +946,16 @@ export default class BaseNode extends CCObject { } if (CC_EDITOR && constructor._disallowMultiple) { - if (!this._checkMultipleComp(constructor)) { + if (!this._checkMultipleComp!(constructor)) { return null; } } // check requirement - var ReqComp = constructor._requireComponent; + const ReqComp = constructor._requireComponent; if (ReqComp && !this.getComponent(ReqComp)) { - var depended = this.addComponent(ReqComp); + const depended = this.addComponent(ReqComp); if (!depended) { // depend conflicts return null; @@ -938,13 +964,13 @@ export default class BaseNode extends CCObject { //// check conflict // - //if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) { + // if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) { // return null; - //} + // } // - var component = new constructor(); + const component = new constructor(); component.node = this; this._components.push(component); if ((CC_EDITOR || CC_TEST) && cc.engine && (this._id in cc.engine.attachedObjsForEditor)) { @@ -964,68 +990,47 @@ export default class BaseNode extends CCObject { * !#zh * 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 * 如果你已经获得组件引用,你也可以直接调用 component.destroy() - * @method removeComponent - * @param {String|Function|Component} component - The need remove component. * @deprecated please destroy the component to remove it. * @example * node.removeComponent(cc.Sprite); - * var Test = require("Test"); - * node.removeComponent(Test); */ - removeComponent (component) { + public removeComponent (classConstructor: Constructor): void; + + /** + * !#en + * Removes a component identified by the given name or removes the component object given. + * You can also use component.destroy() if you already have the reference. + * !#zh + * 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 + * 如果你已经获得组件引用,你也可以直接调用 component.destroy() + * @deprecated please destroy the component to remove it. + * @example + * const sprite = node.getComponent(CC.Sprite); + * if (sprite) { + * node.removeComponent(sprite); + * } + * node.removeComponent('cc.Sprite'); + */ + public removeComponent (classNameOrInstance: string | Component): void; + + public removeComponent (component: any) { if (!component) { cc.errorID(3813); return; } - if (!(component instanceof cc.Component)) { - component = this.getComponent(component); + let componentInstance: Component | null = null; + if (component instanceof Component) { + componentInstance = component; + } else { + componentInstance = this.getComponent(component); } - if (component) { - component.destroy(); + if (componentInstance) { + componentInstance.destroy(); } } - // do remove component, only used internally - _removeComponent (component) { - if (!component) { - cc.errorID(3814); - return; - } - - if (!(this._objFlags & Destroying)) { - var i = this._components.indexOf(component); - if (i !== -1) { - this._components.splice(i, 1); - if ((CC_EDITOR || CC_TEST) && cc.engine) { - delete cc.engine.attachedObjsForEditor[component._id]; - } - } - else if (component.node !== this) { - cc.errorID(3815); - } - } - } - - _disableChildComps () { - // leave this._activeInHierarchy unmodified - var i, len = this._components.length; - for (i = 0; i < len; ++i) { - var component = this._components[i]; - if (component._enabled) { - cc.director._compScheduler.disableComp(component); - } - } - // deactivate recursively - for (i = 0, len = this._children.length; i < len; ++i) { - var node = this._children[i]; - if (node._active) { - node._disableChildComps(); - } - } - } - - destroy () { - if (cc.Object.prototype.destroy.call(this)) { + public destroy () { + if (super.destroy()) { // disable hierarchy if (this._activeInHierarchy) { this._disableChildComps(); @@ -1040,25 +1045,81 @@ export default class BaseNode extends CCObject { * !#zh * 销毁所有子节点,并释放所有它们对其它对象的引用。
* 实际销毁操作会延迟到当前帧渲染前执行。 - * @method destroyAllChildren * @example * node.destroyAllChildren(); */ - destroyAllChildren () { - var children = this._children; - for (var i = 0; i < children.length; ++i) { - children[i].destroy(); + public destroyAllChildren () { + for (const child of this._children) { + child.destroy(); } } - cleanup () {} - _onSetParent (/*oldParent*/) {} - _onPostActivated () {} - _onBatchRestored () {} - _onBatchCreated () {} + public cleanup () { + return; + } - _onHierarchyChanged (oldParent) { - var newParent = this._parent; + public emit? (type: string, ...args: any[]): void; + + protected _onSetParent (oldParent: this | null) { + if (this._parent) { + if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) { + this.walk((node) => { + BaseNode._setScene(node); + }); + } + } + } + + protected _onPostActivated () { + return; + } + + protected _onBatchRestored () { + return; + } + + protected _onBatchCreated () { + return; + } + + protected _onPreDestroy () { + this._onPreDestroyBase(); + } + + protected _onHierarchyChanged (oldParent: this | null) { + return this._onHierarchyChangedBase(oldParent); + } + + protected _instantiate (cloned) { + if (!cloned) { + cloned = cc.instantiate._clone(this, this); + } + + const thisPrefabInfo = this._prefab; + if (CC_EDITOR && thisPrefabInfo) { + if (this !== thisPrefabInfo.root) { + // var PrefabUtils = Editor.require('scene://utils/prefab'); + // PrefabUtils.initClonedChildOfPrefab(cloned); + } + } + const syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; + if (syncing) { + // if (thisPrefabInfo._synced) { + // return clone; + // } + } else if (CC_EDITOR && cc.engine._isPlaying) { + cloned._name += ' (Clone)'; + } + + // reset and init + cloned._parent = null; + cloned._onBatchRestored(); + + return cloned; + } + + private _onHierarchyChangedBase (oldParent: this | null) { + const newParent = this._parent; if (this._persistNode && !(newParent instanceof cc.Scene)) { cc.game.removePersistRootNode(this); if (CC_EDITOR) { @@ -1067,21 +1128,20 @@ export default class BaseNode extends CCObject { } if (CC_EDITOR || CC_TEST) { - var scene = cc.director.getScene(); - var inCurrentSceneBefore = oldParent && oldParent.isChildOf(scene); - var inCurrentSceneNow = newParent && newParent.isChildOf(scene); + const scene = cc.director.getScene(); + const inCurrentSceneBefore = oldParent && oldParent.isChildOf(scene); + const inCurrentSceneNow = newParent && newParent.isChildOf(scene); if (!inCurrentSceneBefore && inCurrentSceneNow) { // attached - this._registerIfAttached(true); - } - else if (inCurrentSceneBefore && !inCurrentSceneNow) { + this._registerIfAttached!(true); + } else if (inCurrentSceneBefore && !inCurrentSceneNow) { // detached - this._registerIfAttached(false); + this._registerIfAttached!(false); } // update prefab - var newPrefabRoot = newParent && newParent._prefab && newParent._prefab.root; - var myPrefabInfo = this._prefab; + const newPrefabRoot = newParent && newParent._prefab && newParent._prefab.root; + const myPrefabInfo = this._prefab; // var PrefabUtils = Editor.require('scene://utils/prefab'); // if (myPrefabInfo) { // if (newPrefabRoot) { @@ -1102,77 +1162,47 @@ export default class BaseNode extends CCObject { // } // conflict detection - //_Scene.DetectConflict.afterAddChild(this); + // _Scene.DetectConflict.afterAddChild(this); } - var shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy); + const shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy); if (this._activeInHierarchy !== shouldActiveNow) { cc.director._nodeActivator.activateNode(this, shouldActiveNow); } } - _instantiate (cloned) { - if (!cloned) { - cloned = cc.instantiate._clone(this, this); - } - - var thisPrefabInfo = this._prefab; - if (CC_EDITOR && thisPrefabInfo) { - if (this !== thisPrefabInfo.root) { - //var PrefabUtils = Editor.require('scene://utils/prefab'); - //PrefabUtils.initClonedChildOfPrefab(cloned); - } - } - var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; - if (syncing) { - //if (thisPrefabInfo._synced) { - // return clone; - //} - } - else if (CC_EDITOR && cc.engine._isPlaying) { - cloned._name += ' (Clone)'; - } - - // reset and init - cloned._parent = null; - cloned._onBatchRestored(); - - return cloned; - } - - _onPreDestroy () { - var i, len; - + private _onPreDestroyBase () { // marked as destroying this._objFlags |= Destroying; // detach self and children from editor - var parent = this._parent; - var destroyByParent = parent && (parent._objFlags & Destroying); + const parent = this._parent; + const destroyByParent: boolean = (parent !== null) && ((parent._objFlags & Destroying) !== 0); if (!destroyByParent && (CC_EDITOR || CC_TEST)) { - this._registerIfAttached(false); + this._registerIfAttached!(false); } // destroy children - var children = this._children; - for (i = 0, len = children.length; i < len; ++i) { + // destroy children + for (const child of this._children) { // destroy immediate so its _onPreDestroy can be called - children[i]._destroyImmediate(); + child._destroyImmediate(); } // destroy self components - for (i = 0, len = this._components.length; i < len; ++i) { - var component = this._components[i]; + for (const component of this._components) { // destroy immediate so its _onPreDestroy can be called + // TO DO + // @ts-ignore component._destroyImmediate(); } - var eventTargets = this.__eventTargets; - for (i = 0, len = eventTargets.length; i < len; ++i) { - var target = eventTargets[i]; - target && target.targetOff(this); + for (const eventTarget of this.__eventTargets) { + if (eventTarget) { + eventTarget.targetOff(this); + } } - eventTargets.length = 0; + this.__eventTargets.length = 0; // remove from persist if (this._persistNode) { @@ -1182,172 +1212,60 @@ export default class BaseNode extends CCObject { if (!destroyByParent) { // remove from parent if (parent) { - var childIndex = parent._children.indexOf(this); + const childIndex = parent._children.indexOf(this); parent._children.splice(childIndex, 1); - parent.emit && parent.emit('child-removed', this); + if (parent.emit) { + parent.emit('child-removed', this); + } } } return destroyByParent; } -} -BaseNode.prototype._onPreDestroyBase = BaseNode.prototype._onPreDestroy; -BaseNode.prototype._onHierarchyChangedBase = BaseNode.prototype._onHierarchyChanged; - -if (CC_EDITOR) { - BaseNode.prototype._checkMultipleComp = function (ctor) { - var existing = this.getComponent(ctor._disallowMultiple); - if (existing) { - if (existing.constructor === ctor) { - cc.errorID(3805, js.getClassName(ctor), this._name); - } - else { - cc.errorID(3806, js.getClassName(ctor), this._name, js.getClassName(existing)); - } - return false; - } - return true; - }; - - /** - * This api should only used by undo system - * @method _addComponentAt - * @param {Component} comp - * @param {Number} index - * @private - */ - BaseNode.prototype._addComponentAt = function (comp, index) { - if (this._objFlags & Destroying) { - return cc.error('isDestroying'); - } - if (!(comp instanceof cc.Component)) { - return cc.errorID(3811); - } - if (index > this._components.length) { - return cc.errorID(3812); + // do remove component, only used internally + private _removeComponent (component: Component) { + if (!component) { + cc.errorID(3814); + return; } - // recheck attributes because script may changed - var ctor = comp.constructor; - if (ctor._disallowMultiple) { - if (!this._checkMultipleComp(ctor)) { - return; - } - } - var ReqComp = ctor._requireComponent; - if (ReqComp && !this.getComponent(ReqComp)) { - if (index === this._components.length) { - // If comp should be last component, increase the index because required component added - ++index; - } - var depended = this.addComponent(ReqComp); - if (!depended) { - // depend conflicts - return null; - } - } - - comp.node = this; - this._components.splice(index, 0, comp); - if ((CC_EDITOR || CC_TEST) && cc.engine && (this._id in cc.engine.attachedObjsForEditor)) { - cc.engine.attachedObjsForEditor[comp._id] = comp; - } - if (this._activeInHierarchy) { - cc.director._nodeActivator.activateComp(comp); - } - }; - - /** - * @method _getDependComponent - * @param {Component} depended - * @return {Component} - * @private - */ - BaseNode.prototype._getDependComponent = function (depended) { - for (var i = 0; i < this._components.length; i++) { - var comp = this._components[i]; - if (comp !== depended && comp.isValid && !cc.Object._willDestroy(comp)) { - var depend = comp.constructor._requireComponent; - if (depend && depended instanceof depend) { - return comp; + if (!(this._objFlags & Destroying)) { + const i = this._components.indexOf(component); + if (i !== -1) { + this._components.splice(i, 1); + if ((CC_EDITOR || CC_TEST) && cc.engine) { + delete cc.engine.attachedObjsForEditor[component._id]; } + } else if ((component.node as BaseNode) !== this) { + cc.errorID(3815); } } - return null; - }; + } - BaseNode.prototype.onRestore = function () { - // check activity state - var shouldActiveNow = this._active && !!(this._parent && this._parent._activeInHierarchy); - if (this._activeInHierarchy !== shouldActiveNow) { - cc.director._nodeActivator.activateNode(this, shouldActiveNow); + private _disableChildComps () { + // leave this._activeInHierarchy unmodified + for (const component of this._components) { + if (component._enabled) { + cc.director._compScheduler.disableComp(component); + } } - }; - - BaseNode.prototype._onPreDestroy = function () { - var destroyByParent = this._onPreDestroyBase(); - if (!destroyByParent) { - // ensure this node can reattach to scene by undo system - // (simulate some destruct logic to make undo system work correctly) - this._parent = null; + // deactivate recursively + for (const node of this._children) { + if (node._active) { + node._disableChildComps(); + } } - return destroyByParent; - }; + } - BaseNode.prototype._onRestoreBase = BaseNode.prototype.onRestore; + private _onSiblingIndexChanged? (siblingIndex: number): void; + + private _registerIfAttached? (attached: boolean): void; + + private _checkMultipleComp? (constructor: Function): boolean; } -if (CC_EDITOR || CC_TEST) { - BaseNode.prototype._registerIfAttached = function (register) { - var attachedObjsForEditor = cc.engine.attachedObjsForEditor; - if (register) { - attachedObjsForEditor[this._id] = this; - for (let i = 0; i < this._components.length; i++) { - let comp = this._components[i]; - attachedObjsForEditor[comp._id] = comp; - } - cc.engine.emit('node-attach-to-scene', this); - } - else { - cc.engine.emit('node-detach-from-scene', this); - delete attachedObjsForEditor[this._id]; - for (let i = 0; i < this._components.length; i++) { - let comp = this._components[i]; - delete attachedObjsForEditor[comp._id]; - } - } - var children = this._children; - for (let i = 0, len = children.length; i < len; ++i) { - var child = children[i]; - child._registerIfAttached(register); - } - }; -} - -if (CC_DEV) { - // promote debug info - js.get(BaseNode.prototype, ' INFO ', function () { - var path = ''; - var node = this; - while (node && !(node instanceof cc.Scene)) { - if (path) { - path = node.name + '/' + path; - } - else { - path = node.name; - } - node = node._parent; - } - return this.name + ', path: ' + path; - }); -} - -BaseNode.idGenerator = idGenerator; - -// For walk -BaseNode._stacks = [[]]; -BaseNode._stackId = 0; +baseNodePolyfill(BaseNode); /** * !#en diff --git a/cocos/scene-graph/component-scheduler.js b/cocos/scene-graph/component-scheduler.js index 121d83b9df..925649e49c 100644 --- a/cocos/scene-graph/component-scheduler.js +++ b/cocos/scene-graph/component-scheduler.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import CCObject from '../core/data/object'; +import { CCObject } from '../core/data/object'; import { MutableForwardIterator } from '../core/utils/array'; import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; @@ -193,7 +193,7 @@ class ReusableInvoker extends LifeCycleInvoker { } } } - + invoke (dt) { if (this._neg.array.length > 0) { this._invoke(this._neg, dt); @@ -479,4 +479,4 @@ if (CC_EDITOR) { }; } -export default ComponentScheduler; \ No newline at end of file +export default ComponentScheduler; diff --git a/cocos/scene-graph/index.js b/cocos/scene-graph/index.js index d3cab311db..94e05131b6 100644 --- a/cocos/scene-graph/index.js +++ b/cocos/scene-graph/index.js @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ -export { default as BaseNode } from './base-node'; -export { default as Node } from './node'; +export { BaseNode } from './base-node'; +export { Node } from './node'; export { default as PrivateNode } from './private-node'; export { default as NodeActivator } from './node-activator'; export { default as Scene } from './scene'; export { default as find } from './find'; -export { default as Layers } from './layers'; +export { Layers } from './layers'; diff --git a/cocos/scene-graph/layers.js b/cocos/scene-graph/layers.ts similarity index 50% rename from cocos/scene-graph/layers.js rename to cocos/scene-graph/layers.ts index cbf668b1b3..47ac5ad384 100644 --- a/cocos/scene-graph/layers.js +++ b/cocos/scene-graph/layers.ts @@ -2,15 +2,27 @@ /** * Entity layer system */ -class Layers { +export class Layers { + + // built-in layers, reserved up to (1 << 7) + public static Default = (1 << 0); + public static IgnoreRaycast = (1 << 1); + public static Gizmos = (1 << 2); + public static Editor = (1 << 3); + // masks + public static All = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor]); + public static RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor, Layers.IgnoreRaycast]); + /** * Add a new layer * @param {string} name name of the new layer * @return {number} new layer's index */ - static addLayer(name) { - if (Layers._nextAvailable > 31) - return new Error('maximum layers reached.'); + public static addLayer (name: string): number | undefined { + if (Layers._nextAvailable > 31) { + console.warn('maximum layers reached.'); + return; + } Layers[name] = (1 << Layers._nextAvailable++); return Layers[name]; } @@ -20,10 +32,11 @@ class Layers { * @param {number[]} includes layers accepted by the mask * @return {number} the specified layer mask */ - static makeInclusiveMask(includes) { + public static makeInclusiveMask (includes: number[]): number { let mask = 0; - for (let i = 0; i < includes.length; i++) - mask |= includes[i]; + for (const inc of includes) { + mask |= inc; + } return mask; } @@ -32,7 +45,7 @@ class Layers { * @param {number[]} excludes layers rejected by the mask * @return {number} the specified layer mask */ - static makeExclusiveMask(excludes) { + public static makeExclusiveMask (excludes: number[]): number { return ~Layers.makeInclusiveMask(excludes); } @@ -42,22 +55,11 @@ class Layers { * @param {number} mask the testing layer mask * @return {boolean} true if accepted */ - static check(layer, mask) { - return (layer & mask) == layer; + public static check (layer: number, mask: number): boolean { + return (layer & mask) === layer; } + + private static _nextAvailable = 8; } -Layers._nextAvailable = 8; - -// built-in layers, reserved up to (1 << 7) -Layers.Default = (1 << 0); -Layers.IgnoreRaycast = (1 << 1); -Layers.Gizmos = (1 << 2); -Layers.Editor = (1 << 3); - -// masks -Layers.All = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor]); -Layers.RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor, Layers.IgnoreRaycast]); - -export default Layers; cc.Layers = Layers; diff --git a/cocos/scene-graph/node-2d.js b/cocos/scene-graph/node-2d.js index b26011c840..1b277b416a 100644 --- a/cocos/scene-graph/node-2d.js +++ b/cocos/scene-graph/node-2d.js @@ -32,8 +32,9 @@ import eventManager from '../core/platform/event-manager/CCEventManager'; import macro from '../core/platform/CCMacro'; import * as js from '../core/utils/js'; import EventTarget from '../core/event/event-target'; -import BaseNode from './base-node'; +import { BaseNode } from './base-node'; import { ccclass, property } from '../core/data/class-decorator'; +import { vec3 } from '../core/vmath/index'; const Flags = cc.Object.Flags; const Destroying = Flags.Destroying; @@ -414,7 +415,7 @@ var _mouseWheelHandler = function (event) { } }; -function _searchMaskInParent (node) { +function _searchMaskInParent(node) { var Mask = cc.Mask; if (Mask) { var index = 0; @@ -430,7 +431,7 @@ function _searchMaskInParent (node) { return null; } -function _checkListeners (node, events) { +function _checkListeners(node, events) { if (!(node._objFlags & Destroying)) { var i = 0; if (node._bubblingListeners) { @@ -452,7 +453,7 @@ function _checkListeners (node, events) { return true; } -function _doDispatchEvent (owner, event) { +function _doDispatchEvent(owner, event) { var target, i; event.target = owner; @@ -522,47 +523,19 @@ if (CC_EDITOR) { * @class Node * @extends _BaseNode */ - @ccclass("cc.Node") -export default class Node extends BaseNode { +@ccclass("cc.NodeUI") +export default class NodeUI extends BaseNode { @property - _opacity = 255; - - @property - _color = cc.Color.WHITE; - - @property - _contentSize = new cc.Size(); - + _contentSize = new cc.Size(100, 100); @property _anchorPoint = cc.v2(0.5, 0.5); - @property - _position = cc.v3(); - + _lpos = cc.v3(); @property - _scaleX = 1.0; - + _lscale = cc.v3(1, 1, 1); @property - _scaleY = 1.0; - - @property - _scale = cc.v3(1, 1, 1); - - @property - _rotationX = 0.0; - - @property - _rotationY = 0.0; - - @property - _quat = new cc.Quat(); - - @property - _skewX = 0.0; - - @property - _skewY = 0.0; - + _lrot = cc.quat(); + _eulerAngles = cc.v3(); @property({ serializable: false }) @@ -571,8 +544,15 @@ export default class Node extends BaseNode { @property _zIndex = 0; - @property - _is3DNode = false; + // world transform + _pos = cc.v3(); + _rot = cc.quat(); + _scale = cc.v3(1, 1, 1); + _worldMatrix = cc.mat4(); + + _hasChanged = false; + _dirty = false; + _matDirty = false; // internal properties @@ -632,10 +612,10 @@ export default class Node extends BaseNode { */ @property get x() { - return this._position.x; + return this._lpos.x; } set x(value) { - var localPosition = this._position; + var localPosition = this._lpos; if (value !== localPosition.x) { if (!CC_EDITOR || isFinite(value)) { if (CC_EDITOR) { @@ -644,12 +624,13 @@ export default class Node extends BaseNode { localPosition.x = value; this.setLocalDirty(LocalDirtyFlag.POSITION); - + // this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; + // fast check event if (this._eventMask & POSITION_ON) { // send event if (CC_EDITOR) { - this.emit(EventType.POSITION_CHANGED, new cc.Vec2(oldValue, localPosition.y)); + this.emit(EventType.POSITION_CHANGED, new cc.Vec3(oldValue, localPosition.y, localPosition.z)); } else { this.emit(EventType.POSITION_CHANGED); @@ -673,10 +654,10 @@ export default class Node extends BaseNode { */ @property get y() { - return this._position.y; + return this._lpos.y; } set y(value) { - var localPosition = this._position; + var localPosition = this._lpos; if (value !== localPosition.y) { if (!CC_EDITOR || isFinite(value)) { if (CC_EDITOR) { @@ -685,12 +666,13 @@ export default class Node extends BaseNode { localPosition.y = value; this.setLocalDirty(LocalDirtyFlag.POSITION); + // this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; // fast check event if (this._eventMask & POSITION_ON) { // send event if (CC_EDITOR) { - this.emit(EventType.POSITION_CHANGED, new cc.Vec2(localPosition.x, oldValue)); + this.emit(EventType.POSITION_CHANGED, new cc.Vec3(localPosition.x, oldValue, localPosition.z)); } else { this.emit(EventType.POSITION_CHANGED); @@ -702,13 +684,13 @@ export default class Node extends BaseNode { } } } - + @property get z() { - return this._position.z; + return this._lpos.z; } set z(value) { - var localPosition = this._position; + var localPosition = this._lpos; if (value !== localPosition.z) { if (!CC_EDITOR || isFinite(value)) { localPosition.z = value; @@ -735,37 +717,35 @@ export default class Node extends BaseNode { */ @property get rotation() { - return this._rotationX; + // return this._rotationX; + return -this.eulerAngles; } set rotation(value) { - if (this._rotationX !== value || this._rotationY !== value) { - this._rotationX = this._rotationY = value; - // Update quaternion from rotation - math.quat.fromEuler(this._quat, 0, 0, -value); - this.setLocalDirty(LocalDirtyFlag.ROTATION); - - if (this._eventMask & ROTATION_ON) { - this.emit(EventType.ROTATION_CHANGED); - } - } + this.eulerAngles = -value; } /** - * !#en The rotation as Euler angles in degrees, used in 2.5D project. - * !#zh 该节点的欧拉角度,用于 2.5D 项目。 + * !#en + * Angle of node, the positive value is anti-clockwise direction. + * !#zh + * 该节点的旋转角度,正值为逆时针方向。 * @property eulerAngles - * @type {Vec3} + * @type {Number} */ @property get eulerAngles() { - return cc.v3(this._rotationX, this._rotationY, this._rotationZ); + return this._eulerAngles.z; } - set eulerAngles(v) { - this._rotationX = v.x; - this._rotationY = v.y; - this._rotationZ = v.z; - math.quat.fromEuler(this._quat, v.x, v.y, v.z); + + set eulerAngles(value) { + math.vec3.set(this._eulerAngles, 0, 0, value); + this._fromEuler(); this.setLocalDirty(LocalDirtyFlag.ROTATION); + // this._renderFlag |= RenderFlow.FLAG_TRANSFORM; + + if (this._eventMask & ROTATION_ON) { + this.emit(EventType.ROTATION_CHANGED); + } } /** @@ -779,19 +759,20 @@ export default class Node extends BaseNode { */ @property get rotationX() { - return this._rotationX; + return this._eulerAngles.x; } set rotationX(value) { - if (this._rotationX !== value) { - this._rotationX = value; + if (this._eulerAngles.x !== value) { + this._eulerAngles.x = value; // Update quaternion from rotation - if (this._rotationX === this._rotationY) { - math.quat.fromEuler(this._quat, 0, 0, -value); + if (this._eulerAngles.x === this._eulerAngles.y) { + math.quat.fromEuler(this._lrot, 0, 0, -value); } else { - math.quat.fromEuler(this._quat, value, this._rotationY, 0); + math.quat.fromEuler(this._lrot, value, this._eulerAngles.y, 0); } this.setLocalDirty(LocalDirtyFlag.ROTATION); + // this._renderFlag |= RenderFlow.FLAG_TRANSFORM; if (this._eventMask & ROTATION_ON) { this.emit(EventType.ROTATION_CHANGED); @@ -810,19 +791,20 @@ export default class Node extends BaseNode { */ @property get rotationY() { - return this._rotationY; + return this._eulerAngles.y; } set rotationY(value) { - if (this._rotationY !== value) { - this._rotationY = value; + if (this._eulerAngles.y !== value) { + this._eulerAngles.y = value; // Update quaternion from rotation - if (this._rotationX === this._rotationY) { - math.quat.fromEuler(this._quat, 0, 0, -value); + if (this._eulerAngles.x === this._eulerAngles.y) { + math.quat.fromEuler(this._lrot, 0, 0, -value); } else { - math.quat.fromEuler(this._quat, this._rotationX, value, 0); + math.quat.fromEuler(this._lrot, this._eulerAngles.x, value, 0); } this.setLocalDirty(LocalDirtyFlag.ROTATION); + // this._renderFlag |= RenderFlow.FLAG_TRANSFORM; if (this._eventMask & ROTATION_ON) { this.emit(EventType.ROTATION_CHANGED); @@ -850,12 +832,13 @@ export default class Node extends BaseNode { */ @property get scaleX() { - return this._scale.x; + return this._lscale.x; } set scaleX(value) { - if (this._scale.x !== value) { - this._scale.x = value; + if (this._lscale.x !== value) { + this._lscale.x = value; this.setLocalDirty(LocalDirtyFlag.SCALE); + // this._renderFlag |= RenderFlow.FLAG_TRANSFORM; if (this._eventMask & SCALE_ON) { this.emit(EventType.SCALE_CHANGED); @@ -872,14 +855,15 @@ export default class Node extends BaseNode { * node.scaleY = 0.5; * cc.log("Node Scale Y: " + node.scaleY); */ - @property + get scaleY() { - return this._scale.y; + return this._lscale.y; } set scaleY(value) { - if (this._scale.y !== value) { - this._scale.y = value; + if (this._lscale.y !== value) { + this._lscale.y = value; this.setLocalDirty(LocalDirtyFlag.SCALE); + // this._renderFlag |= RenderFlow.FLAG_TRANSFORM; if (this._eventMask & SCALE_ON) { this.emit(EventType.SCALE_CHANGED); @@ -896,14 +880,14 @@ export default class Node extends BaseNode { * node.skewX = 0; * cc.log("Node SkewX: " + node.skewX); */ - @property - get skewX() { - return this._skewX; - } - set skewX(value) { - this._skewX = value; - this.setLocalDirty(LocalDirtyFlag.SKEW); - } + // @property + // get skewX() { + // return this._skewX; + // } + // set skewX(value) { + // this._skewX = value; + // this.setLocalDirty(LocalDirtyFlag.SKEW); + // } /** * !#en Skew y @@ -914,14 +898,14 @@ export default class Node extends BaseNode { * node.skewY = 0; * cc.log("Node SkewY: " + node.skewY); */ - @property - get skewY() { - return this._skewY; - } - set skewY(value) { - this._skewY = value; - this.setLocalDirty(LocalDirtyFlag.SKEW); - } + // @property + // get skewY() { + // return this._skewY; + // } + // set skewY(value) { + // this._skewY = value; + // this.setLocalDirty(LocalDirtyFlag.SKEW); + // } /** * !#en Opacity of node, default value is 255. @@ -931,17 +915,17 @@ export default class Node extends BaseNode { * @example * node.opacity = 255; */ - @property({ - range: [0, 255, 1] - }) - get opacity() { - return this._opacity; - } - set opacity(value) { - if (this._opacity !== value) { - this._opacity = value; - } - } + // @property({ + // range: [0, 255, 1] + // }) + // get opacity() { + // return this._opacity; + // } + // set opacity(value) { + // if (this._opacity !== value) { + // this._opacity = value; + // } + // } /** * !#en Color of node, default value is white: (255, 255, 255). @@ -951,18 +935,18 @@ export default class Node extends BaseNode { * @example * node.color = new cc.Color(255, 255, 255); */ - @property - get color() { - return this._color.clone(); - } - set color(value) { - if (!this._color.equals(value)) { - this._color.set(value); - if (CC_DEV && value.a !== 255) { - cc.warnID(1626); - } - } - } + // @property + // get color() { + // return this._color.clone(); + // } + // set color(value) { + // if (!this._color.equals(value)) { + // this._color.set(value); + // if (CC_DEV && value.a !== 255) { + // cc.warnID(1626); + // } + // } + // } /** * !#en Anchor point's position on x axis. @@ -1114,7 +1098,7 @@ export default class Node extends BaseNode { static BuiltinGroupIndex = BuiltinGroupIndex; // is node but not scene - static isNode (obj) { + static isNode(obj) { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); } @@ -1123,10 +1107,10 @@ export default class Node extends BaseNode { * @method constructor * @param {String} [name] */ - constructor (name) { + constructor(name) { super(name); this._reorderChildDirty = false; - + // cache component this._widget = null; // fast render component access @@ -1140,24 +1124,25 @@ export default class Node extends BaseNode { this._mouseListener = null; // default scale - this._scale.x = 1; - this._scale.y = 1; - this._scale.z = 1; + this._lscale.x = 1; + this._lscale.y = 1; + this._lscale.z = 1; this._matrix = _mat4Pool.get(); this._worldMatrix = _mat4Pool.get(); this._localMatDirty = LocalDirtyFlag.ALL; this._worldMatDirty = true; + this._eventMask = 0; this._cullingMask = 1 << this.groupIndex; - this._rotationZ = 0; + // this._rotationZ = 0; } // OVERRIDES - _onSiblingIndexChanged (/*index*/) { + _onSiblingIndexChanged(/*index*/) { // update rendering scene graph, sort them by arrivalOrder var parent = this._parent; var siblings = parent._children; @@ -1170,7 +1155,7 @@ export default class Node extends BaseNode { parent._delaySort(); } - _onPreDestroy () { + _onPreDestroy() { var destroyByParent = this._onPreDestroyBase(); // Actions @@ -1216,7 +1201,7 @@ export default class Node extends BaseNode { } } - _onPostActivated (active) { + _onPostActivated(active) { var actionManager = ActionManagerExist ? cc.director.getActionManager() : null; if (active) { // ActionManager & EventManager @@ -1239,30 +1224,38 @@ export default class Node extends BaseNode { } } - _onHierarchyChanged (oldParent) { - this._updateOrderOfArrival(); - if (this._parent) { - this._parent._delaySort(); - } - this._onHierarchyChangedBase(oldParent); - if (cc._widgetManager) { - cc._widgetManager._nodesOrderDirty = true; - } - } + // _onHierarchyChanged(oldParent) { + // this._updateOrderOfArrival(); + // if (this._parent) { + // this._parent._delaySort(); + // } + // this._onHierarchyChangedBase(oldParent); + // if (cc._widgetManager) { + // cc._widgetManager._nodesOrderDirty = true; + // } + // } // INTERNAL - _upgrade_1x_to_2x () { + _toEuler() { + math.quat.toEuler(this._eulerAngles, this._lrot); + } + + _fromEuler() { + math.quat.fromEuler(this._lrot, this._eulerAngles.x, this._eulerAngles.y, this._eulerAngles.z); + } + + _upgrade_1x_to_2x() { // Upgrade scaleX, scaleY from v1.x // TODO: remove in future version, 3.0 ? - if (this._scaleX !== undefined) { - this._scale.x = this._scaleX; - this._scaleX = undefined; - } - if (this._scaleY !== undefined) { - this._scale.y = this._scaleY; - this._scaleY = undefined; - } + // if (this._scaleX !== undefined) { + // this._lscale.x = this._scaleX; + // this._scaleX = undefined; + // } + // if (this._scaleY !== undefined) { + // this._lscale.y = this._scaleY; + // this._scaleY = undefined; + // } if (this._localZOrder !== 0) { this._zIndex = (this._localZOrder & 0xffff0000) >> 16; @@ -1271,39 +1264,32 @@ export default class Node extends BaseNode { // TODO: remove _rotationX & _rotationY in future version, 3.0 ? // Update quaternion from rotation, when upgrade from 1.x to 2.0 // If rotation x & y is 0 in old version, then update rotation from default quaternion is ok too - if (this._rotationX !== 0 || this._rotationY !== 0) { + let quat = this._lrot; + if ((this._rotationX || this._rotationY) && + (quat.x === 0 && quat.y === 0 && quat.z === 0 && quat.w === 1)) { if (this._rotationX === this._rotationY) { - math.quat.fromEuler(this._quat, 0, 0, -this._rotationX); + math.quat.fromEuler(quat, 0, 0, -this._rotationX); } else { - math.quat.fromEuler(this._quat, this._rotationX, this._rotationY, 0); - } - } - // Update rotation from quaternion - else { - let rotx = this._quat.getRoll(); - let roty = this._quat.getPitch(); - if (rotx === 0 && roty === 0) { - this._rotationX = this._rotationY = -this._quat.getYaw(); - } - else { - this._rotationX = rotx; - this._rotationY = roty; + math.quat.fromEuler(quat, this._rotationX, this._rotationY, 0); } + this._rotationX = this._rotationY = undefined; } + this._toEuler(); + // Upgrade from 2.0.0 preview 4 & earlier versions // TODO: Remove after final version - if (this._color.a < 255 && this._opacity === 255) { - this._opacity = this._color.a; - this._color.a = 255; - } + // if (this._color.a < 255 && this._opacity === 255) { + // this._opacity = this._color.a; + // this._color.a = 255; + // } } /* * The initializer for Node which will be called before all components onLoad */ - _onBatchCreated () { + _onBatchCreated() { this._upgrade_1x_to_2x(); this._updateOrderOfArrival(); @@ -1329,15 +1315,19 @@ export default class Node extends BaseNode { for (let i = 0, len = children.length; i < len; i++) { children[i]._onBatchCreated(); } + + // if (children.length > 0) { + // this._renderFlag |= RenderFlow.FLAG_CHILDREN; + // } } // the same as _onBatchCreated but untouch prefab - _onBatchRestored () { + _onBatchRestored() { this._upgrade_1x_to_2x(); if (!this._activeInHierarchy) { // deactivate ActionManager and EventManager by default - + // ActionManager may not be inited in the editor worker. let manager = cc.director.getActionManager(); manager && manager.pauseTarget(this); @@ -1349,11 +1339,15 @@ export default class Node extends BaseNode { for (var i = 0, len = children.length; i < len; i++) { children[i]._onBatchRestored(); } + + // if (children.length > 0) { + // this._renderFlag |= RenderFlow.FLAG_CHILDREN; + // } } // EVENT TARGET - _checknSetupSysEvent (type) { + _checknSetupSysEvent(type) { let newAdded = false; let forDispatch = false; if (_touchEvents.indexOf(type) !== -1) { @@ -1445,7 +1439,7 @@ export default class Node extends BaseNode { * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this); * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback); */ - on (type, callback, target, useCapture) { + on(type, callback, target, useCapture) { let forDispatch = this._checknSetupSysEvent(type); if (forDispatch) { return this._onDispatch(type, callback, target, useCapture); @@ -1453,20 +1447,20 @@ export default class Node extends BaseNode { else { switch (type) { case EventType.POSITION_CHANGED: - this._eventMask |= POSITION_ON; - break; + this._eventMask |= POSITION_ON; + break; case EventType.SCALE_CHANGED: - this._eventMask |= SCALE_ON; - break; + this._eventMask |= SCALE_ON; + break; case EventType.ROTATION_CHANGED: - this._eventMask |= ROTATION_ON; - break; + this._eventMask |= ROTATION_ON; + break; case EventType.SIZE_CHANGED: - this._eventMask |= SIZE_ON; - break; + this._eventMask |= SIZE_ON; + break; case EventType.ANCHOR_CHANGED: - this._eventMask |= ANCHOR_ON; - break; + this._eventMask |= ANCHOR_ON; + break; } if (!this._bubblingListeners) { this._bubblingListeners = new EventTarget(); @@ -1497,7 +1491,7 @@ export default class Node extends BaseNode { * @example * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback); */ - once (type, callback, target, useCapture) { + once(type, callback, target, useCapture) { let forDispatch = this._checknSetupSysEvent(type); let eventType_hasOnceListener = '__ONCE_FLAG:' + type; @@ -1522,7 +1516,7 @@ export default class Node extends BaseNode { } } - _onDispatch (type, callback, target, useCapture) { + _onDispatch(type, callback, target, useCapture) { // Accept also patameters like: (type, callback, useCapture) if (typeof target === 'boolean') { useCapture = target; @@ -1542,7 +1536,7 @@ export default class Node extends BaseNode { listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget(); } - if ( !listeners.hasEventListener(type, callback, target) ) { + if (!listeners.hasEventListener(type, callback, target)) { listeners.add(type, callback, target); if (target && target.__eventTargets) @@ -1567,7 +1561,7 @@ export default class Node extends BaseNode { * node.off(cc.Node.EventType.TOUCH_START, callback, this.node); * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this); */ - off (type, callback, target, useCapture) { + off(type, callback, target, useCapture) { let touchEvent = _touchEvents.indexOf(type) !== -1; let mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1; if (touchEvent || mouseEvent) { @@ -1594,26 +1588,26 @@ export default class Node extends BaseNode { if (!hasListeners) { switch (type) { case EventType.POSITION_CHANGED: - this._eventMask &= ~POSITION_ON; - break; + this._eventMask &= ~POSITION_ON; + break; case EventType.SCALE_CHANGED: - this._eventMask &= ~SCALE_ON; - break; + this._eventMask &= ~SCALE_ON; + break; case EventType.ROTATION_CHANGED: - this._eventMask &= ~ROTATION_ON; - break; + this._eventMask &= ~ROTATION_ON; + break; case EventType.SIZE_CHANGED: - this._eventMask &= ~SIZE_ON; - break; + this._eventMask &= ~SIZE_ON; + break; case EventType.ANCHOR_CHANGED: - this._eventMask &= ~ANCHOR_ON; - break; + this._eventMask &= ~ANCHOR_ON; + break; } } } } - _offDispatch (type, callback, target, useCapture) { + _offDispatch(type, callback, target, useCapture) { // Accept also patameters like: (type, callback, useCapture) if (typeof target === 'boolean') { useCapture = target; @@ -1628,12 +1622,12 @@ export default class Node extends BaseNode { var listeners = useCapture ? this._capturingListeners : this._bubblingListeners; if (listeners) { listeners.remove(type, callback, target); - + if (target && target.__eventTargets) { js.array.fastRemove(target.__eventTargets, this); } } - + } } @@ -1645,7 +1639,7 @@ export default class Node extends BaseNode { * @example * node.targetOff(target); */ - targetOff (target) { + targetOff(target) { let listeners = this._bubblingListeners; if (listeners) { listeners.targetOff(target); @@ -1688,7 +1682,7 @@ export default class Node extends BaseNode { * @param {String} type - The type of event. * @return {Boolean} True if a callback of the specified type is registered; false otherwise. */ - hasEventListener (type) { + hasEventListener(type) { let has = false; if (this._bubblingListeners) { has = this._bubblingListeners.hasEventListener(type); @@ -1713,11 +1707,11 @@ export default class Node extends BaseNode { * @param {*} [arg4] - Fourth argument in callback * @param {*} [arg5] - Fifth argument in callback * @example - * + * * eventTarget.emit('fire', event); * eventTarget.emit('fire', message, emitter); */ - emit (type, arg1, arg2, arg3, arg4, arg5) { + emit(type, arg1, arg2, arg3, arg4, arg5) { if (this._bubblingListeners) { this._bubblingListeners.emit(type, arg1, arg2, arg3, arg4, arg5); } @@ -1732,7 +1726,7 @@ export default class Node extends BaseNode { * @method dispatchEvent * @param {Event} event - The Event object that is dispatched into the event flow */ - dispatchEvent (event) { + dispatchEvent(event) { _doDispatchEvent(this, event); _cachedArray.length = 0; } @@ -1749,7 +1743,7 @@ export default class Node extends BaseNode { * @example * node.pauseSystemEvents(true); */ - pauseSystemEvents (recursive) { + pauseSystemEvents(recursive) { eventManager.pauseTarget(this, recursive); } @@ -1765,24 +1759,50 @@ export default class Node extends BaseNode { * @example * node.resumeSystemEvents(true); */ - resumeSystemEvents (recursive) { + resumeSystemEvents(recursive) { eventManager.resumeTarget(this, recursive); } - _hitTest (point, listener) { + _hitTest(point, listener) { let w = this._contentSize.width, h = this._contentSize.height, cameraPt = _vec2a, testPt = _vec2b; - - let camera = cc.Camera.findCamera(this); - if (camera) { - camera.getCameraToWorldPoint(point, cameraPt); + + let renderComp = this.getComponent(cc.RenderComponent); + if (!renderComp) { + return false; } - else { - cameraPt.set(point); + let canvas = cc.CanvasComponent.findView(renderComp); + if (!canvas) { + return; } + canvas.node.getWorldRT(_mat4_temp); + + let m12 = _mat4_temp.m12; + let m13 = _mat4_temp.m13; + + let center = cc.visibleRect.center; + // let size = cc.view.getFrameSize(); + // let center = cc.v2(size.width / 2, size.height / 2); + // let center = cc.v2(cc.game._renderer._device._gl.canvas.width / 2, cc.game._renderer._device._gl.canvas.height / 2); + _mat4_temp.m12 = center.x - (_mat4_temp.m00 * m12 + _mat4_temp.m04 * m13); + _mat4_temp.m13 = center.y - (_mat4_temp.m01 * m12 + _mat4_temp.m05 * m13); + + // if (out !== _mat4_temp) { + // mat4.copy(out, _mat4_temp); + // } + math.mat4.invert(_mat4_temp, _mat4_temp); + math.vec2.transformMat4(cameraPt, point, _mat4_temp); + // let camera = cc.Camera.findCamera(this); + // if (camera) { + // camera.getCameraToWorldPoint(point, cameraPt); + // } + // else { + // cameraPt.set(point); + // } + this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); @@ -1825,7 +1845,7 @@ export default class Node extends BaseNode { * @param {Array} array - the array to receive targets * @example {@link cocos2d/core/event/_getCapturingTargets.js} */ - _getCapturingTargets (type, array) { + _getCapturingTargets(type, array) { var parent = this.parent; while (parent) { if (parent._capturingListeners && parent._capturingListeners.hasEventListener(type)) { @@ -1834,7 +1854,7 @@ export default class Node extends BaseNode { parent = parent.parent; } } - + /** * Get all the targets listening to the supplied type of event in the target's bubbling phase. * The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree. @@ -1846,7 +1866,7 @@ export default class Node extends BaseNode { * @param {String} type - the event type * @param {Array} array - the array to receive targets */ - _getBubblingTargets (type, array) { + _getBubblingTargets(type, array) { var parent = this.parent; while (parent) { if (parent._bubblingListeners && parent._bubblingListeners.hasEventListener(type)) { @@ -1856,7 +1876,7 @@ export default class Node extends BaseNode { } } -// TRANSFORM RELATED + // TRANSFORM RELATED /** * !#en Returns a copy of the position (x, y) of the node in its parent's coordinates. * !#zh 获取节点在父节点坐标系中的位置(x, y)。 @@ -1865,8 +1885,8 @@ export default class Node extends BaseNode { * @example * cc.log("Node Position: " + node.getPosition()); */ - getPosition () { - return new cc.Vec2(this._position); + getPosition() { + return new cc.Vec2(this._lpos); } /** @@ -1884,7 +1904,7 @@ export default class Node extends BaseNode { * @param {Number} [y] - Y coordinate for position * @example {@link cocos2d/core/utils/base-node/setPosition.js} */ - setPosition (newPosOrX, y) { + setPosition(newPosOrX, y) { var x; if (y === undefined) { x = newPosOrX.x; @@ -1894,7 +1914,7 @@ export default class Node extends BaseNode { x = newPosOrX; } - var locPosition = this._position; + var locPosition = this._lpos; if (locPosition.x === x && locPosition.y === y) { return; } @@ -1911,7 +1931,7 @@ export default class Node extends BaseNode { if (!CC_EDITOR || isFinite(y)) { locPosition.y = y; } - else { + else { return cc.error(ERR_INVALID_NUMBER, 'y of new position'); } this.setLocalDirty(LocalDirtyFlag.POSITION); @@ -1938,10 +1958,10 @@ export default class Node extends BaseNode { * @example * cc.log("Node Scale: " + node.getScale()); */ - getScale () { - if (this._scale.x !== this._scale.y) + getScale() { + if (this._lscale.x !== this._lscale.y) cc.logID(1603); - return this._scale.x; + return this._lscale.x; } /** @@ -1954,7 +1974,7 @@ export default class Node extends BaseNode { * node.setScale(cc.v2(1, 1)); * node.setScale(1); */ - setScale (x, y) { + setScale(x, y) { if (x && typeof x !== 'number') { y = x.y; x = x.x; @@ -1962,9 +1982,9 @@ export default class Node extends BaseNode { else if (y === undefined) { y = x; } - if (this._scale.x !== x || this._scale.y !== y) { - this._scale.x = x; - this._scale.y = y; + if (this._lscale.x !== x || this._lscale.y !== y) { + this._lscale.x = x; + this._lscale.y = y; this.setLocalDirty(LocalDirtyFlag.SCALE); if (this._eventMask & SCALE_ON) { @@ -1998,7 +2018,7 @@ export default class Node extends BaseNode { * @example * cc.log("Content Size: " + node.getContentSize()); */ - getContentSize () { + getContentSize() { return cc.size(this._contentSize.width, this._contentSize.height); } @@ -2015,7 +2035,7 @@ export default class Node extends BaseNode { * node.setContentSize(cc.size(100, 100)); * node.setContentSize(100, 100); */ - setContentSize (size, height) { + setContentSize(size, height) { var locContentSize = this._contentSize; var clone; if (height === undefined) { @@ -2065,7 +2085,7 @@ export default class Node extends BaseNode { * @example * cc.log("Node AnchorPoint: " + node.getAnchorPoint()); */ - getAnchorPoint () { + getAnchorPoint() { return cc.v2(this._anchorPoint); } @@ -2091,7 +2111,7 @@ export default class Node extends BaseNode { * node.setAnchorPoint(cc.v2(1, 1)); * node.setAnchorPoint(1, 1); */ - setAnchorPoint (point, y) { + setAnchorPoint(point, y) { var locAnchorPoint = this._anchorPoint; if (y === undefined) { if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y)) @@ -2116,7 +2136,7 @@ export default class Node extends BaseNode { * @param {Vec3} out * @param {Vec3} vec3 */ - _invTransformPoint (out, pos) { + _invTransformPoint(out, pos) { if (this._parent) { this._parent._invTransformPoint(out, pos); } else { @@ -2124,36 +2144,36 @@ export default class Node extends BaseNode { } // out = parent_inv_pos - pos - math.vec3.sub(out, out, this._position); + math.vec3.sub(out, out, this._lpos); // out = inv(rot) * out - math.quat.conjugate(_quat_temp, this._quat); + math.quat.conjugate(_quat_temp, this._lrot); math.vec3.transformQuat(out, out, _quat_temp); // out = (1/scale) * out - math.vec3.inverseSafe(_vec3_temp, this._scale); + math.vec3.inverseSafe(_vec3_temp, this._lscale); math.vec3.mul(out, out, _vec3_temp); return out; } - + /* * Calculate and return world position. * This is not a public API yet, its usage could be updated - * @method getWorldPos + * @method getWorldPosition * @param {Vec3} out * @return {Vec3} */ - getWorldPos (out) { - math.vec3.copy(out, this._position); + getWorldPosition(out) { + math.vec3.copy(out, this._lpos); let curr = this._parent; while (curr) { - // out = parent_scale * pos - math.vec3.mul(out, out, curr._scale); + // out = parent_lscale * pos + math.vec3.mul(out, out, curr._lscale); // out = parent_quat * out - math.vec3.transformQuat(out, out, curr._quat); + math.vec3.transformQuat(out, out, curr._lrot); // out = out + pos - math.vec3.add(out, out, curr._position); + math.vec3.add(out, out, curr._lpos); curr = curr._parent; } return out; @@ -2162,16 +2182,16 @@ export default class Node extends BaseNode { /* * Set world position. * This is not a public API yet, its usage could be updated - * @method setWorldPos + * @method setWorldPosition * @param {vec3} pos */ - setWorldPos (pos) { + setWorldPosition(pos) { // NOTE: this is faster than invert world matrix and transform the point if (this._parent) { - this._parent._invTransformPoint(this._position, pos); + this._parent._invTransformPoint(this._lpos, pos); } else { - math.vec3.copy(this._position, pos); + math.vec3.copy(this._lpos, pos); } this.setLocalDirty(LocalDirtyFlag.POSITION); @@ -2190,15 +2210,15 @@ export default class Node extends BaseNode { /* * Calculate and return world rotation * This is not a public API yet, its usage could be updated - * @method getWorldRot + * @method getWorldRotation * @param {Quat} out * @return {Quat} */ - getWorldRot (out) { - math.quat.copy(out, this._quat); + getWorldRotation(out) { + math.quat.copy(out, this._lrot); let curr = this._parent; while (curr) { - math.quat.mul(out, curr._quat, out); + math.quat.mul(out, curr._lrot, out); curr = curr._parent; } return out; @@ -2207,41 +2227,40 @@ export default class Node extends BaseNode { /* * Set world rotation with quaternion * This is not a public API yet, its usage could be updated - * @method setWorldRot + * @method setWorldRotation * @param {Quat} rot */ - setWorldRot (quat) { + setWorldRotation(quat) { if (this._parent) { - this._parent.getWorldRot(this._quat); - math.quat.conjugate(this._quat, this._quat); - math.quat.mul(this._quat, this._quat, quat); + this._parent.getWorldRotation(this._lrot); + math.quat.conjugate(this._lrot, this._lrot); + math.quat.mul(this._lrot, this._lrot, quat); } else { - math.quat.copy(this._quat, quat); + math.quat.copy(this._lrot, quat); } this.setLocalDirty(LocalDirtyFlag.ROTATION); } - getWorldRT (out) { + getWorldRT(out) { let opos = _vec3_temp; let orot = _quat_temp; - math.vec3.copy(opos, this._position); - math.quat.copy(orot, this._quat); + math.vec3.copy(opos, this._lpos); + math.quat.copy(orot, this._lrot); let curr = this._parent; while (curr) { // opos = parent_lscale * lpos math.vec3.mul(opos, opos, curr._scale); // opos = parent_lrot * opos - math.vec3.transformQuat(opos, opos, curr._quat); + math.vec3.transformQuat(opos, opos, curr._lrot); // opos = opos + lpos - math.vec3.add(opos, opos, curr._position); + math.vec3.add(opos, opos, curr._lpos); // orot = lrot * orot - math.quat.mul(orot, curr._quat, orot); + math.quat.mul(orot, curr._lrot, orot); curr = curr._parent; } math.mat4.fromRT(out, orot, opos); - return out; } /** @@ -2251,29 +2270,51 @@ export default class Node extends BaseNode { * @param {Vec3} pos * @param {Vec3} [up] - default is (0,1,0) */ - lookAt (pos, up) { - this.getWorldPos(_vec3_temp); + lookAt(pos, up) { + this.getWorldPosition(_vec3_temp); math.vec3.sub(_vec3_temp, _vec3_temp, pos); // NOTE: we use -z for view-dir math.vec3.normalize(_vec3_temp, _vec3_temp); math.quat.fromViewUp(_quat_temp, _vec3_temp, up); - - this.setWorldRot(_quat_temp); + + this.setWorldRotation(_quat_temp); } - _updateLocalMatrix () { + resetHasChanged() { + this._hasChanged = false; + let len = this._children.length; + for (let i = 0; i < len; ++i) { + this._children[i].resetHasChanged(); + } + } + + /** + * invalidate the world transform information + * for this node and all its children recursively + */ + invalidateChildren() { + if (this._dirty && this._hasChanged) return; + this._dirty = this._hasChanged = true; + + let len = this._children.length; + for (let i = 0; i < len; ++i) { + this._children[i].invalidateChildren(); + } + } + + _updateLocalMatrix() { let dirtyFlag = this._localMatDirty; if (!dirtyFlag) return; // Update transform let t = this._matrix; - //math.mat4.fromRTS(t, this._quat, this._position, this._scale); + //math.mat4.fromRTS(t, this._lrot, this._lpos, this._lscale); if (dirtyFlag & (LocalDirtyFlag.RT | LocalDirtyFlag.SKEW)) { let hasRotation = this._rotationX || this._rotationY; - let hasSkew = this._skewX || this._skewY; - let sx = this._scale.x, sy = this._scale.y; + // let hasSkew = this._skewX || this._skewY; + let sx = this._lscale.x, sy = this._lscale.y; - if (hasRotation || hasSkew) { + if (hasRotation /*|| hasSkew*/) { let a = 1, b = 0, c = 0, d = 1; // rotation if (hasRotation) { @@ -2296,19 +2337,19 @@ export default class Node extends BaseNode { t.m04 = c *= sy; t.m05 = d *= sy; // skew - if (hasSkew) { - let a = t.m00, b = t.m01, c = t.m04, d = t.m05; - let skx = Math.tan(this._skewX * ONE_DEGREE); - let sky = Math.tan(this._skewY * ONE_DEGREE); - if (skx === Infinity) - skx = 99999999; - if (sky === Infinity) - sky = 99999999; - t.m00 = a + c * sky; - t.m01 = b + d * sky; - t.m04 = c + a * skx; - t.m05 = d + b * skx; - } + // if (hasSkew) { + // let a = t.m00, b = t.m01, c = t.m04, d = t.m05; + // let skx = Math.tan(this._skewX * ONE_DEGREE); + // let sky = Math.tan(this._skewY * ONE_DEGREE); + // if (skx === Infinity) + // skx = 99999999; + // if (sky === Infinity) + // sky = 99999999; + // t.m00 = a + c * sky; + // t.m01 = b + d * sky; + // t.m04 = c + a * skx; + // t.m05 = d + b * skx; + // } } else { t.m00 = sx; @@ -2319,20 +2360,20 @@ export default class Node extends BaseNode { } // position - t.m12 = this._position.x; - t.m13 = this._position.y; - + t.m12 = this._lpos.x; + t.m13 = this._lpos.y; + this._localMatDirty = 0; // Register dirty status of world matrix so that it can be recalculated this._worldMatDirty = true; } - _calculWorldMatrix () { + _calculWorldMatrix() { // Avoid as much function call as possible if (this._localMatDirty) { this._updateLocalMatrix(); } - + // Assume parent world matrix is correct let parent = this._parent; if (parent) { @@ -2344,9 +2385,9 @@ export default class Node extends BaseNode { this._worldMatDirty = false; } - _mulMat (out, a, b) { - let aa=a.m00, ab=a.m01, ac=a.m04, ad=a.m05, atx=a.m12, aty=a.m13; - let ba=b.m00, bb=b.m01, bc=b.m04, bd=b.m05, btx=b.m12, bty=b.m13; + _mulMat(out, a, b) { + let aa = a.m00, ab = a.m01, ac = a.m04, ad = a.m05, atx = a.m12, aty = a.m13; + let ba = b.m00, bb = b.m01, bc = b.m04, bd = b.m05, btx = b.m12, bty = b.m13; if (ab !== 0 || ac !== 0) { out.m00 = ba * aa + bb * ac; out.m01 = ba * ab + bb * ad; @@ -2365,7 +2406,7 @@ export default class Node extends BaseNode { } } - _updateWorldMatrix () { + _updateWorldMatrix() { if (this._parent) { this._parent._updateWorldMatrix(); } @@ -2379,12 +2420,12 @@ export default class Node extends BaseNode { } } - setLocalDirty (flag) { + setLocalDirty(flag) { this._localMatDirty = this._localMatDirty | flag; this._worldMatDirty = true; } - setWorldDirty () { + setWorldDirty() { this._worldMatDirty = true; } @@ -2399,11 +2440,11 @@ export default class Node extends BaseNode { * let mat4 = cc.mat4(); * node.getLocalMatrix(mat4); */ - getLocalMatrix (out) { + getLocalMatrix(out) { this._updateLocalMatrix(); return math.mat4.copy(out, this._matrix); } - + /** * !#en * Get the world transform matrix (4x4) @@ -2415,9 +2456,14 @@ export default class Node extends BaseNode { * let mat4 = cc.mat4(); * node.getWorldMatrix(mat4); */ - getWorldMatrix (out) { + getWorldMatrix(out) { this._updateWorldMatrix(); - return math.mat4.copy(out, this._worldMatrix); + + if (out) { + return math.mat4.copy(out, this._worldMatrix); + } else { + return math.mat4.copy(cc.mat4(), this._worldMatrix); + } } /** @@ -2433,7 +2479,7 @@ export default class Node extends BaseNode { * @example * var newVec2 = node.convertToNodeSpace(cc.v2(100, 100)); */ - convertToNodeSpace (worldPoint) { + convertToNodeSpace(worldPoint) { this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); let out = new cc.Vec2(); @@ -2454,7 +2500,7 @@ export default class Node extends BaseNode { * @example * var newVec2 = node.convertToWorldSpace(cc.v2(100, 100)); */ - convertToWorldSpace (nodePoint) { + convertToWorldSpace(nodePoint) { this._updateWorldMatrix(); let out = new cc.Vec2( nodePoint.x - this._anchorPoint.x * this._contentSize.width, @@ -2474,7 +2520,7 @@ export default class Node extends BaseNode { * @example * var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100)); */ - convertToNodeSpaceAR (worldPoint) { + convertToNodeSpaceAR(worldPoint) { this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); let out = new cc.Vec2(); @@ -2492,13 +2538,13 @@ export default class Node extends BaseNode { * @example * var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100)); */ - convertToWorldSpaceAR (nodePoint) { + convertToWorldSpaceAR(nodePoint) { this._updateWorldMatrix(); let out = new cc.Vec2(); return math.vec2.transformMat4(out, nodePoint, this._worldMatrix); } -// OLD TRANSFORM ACCESS APIs + // OLD TRANSFORM ACCESS APIs /** * !#en * Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
@@ -2512,12 +2558,12 @@ export default class Node extends BaseNode { * let affineTransform = cc.AffineTransform.create(); * node.getNodeToParentTransform(affineTransform); */ - getNodeToParentTransform (out) { + getNodeToParentTransform(out) { if (!out) { out = AffineTrans.identity(); } this._updateLocalMatrix(); - + var contentSize = this._contentSize; _vec3_temp.x = -this._anchorPoint.x * contentSize.width; _vec3_temp.y = -this._anchorPoint.y * contentSize.height; @@ -2544,7 +2590,7 @@ export default class Node extends BaseNode { * let affineTransform = cc.AffineTransform.create(); * node.getNodeToParentTransformAR(affineTransform); */ - getNodeToParentTransformAR (out) { + getNodeToParentTransformAR(out) { if (!out) { out = AffineTrans.identity(); } @@ -2563,12 +2609,12 @@ export default class Node extends BaseNode { * let affineTransform = cc.AffineTransform.create(); * node.getNodeToWorldTransform(affineTransform); */ - getNodeToWorldTransform (out) { + getNodeToWorldTransform(out) { if (!out) { out = AffineTrans.identity(); } this._updateWorldMatrix(); - + var contentSize = this._contentSize; _vec3_temp.x = -this._anchorPoint.x * contentSize.width; _vec3_temp.y = -this._anchorPoint.y * contentSize.height; @@ -2594,7 +2640,7 @@ export default class Node extends BaseNode { * let affineTransform = cc.AffineTransform.create(); * node.getNodeToWorldTransformAR(affineTransform); */ - getNodeToWorldTransformAR (out) { + getNodeToWorldTransformAR(out) { if (!out) { out = AffineTrans.identity(); } @@ -2617,7 +2663,7 @@ export default class Node extends BaseNode { * let affineTransform = cc.AffineTransform.create(); * node.getParentToNodeTransform(affineTransform); */ - getParentToNodeTransform (out) { + getParentToNodeTransform(out) { if (!out) { out = AffineTrans.identity(); } @@ -2637,7 +2683,7 @@ export default class Node extends BaseNode { * let affineTransform = cc.AffineTransform.create(); * node.getWorldToNodeTransform(affineTransform); */ - getWorldToNodeTransform (out) { + getWorldToNodeTransform(out) { if (!out) { out = AffineTrans.identity(); } @@ -2656,7 +2702,7 @@ export default class Node extends BaseNode { * @example * var newVec2 = node.convertTouchToNodeSpace(touch); */ - convertTouchToNodeSpace (touch) { + convertTouchToNodeSpace(touch) { return this.convertToNodeSpace(touch.getLocation()); } @@ -2670,10 +2716,10 @@ export default class Node extends BaseNode { * @example * var newVec2 = node.convertTouchToNodeSpaceAR(touch); */ - convertTouchToNodeSpaceAR (touch) { + convertTouchToNodeSpaceAR(touch) { return this.convertToNodeSpaceAR(touch.getLocation()); } - + /** * !#en * Returns a "local" axis aligned bounding box of the node.
@@ -2684,14 +2730,14 @@ export default class Node extends BaseNode { * @example * var boundingBox = node.getBoundingBox(); */ - getBoundingBox () { + getBoundingBox() { this._updateLocalMatrix(); let width = this._contentSize.width; let height = this._contentSize.height; let rect = cc.rect( - -this._anchorPoint.x * width, - -this._anchorPoint.y * height, - width, + -this._anchorPoint.x * width, + -this._anchorPoint.y * height, + width, height); return rect.transformMat4(rect, this._matrix); } @@ -2708,7 +2754,7 @@ export default class Node extends BaseNode { * @example * var newRect = node.getBoundingBoxToWorld(); */ - getBoundingBoxToWorld () { + getBoundingBoxToWorld() { if (this._parent) { this._parent._updateWorldMatrix(); return this._getBoundingBoxTo(this._parent._worldMatrix); @@ -2718,14 +2764,14 @@ export default class Node extends BaseNode { } } - _getBoundingBoxTo (parentMat) { + _getBoundingBoxTo(parentMat) { this._updateLocalMatrix(); let width = this._contentSize.width; let height = this._contentSize.height; let rect = cc.rect( - -this._anchorPoint.x * width, - -this._anchorPoint.y * height, - width, + -this._anchorPoint.x * width, + -this._anchorPoint.y * height, + width, height); var pMat = math.mat4.mul(this._worldMatrix, parentMat, this._matrix); @@ -2747,40 +2793,40 @@ export default class Node extends BaseNode { return rect; } - _updateOrderOfArrival () { + _updateOrderOfArrival() { var arrivalOrder = ++_globalOrderOfArrival; this._localZOrder = (this._localZOrder & 0xffff0000) | arrivalOrder; } - /** - * !#en - * Adds a child to the node with z order and name. - * !#zh - * 添加子节点,并且可以修改该节点的 局部 Z 顺序和名字。 - * @method addChild - * @param {Node} child - A child node - * @param {Number} [zIndex] - Z order for drawing priority. Please refer to zIndex property - * @param {String} [name] - A name to identify the node easily. Please refer to name property - * @example - * node.addChild(newNode, 1, "node"); - */ - addChild (child, zIndex, name) { - if (CC_DEV && !cc.Node.isNode(child)) { - return cc.errorID(1634, cc.js.getClassName(child)); - } - cc.assertID(child, 1606); - cc.assertID(child._parent === null, 1605); + // /** + // * !#en + // * Adds a child to the node with z order and name. + // * !#zh + // * 添加子节点,并且可以修改该节点的 局部 Z 顺序和名字。 + // * @method addChild + // * @param {Node} child - A child node + // * @param {Number} [zIndex] - Z order for drawing priority. Please refer to zIndex property + // * @param {String} [name] - A name to identify the node easily. Please refer to name property + // * @example + // * node.addChild(newNode, 1, "node"); + // */ + // addChild(child, zIndex, name) { + // if (CC_DEV && !cc.Node.isNode(child)) { + // return cc.errorID(1634, cc.js.getClassName(child)); + // } + // cc.assertID(child, 1606); + // cc.assertID(child._parent === null, 1605); - // invokes the parent setter - child.parent = this; + // // invokes the parent setter + // child.parent = this; - if (zIndex !== undefined) { - child.zIndex = zIndex; - } - if (name !== undefined) { - child.name = name; - } - } + // if (zIndex !== undefined) { + // child.zIndex = zIndex; + // } + // if (name !== undefined) { + // child.name = name; + // } + // } /** * !#en Stops all running actions and schedulers. @@ -2789,7 +2835,7 @@ export default class Node extends BaseNode { * @example * node.cleanup(); */ - cleanup () { + cleanup() { // actions ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this); // event @@ -2811,7 +2857,7 @@ export default class Node extends BaseNode { * * @method sortAllChildren */ - sortAllChildren () { + sortAllChildren() { if (this._reorderChildDirty) { this._reorderChildDirty = false; var _children = this._children; @@ -2839,14 +2885,14 @@ export default class Node extends BaseNode { } } - _delaySort () { + _delaySort() { if (!this._reorderChildDirty) { this._reorderChildDirty = true; cc.director.__fastOn(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); } } - _restoreProperties () { + _restoreProperties() { /* * TODO: Refine this code after completing undo/redo 2.0. * The node will be destroyed when deleting in the editor, @@ -2862,6 +2908,7 @@ export default class Node extends BaseNode { this._localMatDirty = LocalDirtyFlag.ALL; this._worldMatDirty = true; + if (this._renderComponent) { if (this._renderComponent.enabled) { this._renderComponent.markForUpdateRenderData(true); @@ -2894,9 +2941,9 @@ if (CC_EDITOR) { // 3D Node Property /** - * !en + * !en * Switch 2D/3D node. The 2D nodes will run faster. - * !zh + * !zh * 切换 2D/3D 节点,2D 节点会有更高的运行效率 * @property {Boolean} is3DNode * @default false @@ -3019,4 +3066,4 @@ js.getset(_p, 'rotation', _p.getRotation, _p.setRotation); js.getset(_p, 'position', _p.getPosition, _p.setPosition, false, true); js.getset(_p, 'scale', _p.getScale, _p.setScale, false, true); -cc.Node2D = Node; +cc.NodeUI = NodeUI; diff --git a/cocos/scene-graph/node-activator.js b/cocos/scene-graph/node-activator.js index 907826095f..aa6443538b 100644 --- a/cocos/scene-graph/node-activator.js +++ b/cocos/scene-graph/node-activator.js @@ -25,7 +25,7 @@ ****************************************************************************/ import ComponentScheduler from './component-scheduler'; -import CCObject from '../core/data/object'; +import { CCObject } from '../core/data/object'; import { Pool, array } from '../core/utils/js'; import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; diff --git a/cocos/scene-graph/node.js b/cocos/scene-graph/node.js deleted file mode 100644 index 1767b63fce..0000000000 --- a/cocos/scene-graph/node.js +++ /dev/null @@ -1,493 +0,0 @@ -import { vec3, mat4, quat } from '../core/vmath'; -import { Vec3 } from '../core/value-types'; -import BaseNode from './base-node'; -import Layers from './layers'; -import { EventTarget } from "../core/event"; -import { ccclass, property, mixins } from '../core/data/class-decorator'; - -let v3_a = cc.v3(); -let q_a = cc.quat(); -let array_a = new Array(10); - -let EventType = cc.Enum({ - TRANSFORM_CHANGED: 'transform-changed', - POSITION_PART: 1, - ROTATION_PART: 2, - SCALE_PART: 4 -}); - -@ccclass('cc.Node') -@mixins(EventTarget) -class Node extends BaseNode { - // local transform - @property - _lpos = cc.v3(); - @property - _lrot = cc.quat(); - @property - _lscale = cc.v3(1, 1, 1); - @property - _layer = Layers.Default; // the layer this node belongs to - - @property - _euler = cc.v3(); // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. - - @property({ - type: Vec3 - }) - set eulerAngles(val) { - this.setRotationFromEuler(val.x, val.y, val.z); - } - get eulerAngles() { - if (this._eulerDirty) { - quat.toEuler(this._euler, this._lrot); - this._eulerDirty = false; - } - return this._euler; - } - - set layer(l) { - this._layer = l; - } - - get layer() { - return this._layer; - } - - // world transform - _pos = cc.v3(); - _rot = cc.quat(); - _scale = cc.v3(1, 1, 1); - _mat = cc.mat4(); - - _dirty = false; // does the world transform need to update? - _hasChanged = false; // has the transform changed in this frame? - - _matDirty = false; - _eulerDirty = false; - - // is node but not scene - static isNode (obj) { - return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); - } - - static EventType = EventType; - - constructor (name) { - super(name); - EventTarget.call(this); - } - - - // =============================== - // hierarchy - // =============================== - - /** - * invalidate all children after relevant events - */ - onRestore() { - super.onRestore(); - this.invalidateChildren(); - } - - _onSetParent(/*oldParent*/) { - this.invalidateChildren(); - } - - _onPostActivated() { - this.invalidateChildren(); - } - - // =============================== - // transform helper - // =============================== - - /** - * Set rotation by lookAt target point - * @param {vec3} pos target position - * @param {vec3} up the up vector, default to (0,1,0) - */ - lookAt(pos, up) { - this.getWorldPosition(v3_a); - vec3.sub(v3_a, v3_a, pos); // NOTE: we use -z for view-dir - vec3.normalize(v3_a, v3_a); - quat.fromViewUp(q_a, v3_a, up); - - this.setWorldRotation(q_a); - } - - /** - * Reset the `hasChanged` flag recursively - */ - resetHasChanged() { - this._hasChanged = false; - let len = this._children.length; - for (let i = 0; i < len; ++i) { - this._children[i].resetHasChanged(); - } - } - - /** - * invalidate the world transform information - * for this node and all its children recursively - */ - invalidateChildren() { - if (this._dirty && this._hasChanged) return; - this._dirty = this._hasChanged = true; - - let len = this._children.length; - for (let i = 0; i < len; ++i) { - this._children[i].invalidateChildren(); - } - } - - /** - * update the world transform information if outdated - */ - updateWorldTransform() { - if (!this._dirty) return; - let cur = this, child, i = 0; - while (cur._dirty) { - // top level node - array_a[i++] = cur; - cur = cur._parent; - if (!cur) break; - } - while (i) { - child = array_a[--i]; - if (cur) { - vec3.mul(child._pos, child._lpos, cur._scale); - vec3.transformQuat(child._pos, child._pos, cur._rot); - vec3.add(child._pos, child._pos, cur._pos); - quat.mul(child._rot, cur._rot, child._lrot); - vec3.mul(child._scale, cur._scale, child._lscale); - } - child._matDirty = true; // further deferred eval - child._dirty = false; - cur = child; - } - } - - updateWorldTransformFull() { - this.updateWorldTransform(); - if (!this._matDirty) return; - mat4.fromRTS(this._mat, this._rot, this._pos, this._scale); - this._matDirty = false; - } - - // =============================== - // transform - // =============================== - - /** - * set local position - * @param {vec3|number} val the new local position, or the x component of it - * @param {number} [y] the y component of the new local position - * @param {number} [z] the z component of the new local position - */ - setPosition(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._lpos, val); - } else if (arguments.length === 3) { - vec3.set(this._lpos, val, y, z); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); - } - - /** - * get local position - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getPosition(out) { - if (out) { - return vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z); - } else { - return vec3.copy(cc.v3(), this._lpos); - } - } - - /** - * set local rotation - * @param {quat|number} val the new local rotation, or the x component of it - * @param {number} [y] the y component of the new local rotation - * @param {number} [z] the z component of the new local rotation - * @param {number} [w] the w component of the new local rotation - */ - setRotation(val, y, z, w) { - if (arguments.length === 1) { - quat.copy(this._lrot, val); - } else if (arguments.length === 4) { - quat.set(this._lrot, val, y, z, w); - } - this._eulerDirty = true; - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * set local rotation from euler angles - * @param {number} x - Angle to rotate around X axis in degrees. - * @param {number} y - Angle to rotate around Y axis in degrees. - * @param {number} z - Angle to rotate around Z axis in degrees. - */ - setRotationFromEuler(x, y, z) { - vec3.set(this._euler, x, y, z); - this._eulerDirty = false; - quat.fromEuler(this._lrot, x, y, z); - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * get local rotation - * @param {quat} [out] the receiving quaternion - * @return {quat} the resulting quaternion - */ - getRotation(out) { - if (out) { - return quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w); - } else { - return quat.copy(cc.quat(), this._lrot); - } - } - - /** - * set local scale - * @param {vec3|number} val the new local scale, or the x component of it - * @param {number} [y] the y component of the new local scale - * @param {number} [z] the z component of the new local scale - */ - setScale(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._lscale, val); - } else if (arguments.length === 3) { - vec3.set(this._lscale, val, y, z); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); - } - - /** - * get local scale - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getScale(out) { - if (out) { - return vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z); - } else { - return vec3.copy(cc.v3(), this._lscale); - } - } - - /** - * set world position - * @param {vec3|number} val the new world position, or the x component of it - * @param {number} [y] the y component of the new world position - * @param {number} [z] the z component of the new world position - */ - setWorldPosition(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._pos, val); - } else if (arguments.length === 3) { - vec3.set(this._pos, val, y, z); - } - let parent = this._parent, local = this._lpos; - if (parent) { - parent.updateWorldTransform(); - vec3.sub(local, this._pos, parent._pos); - vec3.transformQuat(local, local, quat.conjugate(q_a, parent._rot)); - vec3.div(local, local, parent._scale); - } else { - vec3.copy(this._lpos, this._pos); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); - } - - /** - * get world position - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getWorldPosition(out) { - this.updateWorldTransform(); - if (out) { - return vec3.copy(out, this._pos); - } else { - return vec3.copy(cc.v3(), this._pos); - } - } - - /** - * set world rotation - * @param {quat|number} val the new world rotation, or the x component of it - * @param {number} [y] the y component of the new world rotation - * @param {number} [z] the z component of the new world rotation - * @param {number} [w] the w component of the new world rotation - */ - setWorldRotation(val, y, z, w) { - if (arguments.length === 1) { - quat.copy(this._rot, val); - } else if (arguments.length === 4) { - quat.set(this._rot, val, y, z, w); - } - if (this._parent) { - this._parent.getWorldRotation(q_a); - quat.mul(this._lrot, quat.conjugate(q_a, q_a), this._rot); - } else { - quat.copy(this._lrot, this._rot); - } - this._eulerDirty = true; - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * set world rotation from euler angles - * @param {number} x - Angle to rotate around X axis in degrees. - * @param {number} y - Angle to rotate around Y axis in degrees. - * @param {number} z - Angle to rotate around Z axis in degrees. - */ - setWorldRotationFromEuler(x, y, z) { - vec3.set(this._euler, x, y, z); - this._eulerDirty = false; - quat.fromEuler(this._rot, x, y, z); - if (this._parent) { - this._parent.getWorldRotation(q_a); - quat.mul(this._lrot, this._rot, quat.conjugate(q_a, q_a)); - } else { - quat.copy(this._lrot, this._rot); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * get world rotation - * @param {quat} [out] the receiving quaternion - * @return {quat} the resulting quaternion - */ - getWorldRotation(out) { - this.updateWorldTransform(); - if (out) { - return quat.copy(out, this._rot); - } else { - return quat.copy(cc.quat(), this._rot); - } - } - - /** - * set world scale - * @param {vec3|number} val the new world scale, or the x component of it - * @param {number} [y] the y component of the new world scale - * @param {number} [z] the z component of the new world scale - */ - setWorldScale(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._scale, val); - } else if (arguments.length === 3) { - vec3.set(this._scale, val, y, z); - } - if (this._parent) { - this._parent.getWorldScale(v3_a); - vec3.div(this._lscale, this._scale, v3_a); - } else { - vec3.copy(this._lscale, this._scale); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); - } - - /** - * get world scale - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getWorldScale(out) { - this.updateWorldTransform(); - if (out) { - return vec3.copy(out, this._scale); - } else { - return vec3.copy(cc.v3(), this._scale); - } - } - - /** - * get the matrix that transforms a point from local space into world space - * @param {mat4} [out] the receiving matrix - * @return {mat4} the resulting matrix - */ - getWorldMatrix(out) { - this.updateWorldTransformFull(); - if (out) { - return mat4.copy(out, this._mat); - } else { - return mat4.copy(cc.mat4(), this._mat); - } - } - - /** - * get world transform matrix (with only rotation and scale) - * @param {mat4} [out] the receiving matrix - * @return {mat4} the resulting matrix - */ - getWorldRS(out) { - this.updateWorldTransformFull(); - if (out) { - mat4.copy(out, this._mat); - } else { - out = mat4.copy(cc.mat4(), this._mat); - } - out.m12 = 0; out.m13 = 0; out.m14 = 0; - return out; - } - - /** - * get world transform matrix (with only rotation and translation) - * @param {mat4} [out] the receiving matrix - * @return {mat4} the resulting matrix - */ - getWorldRT(out) { - this.updateWorldTransform(); - if (!out) { - out = cc.mat4(); - } - return mat4.fromRT(out, this._rot, this._pos); - } -} - -if (CC_EDITOR) { - let repeat = (t, l) => t - Math.floor(t / l) * l; - let desc = { - set(val) { - this.setRotationFromEuler(val.x, val.y, val.z); - }, - get() { - if (this._eulerDirty) { - let eu = this._euler; - quat.toEuler(v3_a, this._lrot); - eu.x = repeat(v3_a.x - eu.x + 180, 360) + eu.x - 180; - eu.y = repeat(v3_a.y - eu.y + 180, 360) + eu.y - 180; - eu.z = repeat(v3_a.z - eu.z + 180, 360) + eu.z - 180; - this._eulerDirty = false; - } - return this._euler; - } - }; - Object.defineProperty(Node.prototype, 'eulerAngles', desc); -} - -cc.Node = Node; -export default Node; diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts new file mode 100644 index 0000000000..c9acd92d01 --- /dev/null +++ b/cocos/scene-graph/node.ts @@ -0,0 +1,1287 @@ +import { UITransformComponent } from '../3d/ui/components/ui-transfrom-component'; +import { ccclass, mixins, property } from '../core/data/class-decorator'; +import { DefaultEventTarget, EventTarget } from '../core/event/event-target-base'; +import { Enum, Mat4, Quat, Vec3 } from '../core/value-types'; +import Size from '../core/value-types/size'; +import Vec2 from '../core/value-types/vec2'; +import { mat4, quat, vec3 } from '../core/vmath'; +import { BaseNode } from './base-node'; +import { Layers } from './layers'; +import { WidgetComponent } from '../3d/ui/components/widget-component'; + +const v3_a = new Vec3(); +const q_a = new Quat(); +const array_a = new Array(10); +const _cachedArray = new Array(16); +_cachedArray.length = 0; + +const EventType = Enum({ + TRANSFORM_CHANGED: 'transform-changed', + POSITION_PART: 1, + ROTATION_PART: 2, + SCALE_PART: 4, + TOUCH_START: 'touch-start', + TOUCH_MOVE: 'touch-move', + TOUCH_END: 'touch-end', + TOUCH_CANCEL: 'touch-cancel', + MOUSE_DOWN: 'mouse-down', + MOUSE_ENTER: 'mouse-enter', + MOUSE_MOVE: 'mouse-move', + MOUSE_LEAVE: 'mouse-leave', + MOUSE_UP: 'mouse-up', + MOUSE_WHEEL: 'mouse-wheel', +}); + +const _touchEvents = [ + EventType.TOUCH_START, + EventType.TOUCH_MOVE, + EventType.TOUCH_END, + EventType.TOUCH_CANCEL, +]; +const _mouseEvents = [ + EventType.MOUSE_DOWN, + EventType.MOUSE_ENTER, + EventType.MOUSE_MOVE, + EventType.MOUSE_LEAVE, + EventType.MOUSE_UP, + EventType.MOUSE_WHEEL, +]; + +const _touchStartHandler = function (touch, event) { + const pos = touch.getLocation(); + const node = this.owner; + + if (node._hitTest(pos, this)) { + event.type = EventType.TOUCH_START; + event.touch = touch; + event.bubbles = true; + node.dispatchEvent(event); + return true; + } + return false; +}; +const _touchMoveHandler = function (touch, event) { + const node = this.owner; + event.type = EventType.TOUCH_MOVE; + event.touch = touch; + event.bubbles = true; + node.dispatchEvent(event); +}; +const _touchEndHandler = function (touch, event) { + const pos = touch.getLocation(); + const node = this.owner; + + if (node._hitTest(pos, this)) { + event.type = EventType.TOUCH_END; + } else { + event.type = EventType.TOUCH_CANCEL; + } + event.touch = touch; + event.bubbles = true; + node.dispatchEvent(event); +}; +const _touchCancelHandler = function (touch, event) { + const node = this.owner; + + event.type = EventType.TOUCH_CANCEL; + event.touch = touch; + event.bubbles = true; + node.dispatchEvent(event); +}; + +const _mouseDownHandler = function (event) { + const pos = event.getLocation(); + const node = this.owner; + + if (node._hitTest(pos, this)) { + event.type = EventType.MOUSE_DOWN; + event.bubbles = true; + node.dispatchEvent(event); + } +}; +const _mouseMoveHandler = function (event) { + const pos = event.getLocation(); + const node = this.owner; + const hit = node._hitTest(pos, this); + if (hit) { + if (!this._previousIn) { + // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification + if (_currentHovered && _currentHovered._mouseListener) { + event.type = EventType.MOUSE_LEAVE; + _currentHovered.dispatchEvent(event); + _currentHovered._mouseListener._previousIn = false; + } + _currentHovered = this.owner; + event.type = EventType.MOUSE_ENTER; + node.dispatchEvent(event); + this._previousIn = true; + } + event.type = EventType.MOUSE_MOVE; + event.bubbles = true; + node.dispatchEvent(event); + } else if (this._previousIn) { + event.type = EventType.MOUSE_LEAVE; + node.dispatchEvent(event); + this._previousIn = false; + _currentHovered = null; + } else { + // continue dispatching + return; + } + + // Event processed, cleanup + event.stopPropagation(); +}; +const _mouseUpHandler = function (event) { + const pos = event.getLocation(); + const node = this.owner; + + if (node._hitTest(pos, this)) { + event.type = EventType.MOUSE_UP; + event.bubbles = true; + node.dispatchEvent(event); + event.stopPropagation(); + } +}; +const _mouseWheelHandler = function (event) { + const pos = event.getLocation(); + const node = this.owner; + + if (node._hitTest(pos, this)) { + event.type = EventType.MOUSE_WHEEL; + event.bubbles = true; + node.dispatchEvent(event); + event.stopPropagation(); + } +}; + +function _doDispatchEvent (owner, event) { + let target, i; + event.target = owner; + + // Event.CAPTURING_PHASE + _cachedArray.length = 0; + owner._getCapturingTargets(event.type, _cachedArray); + // capturing + event.eventPhase = 1; + for (i = _cachedArray.length - 1; i >= 0; --i) { + target = _cachedArray[i]; + if (target._capturingListeners) { + event.currentTarget = target; + // fire event + target._capturingListeners.emit(event.type, event, _cachedArray); + // check if propagation stopped + if (event._propagationStopped) { + _cachedArray.length = 0; + return; + } + } + } + _cachedArray.length = 0; + + // Event.AT_TARGET + // checks if destroyed in capturing callbacks + event.eventPhase = 2; + event.currentTarget = owner; + if (owner._capturingListeners) { + owner._capturingListeners.emit(event.type, event); + } + if (!event._propagationImmediateStopped && owner._bubblingListeners) { + owner._bubblingListeners.emit(event.type, event); + } + + if (!event._propagationStopped && event.bubbles) { + // Event.BUBBLING_PHASE + owner._getBubblingTargets(event.type, _cachedArray); + // propagate + event.eventPhase = 3; + for (i = 0; i < _cachedArray.length; ++i) { + target = _cachedArray[i]; + if (target._bubblingListeners) { + event.currentTarget = target; + // fire event + target._bubblingListeners.emit(event.type, event); + // check if propagation stopped + if (event._propagationStopped) { + _cachedArray.length = 0; + return; + } + } + } + } + _cachedArray.length = 0; +} + +enum NodeSpace { + LOCAL, + WORLD, +} + +@ccclass('cc.Node') +@mixins(EventTarget) +class Node extends EventTarget(BaseNode) { + public static EventType = EventType; + public static NodeSpace = NodeSpace; + + // is node but not scene + 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 + @property + protected _lpos = new Vec3(); + @property + protected _lrot = new Quat(); + @property + protected _lscale = new Vec3(1, 1, 1); + @property + protected _layer = Layers.Default; // the layer this node belongs to + + // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. + @property + protected _euler = new Vec3(); + + // world transform + protected _pos = new Vec3(); + protected _rot = new Quat(); + protected _scale = new Vec3(1, 1, 1); + protected _mat = new Mat4(); + + protected _dirty = false; // does the world transform need to update? + protected _hasChanged = false; // has the transform changed in this frame? + + protected _matDirty = false; + protected _eulerDirty = false; + + protected _bubblingListeners: EventTarget|null = null; + protected _capturingListeners: EventTarget | null = null; + + @property({ + type: Vec3, + }) + set eulerAngles (val) { + this.setRotationFromEuler(val.x, val.y, val.z); + } + get eulerAngles () { + if (this._eulerDirty) { + quat.toEuler(this._euler, this._lrot); + this._eulerDirty = false; + } + return this._euler; + } + + get hasChanged () { + return this._hasChanged; + } + + set layer (l) { + this._layer = l; + } + + get layer () { + return this._layer; + } + + get width () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.width; + } + + set width (value) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.width = value; + } + + get height () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.height; + } + + set height (value) { + if (!this.uiTransfromComp) { + return; + } + this.uiTransfromComp.height = value; + } + + get anchorX () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.anchorX; + } + + set anchorX (value) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.anchorX = value; + } + + get anchorY () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.anchorY; + } + + set anchorY (value) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.anchorY = value; + } + + constructor (name: string) { + super(name); + // EventTarget.call(this); + } + + // =============================== + // hierarchy + // =============================== + + /** + * invalidate all children after relevant events + */ + public onRestore () { + super.onRestore(); + this.invalidateChildren(); + } + + public _onSetParent (oldParent: this) { + super._onSetParent(oldParent); + this.invalidateChildren(); + } + + public _onPostActivated () { + this.invalidateChildren(); + } + + // =============================== + // transform helper, convenient but not the most efficient + // =============================== + + /** + * Rotate the node + * @param rot - rotation to apply + * @param ns - the operating space + */ + public rotate (rot: Quat, ns?: NodeSpace) { + const space = ns || NodeSpace.LOCAL; + if (space === NodeSpace.LOCAL) { + this.getRotation(q_a); + this.setRotation(quat.multiply(q_a, q_a, rot)); + } else if (space === NodeSpace.WORLD) { + this.getWorldRotation(q_a); + this.setWorldRotation(quat.multiply(q_a, rot, q_a)); + } + } + + /** + * rotate the node around X axis + * @param rad - rotating angle + * @param ns - the operating space + */ + public pitch (rad: number, ns?: NodeSpace) { + const space = ns || NodeSpace.LOCAL; + if (space === NodeSpace.LOCAL) { + this.getWorldRotation(q_a); + quat.toAxisX(v3_a, q_a); + quat.fromAxisAngle(q_a, v3_a, rad); + this.rotate(q_a, ns); + } else if (space === NodeSpace.WORLD) { + quat.fromAxisAngle(q_a, vec3.UNIT_X, rad); + this.rotate(q_a, ns); + } + } + + /** + * rotate the node around Y axis + * @param rad - rotating angle + * @param ns - the operating space + */ + public yaw (rad: number, ns?: NodeSpace) { + const space = ns || NodeSpace.LOCAL; + if (space === NodeSpace.LOCAL) { + this.getWorldRotation(q_a); + quat.toAxisY(v3_a, q_a); + quat.fromAxisAngle(q_a, v3_a, rad); + this.rotate(q_a, ns); + } else if (space === NodeSpace.WORLD) { + quat.fromAxisAngle(q_a, vec3.UNIT_Y, rad); + this.rotate(q_a, ns); + } + } + + /** + * rotate the node around Z axis + * @param rad - rotating angle + * @param ns - the operating space + */ + public roll (rad: number, ns?: NodeSpace) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL) { + this.getWorldRotation(q_a); + quat.toAxisZ(v3_a, q_a); + quat.fromAxisAngle(q_a, v3_a, rad); + this.rotate(q_a, ns); + } else if (space === NodeSpace.WORLD) { + quat.fromAxisAngle(q_a, vec3.UNIT_Z, rad); + this.rotate(q_a, ns); + } + } + + public get direction (): Vec3 { + this.getRotation(q_a); + return vec3.transformQuat(new Vec3(), vec3.UNIT_Z, q_a); + } + + public set direction (dir: Vec3) { + quat.rotationTo(q_a, vec3.UNIT_Z, dir); + this.setRotation(q_a); + } + + /** + * Set rotation by lookAt target point + * @param pos - target position + * @param up - the up vector, default to (0,1,0) + */ + public lookAt (pos: Vec3, up: Vec3) { + this.getWorldPosition(v3_a); + vec3.sub(v3_a, v3_a, pos); // NOTE: we use -z for view-dir + vec3.normalize(v3_a, v3_a); + quat.fromViewUp(q_a, v3_a, up); + + this.setWorldRotation(q_a); + } + + // =============================== + // transform maintainer + // =============================== + + /** + * Reset the `hasChanged` flag recursively + */ + public resetHasChanged () { + this._hasChanged = false; + const len = this._children.length; + for (let i = 0; i < len; ++i) { + this._children[i].resetHasChanged(); + } + } + + /** + * invalidate the world transform information + * for this node and all its children recursively + */ + public invalidateChildren () { + if (this._dirty && this._hasChanged) { return; } + this._dirty = this._hasChanged = true; + for (const child of this._children) { + child.invalidateChildren(); + } + } + + /** + * update the world transform information if outdated + * here we assume all nodes are children of a scene node, + * which is always not dirty, has an identity transform and no parent. + */ + public updateWorldTransform () { + if (!this._dirty) { return; } + let cur: this | null = this; + let i = 0; + while (cur._dirty) { + // top level node + array_a[i++] = cur; + cur = cur._parent; + if (!cur || !cur._parent) { + cur = null; + break; + } + } + let child: this; + while (i) { + child = array_a[--i]; + if (cur) { + vec3.mul(child._pos, child._lpos, cur._scale); + vec3.transformQuat(child._pos, child._pos, cur._rot); + vec3.add(child._pos, child._pos, cur._pos); + quat.mul(child._rot, cur._rot, child._lrot); + vec3.mul(child._scale, cur._scale, child._lscale); + } + child._matDirty = true; // further deferred eval + child._dirty = false; + cur = child; + } + } + + public updateWorldTransformFull () { + this.updateWorldTransform(); + if (!this._matDirty) { return; } + mat4.fromRTS(this._mat, this._rot, this._pos, this._scale); + this._matDirty = false; + } + + // =============================== + // transform + // =============================== + + /** + * Sets local position. + * @param position - The new local position. + */ + public setPosition (position: Vec3): void; + + /** + * Sets local position. + * @param x - The x component of the new local position. + * @param y - The y component of the new local position. + * @param z - The z component of the new local position. + * @param w - The w component of the new local position. + */ + public setPosition (x: number, y: number, z: number): void; + + /** + * set local position + * @param val - the new local position, or the x component of it + * @param y - the y component of the new local position + * @param z - the z component of the new local position + */ + public setPosition (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._lpos, val as Vec3); + } else if (arguments.length === 3) { + vec3.set(this._lpos, val as number, y, z); + } + vec3.copy(this._pos, this._lpos); + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); + } + + /** + * get local position + * @param out the receiving vector + * @returns the resulting vector + */ + public getPosition (out?: Vec3): Vec3 { + if (out) { + return vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z); + } else { + return vec3.copy(new Vec3(), this._lpos); + } + } + + /** + * Sets local rotation. + * @param rotation - The new local rotation. + */ + public setRotation (rotation: Quat): void; + + /** + * Sets local rotation. + * @param x - The x component of the new local rotation. + * @param y - The y component of the new local rotation. + * @param z - The z component of the new local rotation. + * @param w - The w component of the new local rotation. + */ + public setRotation (x: number, y: number, z: number, w: number): void; + + public setRotation (val: Quat | number, y?: number, z?: number, w?: number) { + if (y === undefined || z === undefined || w === undefined) { + quat.copy(this._lrot, val as Quat); + } else if (arguments.length === 4) { + quat.set(this._lrot, val as number, y, z, w); + } + quat.copy(this._rot, this._lrot); + this._eulerDirty = true; + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * set local rotation from euler angles + * @param x - Angle to rotate around X axis in degrees. + * @param y - Angle to rotate around Y axis in degrees. + * @param z - Angle to rotate around Z axis in degrees. + */ + public setRotationFromEuler (x: number, y: number, z: number) { + vec3.set(this._euler, x, y, z); + this._eulerDirty = false; + quat.fromEuler(this._lrot, x, y, z); + quat.copy(this._rot, this._lrot); + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * get local rotation + * @param out - the receiving quaternion + * @returns the resulting quaternion + */ + public getRotation (out?: Quat): Quat { + if (out) { + return quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w); + } else { + return quat.copy(new Quat(), this._lrot); + } + } + + /** + * Sets local scale. + * @param scale - The new local scale. + */ + public setScale (scale: Vec3): void; + + /** + * Sets local scale. + * @param x - The x component of the new local scale. + * @param y - The y component of the new local scale. + * @param z - The z component of the new local scale. + */ + public setScale (x: number, y: number, z: number): void; + + /** + * set local scale + * @param val - the new local scale, or the x component of it + * @param y - the y component of the new local scale + * @param z - the z component of the new local scale + */ + public setScale (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._lscale, val as Vec3); + } else if (arguments.length === 3) { + vec3.set(this._lscale, val as number, y, z); + } + vec3.copy(this._scale, this._lscale); + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); + } + + /** + * get local scale + * @param out - the receiving vector + * @returns the resulting vector + */ + public getScale (out?: Vec3): Vec3 { + if (out) { + return vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z); + } else { + return vec3.copy(new Vec3(), this._lscale); + } + } + + /** + * Sets world position. + * @param position - The new world position. + */ + public setWorldPosition (position: Vec3): void; + + /** + * Sets world position. + * @param x - The x component of the new world position. + * @param y - The y component of the new world position. + * @param z - The z component of the new world position. + */ + public setWorldPosition (x: number, y: number, z: number): void; + + /** + * set world position + * @param val - the new world position, or the x component of it + * @param y - the y component of the new world position + * @param z - the z component of the new world position + */ + public setWorldPosition (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._pos, val as Vec3); + } else if (arguments.length === 3) { + vec3.set(this._pos, val as number, y, z); + } + const parent = this._parent; + const local = this._lpos; + if (parent) { + parent.updateWorldTransform(); + vec3.sub(local, this._pos, parent._pos); + vec3.transformQuat(local, local, quat.conjugate(q_a, parent._rot)); + vec3.div(local, local, parent._scale); + } else { + vec3.copy(this._lpos, this._pos); + } + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); + } + + /** + * get world position + * @param out - the receiving vector + * @returns the resulting vector + */ + public getWorldPosition (out?: Vec3): Vec3 { + this.updateWorldTransform(); + if (out) { + return vec3.copy(out, this._pos); + } else { + return vec3.copy(new Vec3(), this._pos); + } + } + + /** + * Sets world rotation. + * @param rotation - The new world rotation. + */ + public setWorldRotation (rotation: Quat): void; + + /** + * Sets world rotation. + * @param x - The x component of the new world rotation. + * @param y - The y component of the new world rotation. + * @param z - The z component of the new world rotation. + * @param w - The w component of the new world rotation. + */ + public setWorldRotation (x: number, y: number, z: number, w: number): void; + + /** + * set world rotation + * @param val - the new world rotation, or the x component of it + * @param y - the y component of the new world rotation + * @param z - the z component of the new world rotation + * @param w - the w component of the new world rotation + */ + public setWorldRotation (val: Quat | number, y?: number, z?: number, w?: number) { + if (y === undefined || z === undefined || w === undefined) { + quat.copy(this._rot, val as Quat); + } else if (arguments.length === 4) { + quat.set(this._rot, val as number, y, z, w); + } + if (this._parent) { + this._parent.getWorldRotation(q_a); + quat.mul(this._lrot, quat.conjugate(q_a, q_a), this._rot); + } else { + quat.copy(this._lrot, this._rot); + } + this._eulerDirty = true; + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * set world rotation from euler angles + * @param x - Angle to rotate around X axis in degrees. + * @param y - Angle to rotate around Y axis in degrees. + * @param z - Angle to rotate around Z axis in degrees. + */ + public setWorldRotationFromEuler (x: number, y: number, z: number) { + vec3.set(this._euler, x, y, z); + this._eulerDirty = false; + quat.fromEuler(this._rot, x, y, z); + if (this._parent) { + this._parent.getWorldRotation(q_a); + quat.mul(this._lrot, this._rot, quat.conjugate(q_a, q_a)); + } else { + quat.copy(this._lrot, this._rot); + } + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * get world rotation + * @param out - the receiving quaternion + * @returns the resulting quaternion + */ + public getWorldRotation (out?: Quat): Quat { + this.updateWorldTransform(); + if (out) { + return quat.copy(out, this._rot); + } else { + return quat.copy(new Quat(), this._rot); + } + } + + /** + * Sets world scale. + * @param scale - The new world scale. + */ + public setWorldScale (scale: Vec3): void; + + /** + * Sets world scale. + * @param x - The x component of the new world scale. + * @param y - The y component of the new world scale. + * @param z - The z component of the new world scale. + */ + public setWorldScale (x: number, y: number, z: number): void; + + /** + * set world scale + * @param val - the new world scale, or the x component of it + * @param y - the y component of the new world scale + * @param z - the z component of the new world scale + */ + public setWorldScale (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._scale, val as Vec3); + } else if (arguments.length === 3) { + vec3.set(this._scale, val as number, y, z); + } + if (this._parent) { + this._parent.getWorldScale(v3_a); + vec3.div(this._lscale, this._scale, v3_a); + } else { + vec3.copy(this._lscale, this._scale); + } + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); + } + + /** + * get world scale + * @param out - the receiving vector + * @returns the resulting vector + */ + public getWorldScale (out?: Vec3): Vec3 { + this.updateWorldTransform(); + if (out) { + return vec3.copy(out, this._scale); + } else { + return vec3.copy(new Vec3(), this._scale); + } + } + + /** + * get the matrix that transforms a point from local space into world space + * @param out - the receiving matrix + * @returns the - resulting matrix + */ + public getWorldMatrix (out?: Mat4): Mat4 { + this.updateWorldTransformFull(); + if (out) { + return mat4.copy(out, this._mat); + } else { + return mat4.copy(new Mat4(), this._mat); + } + } + + /** + * get world transform matrix (with only rotation and scale) + * @param out - the receiving matrix + * @returns the - resulting matrix + */ + public getWorldRS (out?: Mat4): Mat4 { + this.updateWorldTransformFull(); + if (out === undefined) { out = new Mat4(); } + mat4.copy(out, this._mat); + out.m12 = 0; out.m13 = 0; out.m14 = 0; + return out; + } + + /** + * get world transform matrix (with only rotation and translation) + * @param out - the receiving matrix + * @returns the - resulting matrix + */ + public getWorldRT (out?: Mat4): Mat4 { + this.updateWorldTransform(); + if (!out) { + out = new Mat4(); + } + return mat4.fromRT(out, this._rot, this._pos); + } + + public getAnchorPoint () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.anchorPoint; + } + + public setAnchorPoint (point: Vec2, y: number) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.setAnchorPoint(point, y); + } + + public getContentSize () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.contentSize; + } + + public setContentSize (size: Size, height?: number) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.setContentSize(size, height); + } + + // EVENT TARGET + + public _checknSetupSysEvent (type) { + let newAdded = false; + let forDispatch = false; + if (_touchEvents.indexOf(type) !== -1) { + if (!this._touchListener) { + this._touchListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + owner: this, + mask: _searchMaskInParent(this), + onTouchBegan: _touchStartHandler, + onTouchMoved: _touchMoveHandler, + onTouchEnded: _touchEndHandler, + onTouchCancelled: _touchCancelHandler, + }); + eventManager.addListener(this._touchListener, this); + newAdded = true; + } + forDispatch = true; + } else if (_mouseEvents.indexOf(type) !== -1) { + if (!this._mouseListener) { + this._mouseListener = cc.EventListener.create({ + event: cc.EventListener.MOUSE, + _previousIn: false, + owner: this, + mask: _searchMaskInParent(this), + onMouseDown: _mouseDownHandler, + onMouseMove: _mouseMoveHandler, + onMouseUp: _mouseUpHandler, + onMouseScroll: _mouseWheelHandler, + }); + eventManager.addListener(this._mouseListener, this); + newAdded = true; + } + forDispatch = true; + } + if (newAdded && !this._activeInHierarchy) { + cc.director.getScheduler().schedule(function () { + if (!this._activeInHierarchy) { + eventManager.pauseTarget(this); + } + }, this, 0, 0, 0, false); + } + return forDispatch; + } + + /** + * !#en + * Register a callback of a specific event type on Node.
+ * Use this method to register touch or mouse event permit propagation based on scene graph,
+ * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
+ * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
+ * 2. At target phase: dispatch to the listeners of the real target
+ * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
+ * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
+ * It's the recommended way to register touch/mouse event for Node,
+ * please do not use cc.eventManager directly for Node.
+ * You can also register custom event and use `emit` to trigger custom event on Node.
+ * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
+ * You can also pass event callback parameters with `emit` by passing parameters after `type`. + * !#zh + * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
+ * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
+ * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
+ * 2. 目标阶段:派发给目标节点的监听器。
+ * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
+ * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
+ * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
+ * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
+ * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表 + * @method on + * @param {String|Node.EventType} type - A string representing the event type to listen for.
See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {Event|any} [callback.event] event or first argument when emit + * @param {any} [callback.arg2] arg2 + * @param {any} [callback.arg3] arg3 + * @param {any} [callback.arg4] arg4 + * @param {any} [callback.arg5] arg5 + * @param {Object} [target] - The target (this object) to invoke the callback, can be null + * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase. + * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. + * @typescript + * on(type: string, callback: T, target?: any, useCapture?: boolean): T + * @example + * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. + * node.on(cc.Node.EventType.TOUCH_START, callback, this); + * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this); + * node.on(cc.Node.EventType.TOUCH_END, callback, this); + * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this); + * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback); + */ + public on (type, callback, target, useCapture?: number) { + const forDispatch = this._checknSetupSysEvent(type); + if (forDispatch) { + return this._onDispatch(type, callback, target, useCapture); + } else { + // switch (type) { + // case EventType.POSITION_CHANGED: + // this._eventMask |= POSITION_ON; + // break; + // case EventType.SCALE_CHANGED: + // this._eventMask |= SCALE_ON; + // break; + // case EventType.ROTATION_CHANGED: + // this._eventMask |= ROTATION_ON; + // break; + // case EventType.SIZE_CHANGED: + // this._eventMask |= SIZE_ON; + // break; + // case EventType.ANCHOR_CHANGED: + // this._eventMask |= ANCHOR_ON; + // break; + // } + if (!this._bubblingListeners) { + this._bubblingListeners = new DefaultEventTarget(); + } + return this._bubblingListeners.on(type, callback, target); + } + } + + // /** + // * !#en + // * Register an callback of a specific event type on the Node, + // * the callback will remove itself after the first time it is triggered. + // * !#zh + // * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。 + // * + // * @method once + // * @param {String} type - A string representing the event type to listen for. + // * @param {Function} callback - The callback that will be invoked when the event is dispatched. + // * The callback is ignored if it is a duplicate (the callbacks are unique). + // * @param {Event|any} [callback.event] event or first argument when emit + // * @param {any} [callback.arg2] arg2 + // * @param {any} [callback.arg3] arg3 + // * @param {any} [callback.arg4] arg4 + // * @param {any} [callback.arg5] arg5 + // * @param {Object} [target] - The target (this object) to invoke the callback, can be null + // * @typescript + // * once(type: string, callback: T, target?: any, useCapture?: boolean): T + // * @example + // * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback); + // */ + // once(type, callback, target, useCapture) { + // let forDispatch = this._checknSetupSysEvent(type); + // let eventType_hasOnceListener = '__ONCE_FLAG:' + type; + + // let listeners = null; + // if (forDispatch && useCapture) { + // listeners = this._capturingListeners = this._capturingListeners || new DefaultEventTarget(); + // } + // else { + // listeners = this._bubblingListeners = this._bubblingListeners || new DefaultEventTarget(); + // } + + // let hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target); + // if (!hasOnceListener) { + // let self = this; + // let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { + // self.off(type, onceWrapper, target); + // listeners.remove(eventType_hasOnceListener, callback, target); + // callback.call(this, arg1, arg2, arg3, arg4, arg5); + // }; + // this.on(type, onceWrapper, target); + // listeners.add(eventType_hasOnceListener, callback, target); + // } + // } + + public _onDispatch (type, callback, target, useCapture) { + // Accept also patameters like: (type, callback, useCapture) + if (typeof target === 'boolean') { + useCapture = target; + target = undefined; + } else { useCapture = !!useCapture; } + if (!callback) { + cc.errorID(6800); + return; + } + + let listeners = null; + if (useCapture) { + listeners = this._capturingListeners = this._capturingListeners || new DefaultEventTarget(); + } else { + listeners = this._bubblingListeners = this._bubblingListeners || new DefaultEventTarget(); + } + + if (!listeners.hasEventListener(type, callback, target)) { + listeners.add(type, callback, target); + + if (target && target.__eventTargets) { + target.__eventTargets.push(this); + } + } + + return callback; + } + + /** + * !#en + * Removes the callback previously registered with the same type, callback, target and or useCapture. + * This method is merely an alias to removeEventListener. + * !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。 + * @method off + * @param {String} type - A string representing the event type being removed. + * @param {Function} [callback] - The callback to remove. + * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed + * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase. + * @example + * this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this); + * node.off(cc.Node.EventType.TOUCH_START, callback, this.node); + * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this); + */ + public off (type, callback, target, useCapture?: number) { + const touchEvent = _touchEvents.indexOf(type) !== -1; + const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1; + if (touchEvent || mouseEvent) { + this._offDispatch(type, callback, target, useCapture); + + if (touchEvent) { + if (this._touchListener && !_checkListeners(this, _touchEvents)) { + eventManager.removeListener(this._touchListener); + this._touchListener = null; + } + } else if (mouseEvent) { + if (this._mouseListener && !_checkListeners(this, _mouseEvents)) { + eventManager.removeListener(this._mouseListener); + this._mouseListener = null; + } + } + } else if (this._bubblingListeners) { + this._bubblingListeners.off(type, callback, target); + + const hasListeners = this._bubblingListeners.hasEventListener(type); + // All listener removed + // if (!hasListeners) { + // switch (type) { + // case EventType.POSITION_CHANGED: + // this._eventMask &= ~POSITION_ON; + // break; + // case EventType.SCALE_CHANGED: + // this._eventMask &= ~SCALE_ON; + // break; + // case EventType.ROTATION_CHANGED: + // this._eventMask &= ~ROTATION_ON; + // break; + // case EventType.SIZE_CHANGED: + // this._eventMask &= ~SIZE_ON; + // break; + // case EventType.ANCHOR_CHANGED: + // this._eventMask &= ~ANCHOR_ON; + // break; + // } + // } + } + } + + public _offDispatch (type, callback, target, useCapture) { + // Accept also patameters like: (type, callback, useCapture) + if (typeof target === 'boolean') { + useCapture = target; + target = undefined; + } else { useCapture = !!useCapture; } + if (!callback) { + this._capturingListeners && this._capturingListeners.removeAll(type); + this._bubblingListeners && this._bubblingListeners.removeAll(type); + } else { + const listeners = useCapture ? this._capturingListeners : this._bubblingListeners; + if (listeners) { + listeners.remove(type, callback, target); + + if (target && target.__eventTargets) { + js.array.fastRemove(target.__eventTargets, this); + } + } + + } + } + + /** + * !#en + * Trigger an event directly with the event name and necessary arguments. + * !#zh + * 通过事件名发送自定义事件 + * + * @method emit + * @param {String} type - event type + * @param {*} [arg1] - First argument in callback + * @param {*} [arg2] - Second argument in callback + * @param {*} [arg3] - Third argument in callback + * @param {*} [arg4] - Fourth argument in callback + * @param {*} [arg5] - Fifth argument in callback + * @example + * + * eventTarget.emit('fire', event); + * eventTarget.emit('fire', message, emitter); + */ + public emit (type, ...args: any[]) { + if (this._bubblingListeners) { + this._bubblingListeners.emit(type, ...args); + } + } + + /** + * !#en + * Dispatches an event into the event flow. + * The event target is the EventTarget object upon which the dispatchEvent() method is called. + * !#zh 分发事件到事件流中。 + * + * @method dispatchEvent + * @param {Event} event - The Event object that is dispatched into the event flow + */ + public dispatchEvent (event) { + _doDispatchEvent(this, event); + _cachedArray.length = 0; + } +} + +if (CC_EDITOR) { + const repeat = (t: number, l: number) => t - Math.floor(t / l) * l; + Object.defineProperty(Node.prototype, 'eulerAngles', { + set (val: Vec3) { + this.setRotationFromEuler(val.x, val.y, val.z); + }, + get () { + if (this._eulerDirty) { + const eu = this._euler; + quat.toEuler(v3_a, this._lrot); + eu.x = repeat(v3_a.x - eu.x + 180, 360) + eu.x - 180; + eu.y = repeat(v3_a.y - eu.y + 180, 360) + eu.y - 180; + eu.z = repeat(v3_a.z - eu.z + 180, 360) + eu.z - 180; + this._eulerDirty = false; + } + return this._euler; + }, + }); +} + +cc.Node = Node; +export { Node }; diff --git a/cocos/scene-graph/private-node.js b/cocos/scene-graph/private-node.js index 50c22cb9bf..f17569b64e 100644 --- a/cocos/scene-graph/private-node.js +++ b/cocos/scene-graph/private-node.js @@ -25,7 +25,7 @@ 'use strict'; -import Node from './node'; +import { Node } from './node'; import { ccclass, property } from '../core/data/class-decorator'; const LocalDirtyFlag = Node._LocalDirtyFlag; @@ -164,4 +164,4 @@ export default class PrivateNode extends Node { cc.js.getset(PrivateNode.prototype, "parent", PrivateNode.prototype.getParent, PrivateNode.prototype.setParent); cc.js.getset(PrivateNode.prototype, "position", PrivateNode.prototype.getPosition, PrivateNode.prototype.setPosition); -cc.PrivateNode = PrivateNode; \ No newline at end of file +cc.PrivateNode = PrivateNode; diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js index d1cee7d257..e35a4bdef8 100644 --- a/cocos/scene-graph/scene.js +++ b/cocos/scene-graph/scene.js @@ -23,8 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -import Node from './node'; +import { Node } from './node'; import { ccclass, property } from '../core/data/class-decorator'; +import { BaseNode } from './base-node'; /** * !#en @@ -38,6 +39,7 @@ import { ccclass, property } from '../core/data/class-decorator'; */ @ccclass("cc.Scene") export default class Scene extends Node { + constructor(name) { super(name); @@ -50,6 +52,10 @@ export default class Scene extends Node { // cache all depend assets for auto release this.dependAssets = null; + + if (cc.director && cc.director.root) { + this._renderScene = cc.director.root.createScene({}); + } } /** @@ -58,20 +64,21 @@ export default class Scene extends Node { * @property {Boolean} autoReleaseAssets * @default false */ - @property({ + @property({ type: cc.Boolean - }) + }) autoReleaseAssets = undefined; - destroy () { + destroy() { super.destroy(); + cc.director.root.destroyScene(this._renderScene); this._activeInHierarchy = false; } - _onHierarchyChanged() {} - _instantiate() {} + _onHierarchyChanged() { } + _instantiate() { } - _load () { + _load() { if (!this._inited) { if (CC_TEST) { cc.assert(!this._activeInHierarchy, 'Should deactivate ActionManager and EventManager by default'); @@ -84,9 +91,10 @@ export default class Scene extends Node { } this._inited = true; } + this.walk(BaseNode._setScene); } - _activate (active) { + _activate(active) { active = (active !== false); if (CC_EDITOR || CC_TEST) { // register all nodes to editor diff --git a/docs/apisrc.json b/docs/apisrc.json index 2c235ed36c..a0e00ced60 100644 --- a/docs/apisrc.json +++ b/docs/apisrc.json @@ -17,12 +17,12 @@ "./cocos2d/audio/**/*", "./cocos2d/core/CCDebug.js", - "./cocos2d/core/CCDirector.js", + "./cocos2d/core/director.js", "./cocos2d/core/CCNode.js", "./cocos2d/core/CCPrivateNode.js", "./cocos2d/core/CCScene.js", - "./cocos2d/core/CCGame.js", - "./cocos2d/core/CCScheduler.js", + "./cocos2d/core/game.js", + "./cocos2d/core/scheduler.js", "./cocos2d/core/assets/**/*", @@ -42,7 +42,7 @@ "!./cocos2d/core/load-pipeline/asset-table.js", "./cocos2d/core/physics/**/*", - + "./cocos2d/core/platform/**/*", "!./cocos2d/core/platform/BKInputManager.js", "!./cocos2d/core/platform/CCAssetLibrary.js", @@ -79,4 +79,4 @@ "./extensions/ccpool/*.js", "./extensions/spine/*.js", "./extensions/dragonbones/*.js" -] \ No newline at end of file +] diff --git a/globals.d.ts b/globals.d.ts new file mode 100644 index 0000000000..8c476a4668 --- /dev/null +++ b/globals.d.ts @@ -0,0 +1,57 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://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. + ****************************************************************************/ + +declare const CC_BUILD: boolean; +declare const CC_TEST: boolean; +declare const CC_EDITOR: boolean; +declare const CC_PREVIEW: boolean; +declare const CC_DEV: boolean; +declare const CC_DEBUG: boolean; +declare const CC_JSB: boolean; +declare const CC_WECHATGAME_SUB: boolean; +declare const CC_WECHATGAME: boolean; +declare const CC_QQPLAY: boolean; +declare const CC_RUNTIME: boolean; +declare const CC_SUPPORT_JIT: boolean; + +declare const cc: any; + +declare const _cc: any; + +type RecursivePartial = { + [P in keyof T]?: + T[P] extends Array ? Array> : + T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; +}; + +declare module "webgl-debug" { + export function makeDebugContext( + webGLRenderingContext: WebGLRenderingContext, + throwOnGLError: (err: GLenum, funcName: string, ...args: any[]) => void + ): WebGLRenderingContext; + + export function glEnumToString(glEnum: GLenum): string; +} \ No newline at end of file diff --git a/index.js b/index.js index c68709743e..f301a466cc 100644 --- a/index.js +++ b/index.js @@ -31,12 +31,16 @@ import cc from './predefine'; // LOAD ENGINE CORE export * from './cocos/core'; export * from './cocos/scene-graph'; -export * from './cocos/renderer'; +import * as renderer from './cocos/renderer'; +export { renderer }; +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'; // export default cc; diff --git a/package.json b/package.json index a4635ad24b..7e5cabdfa4 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", "watchify": "^3.7.0", + "webgl-debug": "github:cocos-creator/webgl-debug#4e535ed", "yargs": "^12.0.5" } } diff --git a/playground/camera.js b/playground/camera.js new file mode 100644 index 0000000000..ed608e6761 --- /dev/null +++ b/playground/camera.js @@ -0,0 +1,233 @@ +// camera + + "use strict"; + +var _dec, _class; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var FirstPersonCamera = (_dec = cc._decorator.ccclass(), _dec(_class = +/*#__PURE__*/ +function (_cc$Component) { + _inherits(FirstPersonCamera, _cc$Component); + + function FirstPersonCamera() { + var _this; + + _classCallCheck(this, FirstPersonCamera); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(FirstPersonCamera).call(this)); + _this._lbtnDown = false; + _this._rbtnDown = false; + _this._keyStates = new Array(128); + + _this._keyStates.fill(false); + + return _this; + } + + _createClass(FirstPersonCamera, [{ + key: "start", + value: function start() { + var _this2 = this; + + var cameraComponent = this.node.getComponent("cc.CameraComponent"); + + if (!cameraComponent) { + console.error("Cannot find cc.CameraComponent on node ".concat(this.node.name)); + } + + cc.eventManager.setEnabled(true); + var mouseListener = cc.EventListener.create({ + event: cc.EventListener.MOUSE, + onMouseDown: function onMouseDown() { + return _this2._mouseDownHandler.apply(_this2, arguments); + }, + onMouseMove: function onMouseMove() { + return _this2._mouseMoveHandler.apply(_this2, arguments); + }, + onMouseUp: function onMouseUp() { + return _this2._mouseUpHandler.apply(_this2, arguments); + }, + onMouseScroll: function onMouseScroll() { + return _this2._mouseWheelHandler.apply(_this2, arguments); + } + }); + cc.eventManager.addListener(mouseListener, 1); + var keyListener = cc.EventListener.create({ + event: cc.EventListener.KEYBOARD, + onKeyPressed: function onKeyPressed() { + return _this2._keyDownHandler.apply(_this2, arguments); + }, + onKeyReleased: function onKeyReleased() { + return _this2._keyUpHandler.apply(_this2, arguments); + } + }); + cc.eventManager.addListener(keyListener, 1); + } + }, { + key: "update", + value: function update(dt) { + var _this3 = this; + + var translationDelta = dt * 10; + + var isKeyPressing = function isKeyPressing(keystr) { + return _this3._keyStates[keystr.charCodeAt(0)]; + }; + + if (isKeyPressing("W")) { + this._translate(this._getForward(), translationDelta); + } + + if (isKeyPressing("S")) { + this._translate(this._getForward(), -translationDelta); + } + + if (isKeyPressing("A")) { + this._translate(this._getRight(), -translationDelta); + } + + if (isKeyPressing("D")) { + this._translate(this._getRight(), translationDelta); + } + + if (isKeyPressing("Q")) { + this._translate(cc.v3(0, 1, 0), -translationDelta); + } + + if (isKeyPressing("E")) { + this._translate(cc.v3(0, 1, 0), translationDelta); + } + } + }, { + key: "_mouseWheelHandler", + value: function _mouseWheelHandler(event) { + var delta = event._scrollY / 120; // forward to screen is positive + + this._translate(this._getForward(), delta); + } + }, { + key: "_mouseDownHandler", + value: function _mouseDownHandler(event) { + if (event._button === 0) { + this._lbtnDown = true; + } else if (event._button === 1) { + this._mbtnDown = true; + } else if (event._button === 2) { + cc.game.canvas.requestPointerLock(); + this._rbtnDown = true; + } + } + }, { + key: "_mouseUpHandler", + value: function _mouseUpHandler(event) { + if (event._button === 0) { + this._lbtnDown = false; + } else if (event._button === 1) { + this._mbtnDown = false; + } else if (event._button === 2) { + document.exitPointerLock(); + this._rbtnDown = false; + } + } + }, { + key: "_mouseMoveHandler", + value: function _mouseMoveHandler(event) { + var dx = event.movementX; + var dy = -event.movementY; + + if (dx !== 0) { + if (this._rbtnDown) { + this._rotateSelfHorizon(dx / 5); + } + } + + if (dy !== 0) { + if (this._rbtnDown) { + this._rotateSelfVertical(dy / 5); + } + } + } + }, { + key: "_keyDownHandler", + value: function _keyDownHandler(keycode) { + if (keycode < this._keyStates.length) { + this._keyStates[keycode] = true; + } + } + }, { + key: "_keyUpHandler", + value: function _keyUpHandler(keycode) { + if (keycode < this._keyStates.length) { + this._keyStates[keycode] = false; + } + } + }, { + key: "_translate", + value: function _translate(direction, delta) { + var position = this.node.getPosition(); + cc.vmath.vec3.scaleAndAdd(position, position, direction, delta); + this.node.setPosition(position); + } + }, { + key: "_rotateSelfHorizon", + value: function _rotateSelfHorizon(delta) { + var rotation = this.node.getRotation(); + var up = cc.v3(0, 1, 0); //const up = this._getUp(); + + cc.vmath.quat.rotateAround(rotation, rotation, up, -delta / 360.0 * 3.14159265); + this.node.setRotation(rotation); + } + }, { + key: "_rotateSelfVertical", + value: function _rotateSelfVertical(delta) { + var rotation = this.node.getRotation(); //const right = cc.v3(1, 0, 0); + + var right = this._getRight(); + + cc.vmath.quat.rotateAround(rotation, rotation, right, delta / 360.0 * 3.14159265); + this.node.setRotation(rotation); + } + }, { + key: "_getForward", + value: function _getForward() { + return this._getDirection(0, 0, -1); + } + }, { + key: "_getRight", + value: function _getRight() { + return this._getDirection(1, 0, 0); + } + }, { + key: "_getUp", + value: function _getUp() { + return this._getDirection(0, 1, 0); + } + }, { + key: "_getDirection", + value: function _getDirection(x, y, z) { + var result = cc.v3(x, y, z); + cc.vmath.vec3.transformQuat(result, result, this.node.getRotation()); + return result; + } + }]); + + return FirstPersonCamera; +}(cc.Component)) || _class); diff --git a/playground/cocos2d-x.png b/playground/cocos2d-x.png new file mode 100644 index 0000000000..6a78452419 Binary files /dev/null and b/playground/cocos2d-x.png differ diff --git a/playground/cubetexture.png b/playground/cubetexture.png new file mode 100644 index 0000000000..078b19a569 Binary files /dev/null and b/playground/cubetexture.png differ diff --git a/playground/files.js b/playground/files.js index af6dc0f92c..9964bb6342 100644 --- a/playground/files.js +++ b/playground/files.js @@ -1,6 +1,7 @@ window.files = { "aa": [ - "simple" + "simple", + "ui" ], // "animation": [ // "spec-skeleton" diff --git a/playground/gizmo.html b/playground/gizmo.html new file mode 100644 index 0000000000..e85417c61f --- /dev/null +++ b/playground/gizmo.html @@ -0,0 +1,154 @@ + + + + + gizmo + + + + + + + + + + + + + + + + diff --git a/playground/simple.html b/playground/simple.html index 7442f8e105..93fcfb7096 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -2,7 +2,7 @@ - spec-scroll-view + simple + + + + + + + + + + + + diff --git a/rollup/build-engine.ts b/rollup/build-engine.ts index 4a437caf29..7586926293 100644 --- a/rollup/build-engine.ts +++ b/rollup/build-engine.ts @@ -66,6 +66,7 @@ async function _doBundle (options: IBuildOptions) { commonjs({ namedExports: { cannon: ['CANNON', 'Shape'], + 'webgl-debug': ['makeDebugContext', 'glEnumToString'], }, }), ]; diff --git a/rollup/config.js b/rollup/config.js index 1bc59f2ff8..58c99afb04 100644 --- a/rollup/config.js +++ b/rollup/config.js @@ -60,7 +60,8 @@ export default { commonjs({ namedExports: { - 'cannon': ['CANNON'] + 'cannon': ['CANNON'], + 'webgl-debug': ['makeDebugContext', 'glEnumToString'] } }), ] diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000..19b0f7c62d --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,63 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "lib": ["es2015", "es2017", "dom"], + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + "allowJs": false, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./dist", /* Redirect output structure to the directory. */ + "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + } + //"include" : ["./source"] + //"exclude" : ["js"] + } diff --git a/tslint.json b/tslint.json index f1676c13ea..605e6fb73e 100644 --- a/tslint.json +++ b/tslint.json @@ -5,12 +5,23 @@ ], "jsRules": {}, "rules": { - "quotemark": [ true, "single" ], + "quotemark": [ + true, + "single" + ], + "one-line": [ + true, + "check-open-brace" + ], "no-console": false, "space-before-function-paren": true, "max-classes-per-file": false, "variable-name": false, - "object-literal-sort-keys": false + "object-literal-sort-keys": false, + "ban-types": false, + "no-bitwise": false, + "no-empty": false, + "radix": false, }, "rulesDirectory": [] } diff --git a/wx.d.ts b/wx.d.ts new file mode 100644 index 0000000000..12434cc7fc --- /dev/null +++ b/wx.d.ts @@ -0,0 +1,11 @@ + +declare interface IWXEventManager { + (listener: (event: Event) => void): void; +} + +declare namespace wx { + const onTouchStart: IWXEventManager; + const onTouchMove: IWXEventManager; + const onTouchEnd: IWXEventManager; + const onTouchCancel: IWXEventManager; +}