mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 08:02:39 +08:00
commit ui
This commit is contained in:
@@ -24,14 +24,16 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
var Event = require('../CCNode').EventType;
|
||||
// var Event = require('../CCNode').EventType;
|
||||
import { Node } from '../../scene-graph/index'
|
||||
|
||||
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 Event = Node.EventType;
|
||||
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;
|
||||
|
||||
@@ -42,7 +44,7 @@ var AlignMode = cc.Enum({
|
||||
});
|
||||
|
||||
// returns a readonly size of the node
|
||||
function getReadonlyNodeSize (parent) {
|
||||
function getReadonlyNodeSize(parent) {
|
||||
if (parent instanceof cc.Scene) {
|
||||
return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect;
|
||||
}
|
||||
@@ -51,12 +53,12 @@ function getReadonlyNodeSize (parent) {
|
||||
}
|
||||
}
|
||||
|
||||
function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, out_inverseScale) {
|
||||
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;;) {
|
||||
for (var node = widgetNode._parent; ;) {
|
||||
var pos = node._position;
|
||||
translateX += pos.x;
|
||||
translateY += pos.y;
|
||||
@@ -89,7 +91,7 @@ var tInverseTranslate = cc.Vec2.ZERO;
|
||||
var tInverseScale = cc.Vec2.ONE;
|
||||
|
||||
// align to borders by adjusting node's position and size (ignore rotation)
|
||||
function align (node, widget) {
|
||||
function align(node, widget) {
|
||||
var hasTarget = widget._target;
|
||||
var target;
|
||||
var inverseTranslate, inverseScale;
|
||||
@@ -225,7 +227,7 @@ function align (node, widget) {
|
||||
node.setPosition(x, y);
|
||||
}
|
||||
|
||||
function visitNode (node) {
|
||||
function visitNode(node) {
|
||||
var widget = node._widget;
|
||||
if (widget) {
|
||||
if (CC_DEV) {
|
||||
@@ -263,7 +265,7 @@ if (CC_EDITOR) {
|
||||
};
|
||||
}
|
||||
|
||||
function refreshScene () {
|
||||
function refreshScene() {
|
||||
// check animation editor
|
||||
if (CC_EDITOR && !Editor.isBuilder) {
|
||||
var AnimUtils = Editor.require('scene://utils/animation');
|
||||
@@ -433,19 +435,19 @@ var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) {
|
||||
var activeWidgets = [];
|
||||
|
||||
// updateAlignment from scene to node recursively
|
||||
function updateAlignment (node) {
|
||||
function updateAlignment(node) {
|
||||
var parent = node._parent;
|
||||
if (cc.Node.isNode(parent)) {
|
||||
updateAlignment(parent);
|
||||
}
|
||||
var widget = node._widget ||
|
||||
node.getComponent(cc.Widget); // node._widget will be null when widget is disabled
|
||||
node.getComponent(cc.Widget); // node._widget will be null when widget is disabled
|
||||
if (widget) {
|
||||
align(node, widget);
|
||||
}
|
||||
}
|
||||
|
||||
var widgetManager = cc._widgetManager = module.exports = {
|
||||
let WidgetManager = cc._widgetManager = {
|
||||
_AlignFlags: {
|
||||
TOP: TOP,
|
||||
MID: MID, // vertical center
|
||||
@@ -489,13 +491,13 @@ var widgetManager = cc._widgetManager = module.exports = {
|
||||
widget.node.off(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget);
|
||||
}
|
||||
},
|
||||
onResized () {
|
||||
onResized() {
|
||||
var scene = cc.director.getScene();
|
||||
if (scene) {
|
||||
this.refreshWidgetOnResized(scene);
|
||||
}
|
||||
},
|
||||
refreshWidgetOnResized (node) {
|
||||
refreshWidgetOnResized(node) {
|
||||
var widget = cc.Node.isNode(node) && node.getComponent(cc.Widget);
|
||||
if (widget) {
|
||||
if (widget.alignMode === AlignMode.ON_WINDOW_RESIZE) {
|
||||
@@ -513,6 +515,8 @@ var widgetManager = cc._widgetManager = module.exports = {
|
||||
AlignMode: AlignMode,
|
||||
};
|
||||
|
||||
export default WidgetManager;
|
||||
|
||||
if (CC_EDITOR) {
|
||||
module.exports._computeInverseTransForTarget = computeInverseTransForTarget;
|
||||
module.exports._getReadonlyNodeSize = getReadonlyNodeSize;
|
||||
|
||||
@@ -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;
|
||||
@@ -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 default class LabelOutline extends Component {
|
||||
_color = cc.color(255, 255, 255, 255);
|
||||
_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 () {
|
||||
set width(value) {
|
||||
this._width = value;
|
||||
this._updateRenderData();
|
||||
}
|
||||
|
||||
_updateRenderData() {
|
||||
let label = this.node.getComponent(cc.Label);
|
||||
if (label) {
|
||||
label._updateRenderData(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
cc.LabelOutline = module.exports = LabelOutline;
|
||||
cc.LabelOutline = LabelOutline;
|
||||
|
||||
@@ -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) <br/>
|
||||
* The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold. <br/>
|
||||
* Should be a float between 0 and 1. <br/>
|
||||
* 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 模式)<br/>
|
||||
* 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。<br/>
|
||||
* 该数值 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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
|
||||
@@ -23,14 +23,19 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
const macro = require('../../../platform/CCMacro');
|
||||
const textUtils = require('../../../utils/text-utils');
|
||||
// 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;
|
||||
// const Component = require('../../../components/component');
|
||||
// const Label = require('../../../components/CCLabel');
|
||||
// const LabelOutline = require('../../../components/CCLabelOutline');
|
||||
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 '../../../../2d/label/CCLabelOutline';
|
||||
|
||||
const Overflow = LabelComponent.Overflow;
|
||||
const WHITE = cc.Color.WHITE;
|
||||
const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component);
|
||||
|
||||
@@ -67,7 +72,7 @@ let _sharedLabelData;
|
||||
//
|
||||
let _canvasPool = {
|
||||
pool: [],
|
||||
get () {
|
||||
get() {
|
||||
let data = this.pool.pop();
|
||||
|
||||
if (!data) {
|
||||
@@ -81,7 +86,7 @@ let _canvasPool = {
|
||||
|
||||
return data;
|
||||
},
|
||||
put (canvas) {
|
||||
put(canvas) {
|
||||
if (this.pool.length >= 32) {
|
||||
return;
|
||||
}
|
||||
@@ -90,32 +95,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 +142,10 @@ module.exports = {
|
||||
_texture = null;
|
||||
},
|
||||
|
||||
_updateVerts () {
|
||||
_updateVerts() {
|
||||
},
|
||||
|
||||
_updateFontFamly (comp) {
|
||||
_updateFontFamly(comp) {
|
||||
if (!comp.useSystemFont) {
|
||||
if (comp.font) {
|
||||
if (comp.font._nativeAsset) {
|
||||
@@ -163,12 +167,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 +182,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 +212,7 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
|
||||
_calculateFillTextStartPosition () {
|
||||
_calculateFillTextStartPosition() {
|
||||
let lineHeight = this._getLineHeight();
|
||||
let lineCount = _splitedStrings.length;
|
||||
let labelX;
|
||||
@@ -237,7 +241,7 @@ module.exports = {
|
||||
return cc.v2(labelX, firstLinelabelY);
|
||||
},
|
||||
|
||||
_updateTexture () {
|
||||
_updateTexture() {
|
||||
_context.clearRect(0, 0, _canvas.width, _canvas.height);
|
||||
_context.font = _fontDesc;
|
||||
|
||||
@@ -271,10 +275,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 +300,7 @@ module.exports = {
|
||||
return cc.v2(labelX, firstLinelabelY);
|
||||
},
|
||||
|
||||
_updateLabelDimensions () {
|
||||
_updateLabelDimensions() {
|
||||
let paragraphedStrings = _string.split('\n');
|
||||
|
||||
if (_overflow === Overflow.RESIZE_HEIGHT) {
|
||||
@@ -323,7 +328,7 @@ module.exports = {
|
||||
_canvas.height = _canvasSize.height;
|
||||
},
|
||||
|
||||
_calculateTextBaseline () {
|
||||
_calculateTextBaseline() {
|
||||
let node = this._node;
|
||||
let hAlign;
|
||||
let vAlign;
|
||||
@@ -351,7 +356,7 @@ module.exports = {
|
||||
_context.textBaseline = vAlign;
|
||||
},
|
||||
|
||||
_calculateSplitedStrings () {
|
||||
_calculateSplitedStrings() {
|
||||
let paragraphedStrings = _string.split('\n');
|
||||
|
||||
if (_isWrapText) {
|
||||
@@ -360,9 +365,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 +377,7 @@ module.exports = {
|
||||
|
||||
},
|
||||
|
||||
_getFontDesc () {
|
||||
_getFontDesc() {
|
||||
let fontDesc = _fontSize.toString() + 'px ';
|
||||
fontDesc = fontDesc + _fontFamily;
|
||||
if (_isBold) {
|
||||
@@ -382,7 +387,7 @@ module.exports = {
|
||||
return fontDesc;
|
||||
},
|
||||
|
||||
_getLineHeight () {
|
||||
_getLineHeight() {
|
||||
let nodeSpacingY = _lineHeight;
|
||||
if (nodeSpacingY === 0) {
|
||||
nodeSpacingY = _fontSize;
|
||||
@@ -393,7 +398,7 @@ module.exports = {
|
||||
return nodeSpacingY | 0;
|
||||
},
|
||||
|
||||
_calculateParagraphLength (paragraphedStrings, ctx) {
|
||||
_calculateParagraphLength(paragraphedStrings, ctx) {
|
||||
let paragraphLength = [];
|
||||
|
||||
for (let i = 0; i < paragraphedStrings.length; ++i) {
|
||||
@@ -404,20 +409,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 +464,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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -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<br/>
|
||||
* When Button state changed:<br/>
|
||||
* If Transition type is Button.Transition.NONE, Button will do nothing<br/>
|
||||
* If Transition type is Button.Transition.COLOR, Button will change target's color<br/>
|
||||
* If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite<br/>
|
||||
* If Transition type is Button.Transition.SCALE, Button will change target node's scale<br/>
|
||||
*
|
||||
* Button will trigger 5 events:<br/>
|
||||
* Button.EVENT_TOUCH_DOWN<br/>
|
||||
* Button.EVENT_TOUCH_UP<br/>
|
||||
* Button.EVENT_HOVER_IN<br/>
|
||||
* Button.EVENT_HOVER_MOVE<br/>
|
||||
* Button.EVENT_HOVER_OUT<br/>
|
||||
*
|
||||
* !#zh
|
||||
* 按钮组件。可以被按下,或者点击。<br/>
|
||||
*
|
||||
* 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:<br/>
|
||||
* -Button.Transition.NONE // 不做任何过渡<br/>
|
||||
* -Button.Transition.COLOR // 进行颜色之间过渡<br/>
|
||||
* -Button.Transition.SPRITE // 进行精灵之间过渡<br/>
|
||||
* -Button.Transition.SCALE // 进行缩放过渡<br/>
|
||||
*
|
||||
* 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):<br/>
|
||||
* // 以下事件可以在全平台上都触发<br/>
|
||||
* -cc.Node.EventType.TOUCH_START // 按下时事件<br/>
|
||||
* -cc.Node.EventType.TOUCH_Move // 按住移动后事件<br/>
|
||||
* -cc.Node.EventType.TOUCH_END // 按下后松开后事件<br/>
|
||||
* -cc.Node.EventType.TOUCH_CANCEL // 按下取消事件<br/>
|
||||
* // 以下事件只在 PC 平台上触发<br/>
|
||||
* -cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件<br/>
|
||||
* -cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件<br/>
|
||||
* -cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件<br/>
|
||||
* -cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件<br/>
|
||||
* -cc.Node.EventType.MOUSE_UP // 鼠标松开事件<br/>
|
||||
* -cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件<br/>
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
+168
-150
@@ -24,8 +24,9 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
const misc = require('../utils/misc');
|
||||
const Component = require('./CCComponent');
|
||||
import Component from '../../components/CCComponent';
|
||||
import misc from '../../core/utils/misc';
|
||||
import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../core/data/class-decorator';
|
||||
|
||||
var GETTINGSHORTERFACTOR = 20;
|
||||
|
||||
@@ -52,117 +53,137 @@ var Direction = cc.Enum({
|
||||
* @class Scrollbar
|
||||
* @extends Component
|
||||
*/
|
||||
var Scrollbar = cc.Class({
|
||||
name: 'cc.Scrollbar',
|
||||
extends: require('./CCComponent'),
|
||||
@ccclass('cc.ScrollBarComponent')
|
||||
@executionOrder(100)
|
||||
@menu('UI/ScrollBar')
|
||||
// @executeInEditMode
|
||||
export default class ScrollBarComponent extends Component {
|
||||
@property
|
||||
_scrollView = null;
|
||||
_touching = false;
|
||||
_autoHideRemainingTime = 0;
|
||||
@property
|
||||
_handle = null;
|
||||
@property
|
||||
_direction = Direction.HORIZONTAL;
|
||||
@property
|
||||
_enableAutoHide = false;
|
||||
@property
|
||||
_autoHideTime = 1.0;
|
||||
/**
|
||||
* !#en The "handle" part of the scrollbar.
|
||||
* !#zh 作为当前滚动区域位置显示的滑块 Sprite。
|
||||
* @property {Sprite} handle
|
||||
*/
|
||||
@property({
|
||||
type: cc.Node
|
||||
})
|
||||
get handle() {
|
||||
return this._handle;
|
||||
}
|
||||
|
||||
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',
|
||||
set handle(value) {
|
||||
value = value.getComponent(cc.RenderComponent);
|
||||
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;
|
||||
}
|
||||
|
||||
statics: {
|
||||
Direction: Direction
|
||||
},
|
||||
set direction(value) {
|
||||
if (this._direction === value) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTargetScrollView: function(scrollView) {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* !#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;
|
||||
|
||||
setTargetScrollView(scrollView) {
|
||||
this._scrollView = scrollView;
|
||||
},
|
||||
}
|
||||
|
||||
_convertToScrollViewSpace: function(content) {
|
||||
_convertToScrollViewSpace(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;
|
||||
}
|
||||
},
|
||||
// _setOpacity(opacity) {
|
||||
// if (this._handle) {
|
||||
// this.node.opacity = opacity;
|
||||
// this._handle.node.opacity = opacity;
|
||||
// }
|
||||
// }
|
||||
|
||||
_onScroll: function(outOfBoundary) {
|
||||
_onScroll(outOfBoundary) {
|
||||
if (this._scrollView) {
|
||||
|
||||
var content = this._scrollView.content;
|
||||
if(content){
|
||||
if (content) {
|
||||
var contentSize = content.getContentSize();
|
||||
var scrollViewSize = this._scrollView.node.getContentSize();
|
||||
var handleNodeSize = this.node.getContentSize();
|
||||
|
||||
if(this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
|
||||
if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.enableAutoHide) {
|
||||
this._autoHideRemainingTime = this.autoHideTime;
|
||||
if (this._enableAutoHide) {
|
||||
this._autoHideRemainingTime = this._autoHideTime;
|
||||
this._setOpacity(this._opacity);
|
||||
}
|
||||
|
||||
@@ -172,14 +193,14 @@ var Scrollbar = cc.Class({
|
||||
var contentPosition = 0;
|
||||
var handleNodeMeasure = 0;
|
||||
|
||||
if (this.direction === Direction.HORIZONTAL) {
|
||||
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) {
|
||||
} else if (this._direction === Direction.VERTICAL) {
|
||||
contentMeasure = contentSize.height;
|
||||
scrollViewMeasure = scrollViewSize.height;
|
||||
handleNodeMeasure = handleNodeSize.height;
|
||||
@@ -195,85 +216,85 @@ var Scrollbar = cc.Class({
|
||||
this._updateHanlderPosition(position);
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
_updateHanlderPosition: function(position) {
|
||||
if (this.handle) {
|
||||
_updateHanlderPosition(position) {
|
||||
if (this._handle) {
|
||||
var oldPosition = this._fixupHandlerPosition();
|
||||
|
||||
this.handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y);
|
||||
this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y);
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
_fixupHandlerPosition: function() {
|
||||
_fixupHandlerPosition() {
|
||||
var barSize = this.node.getContentSize();
|
||||
var barAnchor = this.node.getAnchorPoint();
|
||||
var handleSize = this.handle.node.getContentSize();
|
||||
var handleSize = this._handle.node.getContentSize();
|
||||
|
||||
var handleParent = this.handle.node.parent;
|
||||
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) {
|
||||
if (this._direction === Direction.HORIZONTAL) {
|
||||
fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2);
|
||||
} else if (this.direction === Direction.VERTICAL) {
|
||||
} else if (this._direction === Direction.VERTICAL) {
|
||||
fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y);
|
||||
}
|
||||
|
||||
this.handle.node.setPosition(fixupPosition);
|
||||
this._handle.node.setPosition(fixupPosition);
|
||||
|
||||
return fixupPosition;
|
||||
},
|
||||
}
|
||||
|
||||
_onTouchBegan: function() {
|
||||
if (!this.enableAutoHide) {
|
||||
_onTouchBegan() {
|
||||
if (!this._enableAutoHide) {
|
||||
return;
|
||||
}
|
||||
this._touching = true;
|
||||
},
|
||||
}
|
||||
|
||||
_conditionalDisableScrollBar: function (contentSize, scrollViewSize) {
|
||||
if(contentSize.width <= scrollViewSize.width
|
||||
&& this.direction === Direction.HORIZONTAL){
|
||||
_conditionalDisableScrollBar(contentSize, scrollViewSize) {
|
||||
if (contentSize.width <= scrollViewSize.width
|
||||
&& this._direction === Direction.HORIZONTAL) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if(contentSize.height <= scrollViewSize.height
|
||||
&& this.direction === Direction.VERTICAL){
|
||||
if (contentSize.height <= scrollViewSize.height
|
||||
&& this._direction === Direction.VERTICAL) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
}
|
||||
|
||||
_onTouchEnded: function() {
|
||||
if (!this.enableAutoHide) {
|
||||
_onTouchEnded() {
|
||||
if (!this._enableAutoHide) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._touching = false;
|
||||
|
||||
if (this.autoHideTime <= 0) {
|
||||
if (this._autoHideTime <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (this._scrollView) {
|
||||
var content = this._scrollView.content;
|
||||
if(content){
|
||||
if (content) {
|
||||
var contentSize = content.getContentSize();
|
||||
var scrollViewSize = this._scrollView.node.getContentSize();
|
||||
|
||||
if(this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
|
||||
if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._autoHideRemainingTime = this.autoHideTime;
|
||||
},
|
||||
this._autoHideRemainingTime = this._autoHideTime;
|
||||
}
|
||||
|
||||
_calculateLength: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
|
||||
_calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
|
||||
var denominatorValue = contentMeasure;
|
||||
if (outOfBoundary) {
|
||||
denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR;
|
||||
@@ -281,9 +302,9 @@ var Scrollbar = cc.Class({
|
||||
|
||||
var lengthRation = scrollViewMeasure / denominatorValue;
|
||||
return handleNodeMeasure * lengthRation;
|
||||
},
|
||||
}
|
||||
|
||||
_calculatePosition: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
|
||||
_calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
|
||||
var denominatorValue = contentMeasure - scrollViewMeasure;
|
||||
if (outOfBoundary) {
|
||||
denominatorValue += Math.abs(outOfBoundary);
|
||||
@@ -296,28 +317,28 @@ var Scrollbar = cc.Class({
|
||||
}
|
||||
|
||||
var position = (handleNodeMeasure - actualLenth) * positionRatio;
|
||||
if (this.direction === Direction.VERTICAL) {
|
||||
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;
|
||||
_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) {
|
||||
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) {
|
||||
_processAutoHide(deltaTime) {
|
||||
if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) {
|
||||
return;
|
||||
} else if (this._touching) {
|
||||
return;
|
||||
@@ -325,33 +346,30 @@ var Scrollbar = cc.Class({
|
||||
|
||||
|
||||
this._autoHideRemainingTime -= deltaTime;
|
||||
if (this._autoHideRemainingTime <= this.autoHideTime) {
|
||||
if (this._autoHideRemainingTime <= this._autoHideTime) {
|
||||
this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
|
||||
var opacity = this._opacity * (this._autoHideRemainingTime / this.autoHideTime);
|
||||
var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime);
|
||||
this._setOpacity(opacity);
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
start: function() {
|
||||
if (this.enableAutoHide) {
|
||||
start() {
|
||||
if (this._enableAutoHide) {
|
||||
this._setOpacity(0);
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
hide: function() {
|
||||
hide() {
|
||||
this._autoHideRemainingTime = 0;
|
||||
this._setOpacity(0);
|
||||
},
|
||||
}
|
||||
|
||||
show: function() {
|
||||
this._autoHideRemainingTime = this.autoHideTime;
|
||||
show() {
|
||||
this._autoHideRemainingTime = this._autoHideTime;
|
||||
this._setOpacity(this._opacity);
|
||||
},
|
||||
}
|
||||
|
||||
update: function(dt) {
|
||||
update(dt) {
|
||||
this._processAutoHide(dt);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
cc.Scrollbar = module.exports = Scrollbar;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
@@ -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.
|
||||
*/
|
||||
@@ -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;
|
||||
@@ -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
|
||||
*/
|
||||
@@ -29,9 +29,9 @@ 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.
|
||||
|
||||
+66
-49
@@ -4,38 +4,39 @@ import ImageAsset from '../../assets/image-asset';
|
||||
import { Material } from '../assets/material';
|
||||
import { EffectAsset } from '../assets/effect-asset';
|
||||
import effects from './effects';
|
||||
import { SpriteFrame} from '../../assets/CCSpriteFrame';
|
||||
|
||||
let builtinResMgr = {
|
||||
// this should be called after renderer initialized
|
||||
initBuiltinRes: function(device) {
|
||||
initBuiltinRes: function (device) {
|
||||
builtinResMgr.device = device;
|
||||
// let canvas = document.createElement('canvas');
|
||||
// let context = canvas.getContext('2d');
|
||||
let canvas = document.createElement('canvas');
|
||||
let context = canvas.getContext('2d');
|
||||
|
||||
// // ============================
|
||||
// // builtin textures
|
||||
// // ============================
|
||||
// ============================
|
||||
// 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);
|
||||
// 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);
|
||||
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
|
||||
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
|
||||
// default-texture-cube
|
||||
// let defaultTextureCube = new TextureCube();
|
||||
// defaultTextureCube._uuid = 'default-texture-cube';
|
||||
// defaultTextureCube.image = {
|
||||
@@ -47,29 +48,38 @@ let builtinResMgr = {
|
||||
// bottom: canvasImage,
|
||||
// };
|
||||
|
||||
// // black texture canvas fill
|
||||
// canvas.width = canvas.height = 2;
|
||||
// context.fillStyle = '#000';
|
||||
// context.fillRect(0, 0, 2, 2);
|
||||
// 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;
|
||||
// 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 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;
|
||||
// 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;
|
||||
|
||||
let spriteFrame = new SpriteFrame();
|
||||
spriteFrame.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
|
||||
spriteFrame.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
|
||||
spriteFrame._uuid = 'default-spriteframe';
|
||||
spriteFrame.image = canvasImage;
|
||||
if (spriteFrame.onLoaded) {
|
||||
spriteFrame.onLoaded();
|
||||
}
|
||||
|
||||
// essential builtin effects
|
||||
let efxs = effects.map(e => {
|
||||
@@ -81,15 +91,22 @@ let builtinResMgr = {
|
||||
let defaultMtl = new Material();
|
||||
defaultMtl._uuid = 'default-material';
|
||||
defaultMtl.setDefines({ USE_COLOR: true });
|
||||
defaultMtl.effectAsset = efxs[0];
|
||||
defaultMtl.effectName = 'builtin-effect-unlit';
|
||||
defaultMtl.setProperty('color', cc.color('#FF00FF'));
|
||||
|
||||
// sprite material
|
||||
let spriteMtl = new Material();
|
||||
spriteMtl._uuid = 'sprite-material';
|
||||
spriteMtl.effectName = 'builtin-effect-sprite';
|
||||
defaultMtl.setProperty('mainTexture', defaultTexture);
|
||||
|
||||
let builtins = {
|
||||
// [defaultTexture._uuid]: defaultTexture,
|
||||
// [defaultTextureCube._uuid]: defaultTextureCube,
|
||||
// [blackTexture._uuid]: blackTexture,
|
||||
// [whiteTexture._uuid]: whiteTexture,
|
||||
[defaultMtl._uuid]: defaultMtl
|
||||
[defaultTexture._uuid]: defaultTexture,
|
||||
// [defaultTextureCube._uuid]: defaultTextureCub
|
||||
[blackTexture._uuid]: blackTexture,
|
||||
[whiteTexture._uuid]: whiteTexture,
|
||||
[spriteMtl._uuid]: spriteMtl,
|
||||
[spriteFrame._uuid]:spriteFrame
|
||||
};
|
||||
return Object.assign(builtinResMgr, builtins);
|
||||
},
|
||||
|
||||
+2
-1
@@ -30,6 +30,7 @@ export * from './memop';
|
||||
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;
|
||||
cc.utils = utils;
|
||||
|
||||
@@ -23,8 +23,9 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
require('./sprite');
|
||||
require('./mask-assembler');
|
||||
require('./graphics');
|
||||
require('./label');
|
||||
require('./motion-streak');
|
||||
// require('./sprite');
|
||||
import './sprite/index';
|
||||
// require('./mask-assembler');
|
||||
// require('./graphics');
|
||||
// import './label/index';
|
||||
// require('./motion-streak');
|
||||
+33
-51
@@ -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;
|
||||
+13
-12
@@ -23,14 +23,17 @@
|
||||
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 ttfAssembler from './ttf';
|
||||
import bmfontAssembler from './bmfont';
|
||||
|
||||
var labelAssembler = {
|
||||
getAssembler (comp) {
|
||||
export default labelAssembler = {
|
||||
getAssembler(comp) {
|
||||
let assembler = ttfAssembler;
|
||||
|
||||
|
||||
if (comp.font instanceof cc.BitmapFont) {
|
||||
assembler = bmfontAssembler;
|
||||
}
|
||||
@@ -39,11 +42,9 @@ var labelAssembler = {
|
||||
},
|
||||
|
||||
// Skip invalid labels (without own _assembler)
|
||||
updateRenderData (label) {
|
||||
return label.__allocedDatas;
|
||||
}
|
||||
// updateRenderData(label) {
|
||||
// return label.__allocedDatas;
|
||||
// }
|
||||
};
|
||||
|
||||
Label._assembler = labelAssembler;
|
||||
|
||||
module.exports = labelAssembler;
|
||||
LabelComponent._assembler = labelAssembler;
|
||||
+16
-29
@@ -23,11 +23,14 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
const js = require('../../../../platform/js');
|
||||
const ttfUtls = require('../../../utils/label/ttf');
|
||||
import * as js from '../../../../core/utils/js';
|
||||
import ttfUtls from '../../../../2d/renderer/utils/label/ttf';
|
||||
import { fillMeshVertices3D } from '../utils';
|
||||
|
||||
module.exports = js.addon({
|
||||
createData (comp) {
|
||||
const WHITE = cc.color(255, 255, 255, 255);
|
||||
|
||||
let ttf = {
|
||||
createData(comp) {
|
||||
let renderData = comp.requestRenderData();
|
||||
|
||||
renderData.dataLength = 4;
|
||||
@@ -46,32 +49,11 @@ module.exports = js.addon({
|
||||
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;
|
||||
}
|
||||
fillBuffers(comp, /*renderer*/buffer) {
|
||||
fillMeshVertices3D(comp.node, /*renderer._quadBuffer3D*/buffer, comp._renderData, WHITE._val);
|
||||
},
|
||||
|
||||
_updateVerts (comp) {
|
||||
_updateVerts(comp) {
|
||||
let renderData = comp._renderData;
|
||||
|
||||
let node = comp.node,
|
||||
@@ -90,4 +72,9 @@ module.exports = js.addon({
|
||||
data[3].x = width - appx;
|
||||
data[3].y = height - appy;
|
||||
}
|
||||
}, ttfUtls);
|
||||
}
|
||||
|
||||
js.addon(ttf, ttfUtls);
|
||||
|
||||
export default ttf;
|
||||
|
||||
+109
-91
@@ -1,7 +1,7 @@
|
||||
/****************************************************************************
|
||||
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,
|
||||
@@ -22,27 +22,29 @@
|
||||
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 Sprite = require('../../../../components/CCSprite');
|
||||
const FillType = Sprite.FillType;
|
||||
// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager');
|
||||
import { fillVerticesWithoutCalc3D } from '../utils';
|
||||
import { vec3 } from '../../../../core/vmath/index';
|
||||
|
||||
const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
|
||||
|
||||
module.exports = {
|
||||
let barFilled = {
|
||||
useModel: false,
|
||||
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) {
|
||||
@@ -70,7 +72,7 @@ module.exports = {
|
||||
fillRange = fillRange < 0.0 ? 0.0 : fillRange;
|
||||
fillRange = fillRange - fillStart;
|
||||
fillRange = fillRange < 0 ? 0 : fillRange;
|
||||
|
||||
|
||||
let fillEnd = fillStart + fillRange;
|
||||
fillEnd = fillEnd > 1 ? 1 : fillEnd;
|
||||
|
||||
@@ -79,19 +81,19 @@ module.exports = {
|
||||
}
|
||||
if (vertDirty) {
|
||||
this.updateVerts(sprite, fillStart, fillEnd);
|
||||
this.updateWorldVerts(sprite);
|
||||
// this.updateWorldVerts(sprite);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
updateUVs (sprite, fillStart, fillEnd) {
|
||||
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 atlasWidth = spriteFrame.width;
|
||||
let atlasHeight = spriteFrame.height;
|
||||
let textureRect = spriteFrame._rect;
|
||||
//uv computation should take spritesheet into account.
|
||||
let ul, vb, ur, vt;
|
||||
@@ -113,32 +115,50 @@ module.exports = {
|
||||
ur = (textureRect.x + textureRect.width) / atlasWidth;
|
||||
vt = (textureRect.y) / atlasHeight;
|
||||
|
||||
quadUV0 = quadUV4 = ul;
|
||||
quadUV2 = quadUV6 = ur;
|
||||
quadUV1 = quadUV3 = vb;
|
||||
quadUV5 = quadUV7 = vt;
|
||||
// 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;
|
||||
data[0].u = ul + (ur - ul) * fillStart;
|
||||
data[0].v = vb;
|
||||
data[1].u = ul + (ur - ul) * fillEnd;
|
||||
data[1].v = vb;
|
||||
data[2].u = ul + (ur - ul) * fillStart;
|
||||
data[2].v = vt;
|
||||
data[3].u = ul + (ur - ul) * fillEnd;
|
||||
data[3].v = vt;
|
||||
|
||||
// data[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart;
|
||||
// data[0].v = quadUV1 + (quadUV3 - quadUV1) * fillStart;
|
||||
// data[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd;
|
||||
// data[1].v = quadUV1 + (quadUV3 - quadUV1) * fillEnd;
|
||||
// data[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart;
|
||||
// data[2].v = quadUV5 + (quadUV7 - quadUV5) * fillStart;
|
||||
// data[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd;
|
||||
// data[3].v = quadUV5 + (quadUV7 - quadUV5) * fillEnd;
|
||||
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;
|
||||
data[0].u = ul
|
||||
data[0].v = vb + (vt - vb) * fillStart;
|
||||
data[1].u = ur;
|
||||
data[1].v = vb + (vt - vb) * fillStart;
|
||||
data[2].u = ul;
|
||||
data[2].v = vb + (vt - vb) * fillEnd;
|
||||
data[3].u = ur;
|
||||
data[3].v = vb + (vt - vb) * fillEnd;
|
||||
|
||||
// data[0].u = quadUV0 + (quadUV4 - quadUV0) * fillStart;
|
||||
// data[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart;
|
||||
// data[1].u = quadUV2 + (quadUV6 - quadUV2) * fillStart;
|
||||
// data[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart;
|
||||
// data[2].u = quadUV0 + (quadUV4 - quadUV0) * fillEnd;
|
||||
// data[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd;
|
||||
// data[3].u = quadUV2 + (quadUV6 - quadUV2) * fillEnd;
|
||||
// data[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd;
|
||||
break;
|
||||
default:
|
||||
cc.errorID(2626);
|
||||
@@ -148,7 +168,7 @@ module.exports = {
|
||||
renderData.uvDirty = false;
|
||||
},
|
||||
|
||||
updateVerts (sprite, fillStart, fillEnd) {
|
||||
updateVerts(sprite, fillStart, fillEnd) {
|
||||
let renderData = sprite._renderData,
|
||||
data = renderData._data,
|
||||
node = sprite.node,
|
||||
@@ -156,7 +176,7 @@ module.exports = {
|
||||
appx = node.anchorX * width, appy = node.anchorY * height;
|
||||
|
||||
let l = -appx, b = -appy,
|
||||
r = width-appx, t = height-appy;
|
||||
r = width - appx, t = height - appy;
|
||||
|
||||
let progressStart, progressEnd;
|
||||
switch (sprite._fillType) {
|
||||
@@ -179,70 +199,68 @@ module.exports = {
|
||||
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;
|
||||
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;
|
||||
},
|
||||
|
||||
createData (sprite) {
|
||||
createData(sprite) {
|
||||
let renderData = sprite.requestRenderData();
|
||||
// 0-4 for world verts
|
||||
// 5-8 for local verts
|
||||
renderData.dataLength = 8;
|
||||
renderData.dataLength = 4;
|
||||
renderData.vertexCount = 4;
|
||||
renderData.indiceCount = 6;
|
||||
|
||||
let data = renderData._data;
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
data[i].z = 0;
|
||||
}
|
||||
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;
|
||||
}
|
||||
},
|
||||
// updateWorldVerts(sprite) {
|
||||
// let node = sprite.node,
|
||||
// data = sprite._renderData._data;
|
||||
|
||||
fillBuffers (sprite, renderer) {
|
||||
if (renderer.worldMatDirty) {
|
||||
this.updateWorldVerts(sprite);
|
||||
}
|
||||
// node._updateWorldMatrix();
|
||||
// let matrix = node._worldMatrix;
|
||||
// for (let i = 0; i < 4; i++) {
|
||||
// let local = data[i + 4];
|
||||
// let world = data[i];
|
||||
// vec3.transformMat4(world, local, matrix);
|
||||
// }
|
||||
// },
|
||||
|
||||
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;
|
||||
fillBuffers(sprite, /*renderer*/buffer) {
|
||||
// if (renderer.worldMatDirty) {
|
||||
// this.updateWorldVerts(sprite);
|
||||
// }
|
||||
|
||||
buffer.request(4, 6);
|
||||
// buffer
|
||||
let /*buffer = renderer._meshBuffer3D,*/
|
||||
indiceOffset = buffer.indiceOffset,
|
||||
vertexId = buffer.vertexOffset;
|
||||
|
||||
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;
|
||||
|
||||
// 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;
|
||||
}
|
||||
let 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;
|
||||
}
|
||||
};
|
||||
|
||||
export default barFilled;
|
||||
+37
-34
@@ -23,53 +23,56 @@
|
||||
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 simpleRenderUtil from './simple';
|
||||
import slicedRenderUtil from './sliced';
|
||||
import tiledRenderUtil from './tiled';
|
||||
import radialFilledRenderUtil from './radial-filled';
|
||||
import barFilledRenderUtil from './bar-filled';
|
||||
import meshRenderUtil from './mesh';
|
||||
|
||||
// Inline all type switch to avoid jit deoptimization during inlined function change
|
||||
|
||||
let spriteAssembler = {
|
||||
getAssembler (sprite) {
|
||||
const spriteAssembler = {
|
||||
getAssembler(sprite) {
|
||||
let util = simpleRenderUtil;
|
||||
|
||||
switch (sprite.type) {
|
||||
case SpriteType.SLICED:
|
||||
util = slicedRenderUtil;
|
||||
break;
|
||||
case SpriteType.TILED:
|
||||
util = tiledRenderUtil;
|
||||
break;
|
||||
case SpriteType.FILLED:
|
||||
if (sprite._fillType === FillType.RADIAL) {
|
||||
util = radialFilledRenderUtil;
|
||||
}
|
||||
else {
|
||||
util = barFilledRenderUtil;
|
||||
}
|
||||
break;
|
||||
case SpriteType.MESH:
|
||||
util = meshRenderUtil;
|
||||
break;
|
||||
}
|
||||
|
||||
// switch (sprite.type) {
|
||||
// case SpriteType.SLICED:
|
||||
// util = slicedRenderUtil;
|
||||
// break;
|
||||
// // case SpriteType.TILED:
|
||||
// // util = tiledRenderUtil;
|
||||
// // break;
|
||||
// case SpriteType.FILLED:
|
||||
// // if (sprite._fillType === FillType.RADIAL) {
|
||||
// // util = radialFilledRenderUtil;
|
||||
// // }
|
||||
// // else {
|
||||
// util = barFilledRenderUtil;
|
||||
// // }
|
||||
// break;
|
||||
// // case SpriteType.MESH:
|
||||
// // util = meshRenderUtil;
|
||||
// // break;
|
||||
// }
|
||||
|
||||
return util;
|
||||
},
|
||||
|
||||
// Skip invalid sprites (without own _assembler)
|
||||
updateRenderData (sprite) {
|
||||
updateRenderData(sprite) {
|
||||
return sprite.__allocedDatas;
|
||||
}
|
||||
};
|
||||
|
||||
Sprite._assembler = spriteAssembler;
|
||||
export {
|
||||
spriteAssembler
|
||||
}
|
||||
|
||||
module.exports = spriteAssembler;
|
||||
SpriteComponent._assembler = spriteAssembler;
|
||||
+41
-61
@@ -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];
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default mesh;
|
||||
@@ -0,0 +1,341 @@
|
||||
/****************************************************************************
|
||||
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 { fillVertices3D } from '../utils';
|
||||
|
||||
const PI_2 = Math.PI * 2;
|
||||
|
||||
let _vertPos = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)];
|
||||
let _vertices = [0, 0, 0, 0];
|
||||
let _uvs = [0, 0, 0, 0, 0, 0, 0, 0];
|
||||
let _intersectPoint_1 = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)];
|
||||
let _intersectPoint_2 = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)];
|
||||
let _center = cc.v2(0, 0);
|
||||
let _triangles = [];
|
||||
|
||||
function _calcInsectedPoints(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 (cosAngle !== 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 (sinAngle !== 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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
function _calculateVertices(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 = _vertices;
|
||||
vertices[0] = l;
|
||||
vertices[1] = b;
|
||||
vertices[2] = r;
|
||||
vertices[3] = t;
|
||||
|
||||
let 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;
|
||||
|
||||
_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;
|
||||
|
||||
_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];
|
||||
}
|
||||
}
|
||||
|
||||
function _calculateUVs(spriteFrame) {
|
||||
let atlasWidth = spriteFrame.width;
|
||||
let atlasHeight = spriteFrame.height;
|
||||
let textureRect = spriteFrame._rect;
|
||||
|
||||
let u0, u1, v0, v1;
|
||||
let 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) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
function _generateTriangle(data, offset, vert0, vert1, vert2) {
|
||||
let vertices = _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);
|
||||
_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) {
|
||||
let uvs = _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;
|
||||
}
|
||||
|
||||
let radialFilled = {
|
||||
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 (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
|
||||
_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) {
|
||||
let triangle = _triangles[triangleIndex];
|
||||
if (!triangle) {
|
||||
continue;
|
||||
}
|
||||
//all in
|
||||
if (fillRange >= PI_2) {
|
||||
renderData.dataLength = offset + 3;
|
||||
_generateTriangle(data, 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(data, offset, _center, _vertPos[triangle[0]], _intersectPoint_2[triangleIndex]);
|
||||
} else {
|
||||
//startAngle to endAngle
|
||||
_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
|
||||
_generateTriangle(data, offset, _center, _intersectPoint_1[triangleIndex], _vertPos[triangle[1]]);
|
||||
offset += 3;
|
||||
} else {
|
||||
renderData.dataLength = offset + 3;
|
||||
//fillStart to fillEnd
|
||||
_generateTriangle(data, 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, /*renderer*/buffer) {
|
||||
let node = comp.node,
|
||||
color = comp._color._val,
|
||||
/*buffer = renderer._meshBuffer3D,*/
|
||||
renderData = comp._renderData;
|
||||
|
||||
let indiceOffset = buffer.indiceOffset,
|
||||
vertexId = buffer.vertexOffset;
|
||||
fillVertices3D(node, buffer, renderData, color);
|
||||
|
||||
// buffer data may be realloc, need get reference after request.
|
||||
let ibuf = buffer._iData;
|
||||
for (let i = 0; i < renderData.dataLength; i++) {
|
||||
ibuf[indiceOffset + i] = vertexId + i;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
export default radialFilled;
|
||||
@@ -0,0 +1,169 @@
|
||||
/****************************************************************************
|
||||
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 { vec3 } from '../../../../core/vmath/index';
|
||||
// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager');
|
||||
let matrix = cc.mat4();
|
||||
|
||||
let simple = {
|
||||
useModel: false,
|
||||
|
||||
createData(sprite) {
|
||||
let renderData = sprite.requestRenderData();
|
||||
renderData.dataLength = 4;
|
||||
renderData.vertexCount = 4;
|
||||
renderData.indiceCount = 6;
|
||||
return renderData;
|
||||
},
|
||||
|
||||
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: (function () {
|
||||
let vec3_temps = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
vec3_temps.push(vec3.create());
|
||||
}
|
||||
return function (sprite, /*renderer*/buffer) {
|
||||
let data = sprite._renderData._data,
|
||||
node = sprite.node,
|
||||
color = sprite._color;
|
||||
|
||||
node.getWorldMatrix(matrix);
|
||||
|
||||
let /*buffer = renderer._meshBuffer3D,*/
|
||||
vertexOffset = buffer.byteOffset >> 2,
|
||||
indiceOffset = buffer.indiceOffset,
|
||||
vertexId = buffer.vertexOffset;
|
||||
|
||||
buffer.request(4, 6);
|
||||
|
||||
// buffer data may be realloc, need get reference after request.
|
||||
let vbuf = buffer.vData,
|
||||
uintbuf = buffer.uintVData,
|
||||
ibuf = buffer.iData;
|
||||
|
||||
let data0 = data[0], data3 = data[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
|
||||
let uv = sprite._spriteFrame.uv;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
// vertex
|
||||
let vertex = vec3_temps[i];
|
||||
vec3.transformMat4(vertex, vertex, matrix);
|
||||
|
||||
vbuf[vertexOffset++] = vertex.x;
|
||||
vbuf[vertexOffset++] = vertex.y;
|
||||
vbuf[vertexOffset++] = vertex.z;
|
||||
|
||||
// uv
|
||||
let 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;
|
||||
};
|
||||
})(),
|
||||
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
export default simple;
|
||||
+77
-49
@@ -23,59 +23,63 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
|
||||
// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
|
||||
import { vec3 } from '../../../../core/vmath/index';
|
||||
|
||||
module.exports = {
|
||||
const vec3_temp = vec3.create();
|
||||
|
||||
let sliced = {
|
||||
useModel: false,
|
||||
|
||||
createData (sprite) {
|
||||
createData(sprite) {
|
||||
let renderData = sprite.requestRenderData();
|
||||
// 0-4 for local verts
|
||||
// 5-20 for world verts
|
||||
renderData.dataLength = 20;
|
||||
// renderData.dataLength = 20;
|
||||
renderData.dataLength = 16;
|
||||
|
||||
renderData.vertexCount = 16;
|
||||
renderData.indiceCount = 54;
|
||||
return renderData;
|
||||
},
|
||||
|
||||
updateRenderData (sprite, batchData) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
// this.updateWorldVerts(sprite);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
updateVerts (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);
|
||||
@@ -84,55 +88,78 @@ module.exports = {
|
||||
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;
|
||||
|
||||
let value = [
|
||||
cc.v3(-appx, -appy, 0),
|
||||
cc.v3(leftWidth * xScale - appx, bottomHeight * yScale - appy, 0),
|
||||
cc.v3(leftWidth * xScale - appx + sizableWidth, bottomHeight * yScale - appy + sizableHeight, 0),
|
||||
cc.v3(width - appx, height - appy, 0)
|
||||
];
|
||||
|
||||
for (let row = 0; row < 4; ++row) {
|
||||
let rowD = value[row];
|
||||
for (let col = 0; col < 4; ++col) {
|
||||
let colD = value[col];
|
||||
let world = data[row * 4 + col];
|
||||
vec3.set(world, colD.x, rowD.y, 0);
|
||||
// vec3.transformMat4(world, vec3_temp, matrix);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
fillBuffers(sprite, /*renderer*/buffer) {
|
||||
// if (renderer.worldMatDirty) {
|
||||
this.updateWorldVerts(sprite);
|
||||
// }
|
||||
|
||||
let renderData = sprite._renderData,
|
||||
node = sprite.node,
|
||||
color = sprite._color._val,
|
||||
data = renderData._data;
|
||||
|
||||
let buffer = renderer._meshBuffer,
|
||||
let /*buffer = is3DNode ? renderer._meshBuffer3D : renderer._meshBuffer,*/
|
||||
vertexOffset = buffer.byteOffset >> 2,
|
||||
vertexCount = renderData.vertexCount;
|
||||
|
||||
let indiceOffset = buffer.indiceOffset,
|
||||
vertexCount = renderData.vertexCount,
|
||||
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,
|
||||
uintbuf = buffer._uintVData,
|
||||
ibuf = buffer._iData;
|
||||
|
||||
for (let i = 4; i < 20; ++i) {
|
||||
// for (let i = 4; i < 20; ++i) {
|
||||
for (let i = 0; i < 16; ++i) {
|
||||
let vert = data[i];
|
||||
let uvs = uvSliced[i - 4];
|
||||
// let uvs = uvSliced[i - 4];
|
||||
let uvs = uvSliced[i];
|
||||
|
||||
vbuf[vertexOffset++] = vert.x;
|
||||
vbuf[vertexOffset++] = vert.y;
|
||||
vbuf[vertexOffset++] = vert.z;
|
||||
vbuf[vertexOffset++] = uvs.u;
|
||||
vbuf[vertexOffset++] = uvs.v;
|
||||
uintbuf[vertexOffset++] = color;
|
||||
}
|
||||
|
||||
for (let r = 0; r < 3; ++r) {
|
||||
for (let c = 0; c < 3; ++c) {
|
||||
let start = vertexId + r*4 + c;
|
||||
let start = vertexId + r * 4 + c;
|
||||
ibuf[indiceOffset++] = start;
|
||||
ibuf[indiceOffset++] = start + 1;
|
||||
ibuf[indiceOffset++] = start + 4;
|
||||
@@ -143,22 +170,23 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
|
||||
updateWorldVerts (sprite) {
|
||||
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;
|
||||
|
||||
|
||||
// node._updateWorldMatrix();
|
||||
// let matrix = node._worldMatrix;
|
||||
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;
|
||||
let world = data[4 + row * 4 + col];
|
||||
|
||||
vec3.set(vec3_temp, colD.x, rowD.y, 0);
|
||||
// vec3.transformMat4(world, vec3_temp, matrix);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default sliced;
|
||||
@@ -0,0 +1,222 @@
|
||||
/****************************************************************************
|
||||
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 { vec3 } from '../../../../core/vmath/index';
|
||||
|
||||
let tilled = {
|
||||
useModel: false,
|
||||
|
||||
vertexOffset: 6,
|
||||
uvOffset: 3,
|
||||
colorOffset: 5,
|
||||
|
||||
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 node = sprite.node,
|
||||
// contentWidth = Math.abs(node.width),
|
||||
// contentHeight = Math.abs(node.height),
|
||||
contentWidth = Math.abs(node.width),
|
||||
contentHeight = Math.abs(node.height),
|
||||
appx = node.anchorX * contentWidth,
|
||||
appy = node.anchorY * contentHeight;
|
||||
node._updateWorldMatrix();
|
||||
|
||||
let rect = frame._rect,
|
||||
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*/buffer) {
|
||||
let node = sprite.node,
|
||||
color = sprite._color._val,
|
||||
renderData = sprite._renderData,
|
||||
data = renderData._data;
|
||||
|
||||
// buffer
|
||||
let /*buffer = is3DNode ? renderer._meshBuffer3D : renderer._meshBuffer,*/
|
||||
vertexOffset = buffer.byteOffset >> 2,
|
||||
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,
|
||||
uintbuf = buffer._uintVData,
|
||||
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;
|
||||
|
||||
this.fillVertices(vbuf, vertexOffset, matrix, row, col, data);
|
||||
|
||||
let offset = this.vertexOffset, uvOffset = this.uvOffset, colorOffset = this.colorOffset;
|
||||
let offset1 = offset, offset2 = offset * 2, offset3 = offset * 3, offset4 = offset * 4;
|
||||
let coefu, coefv;
|
||||
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);
|
||||
|
||||
let vertexOffsetU = vertexOffset + uvOffset;
|
||||
let 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];
|
||||
}
|
||||
// color
|
||||
uintbuf[vertexOffset + colorOffset] = color;
|
||||
uintbuf[vertexOffset + colorOffset + offset1] = color;
|
||||
uintbuf[vertexOffset + colorOffset + offset2] = color;
|
||||
uintbuf[vertexOffset + colorOffset + offset3] = color;
|
||||
vertexOffset += offset4;
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
},
|
||||
|
||||
fillVertices: (function () {
|
||||
let vec3_temps = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
vec3_temps.push(vec3.create());
|
||||
}
|
||||
return function (vbuf, vertexOffset, matrix, row, col, 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;
|
||||
}
|
||||
}
|
||||
};
|
||||
})(),
|
||||
};
|
||||
|
||||
export default tilled;
|
||||
@@ -0,0 +1,193 @@
|
||||
|
||||
import { vec3, mat4 } from '../../../core/vmath/index';
|
||||
|
||||
let vec3_temp = vec3.create();
|
||||
let _worldMatrix = mat4.create();
|
||||
|
||||
export function fillVertices(node, buffer, renderData, color) {
|
||||
let data = renderData._data,
|
||||
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,
|
||||
uintbuf = buffer._uintVData;
|
||||
|
||||
// let matrix = node._worldMatrix;
|
||||
node.getWorldMatrix(_worldMatrix);
|
||||
let matrix = _worldMatrix;
|
||||
let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
|
||||
tx = matrix.m12, ty = matrix.m13;
|
||||
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;
|
||||
uintbuf[vertexOffset++] = color;
|
||||
}
|
||||
}
|
||||
|
||||
export function fillMeshVertices(node, buffer, renderData, color) {
|
||||
let data = renderData._data,
|
||||
vertexOffset = buffer.byteOffset >> 2;
|
||||
|
||||
let vertexCount = renderData.vertexCount,
|
||||
indiceOffset = buffer.indiceOffset,
|
||||
vertexId = buffer.vertexOffset;
|
||||
|
||||
buffer.request(vertexCount, renderData.indiceCount);
|
||||
|
||||
// buffer data may be realloc, need get reference after request.
|
||||
let vbuf = buffer._vData,
|
||||
uintbuf = buffer._uintVData,
|
||||
ibuf = buffer._iData;
|
||||
|
||||
// let matrix = node._worldMatrix;
|
||||
node.getWorldMatrix(_worldMatrix);
|
||||
let matrix = _worldMatrix;
|
||||
let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
|
||||
tx = matrix.m12, ty = matrix.m13;
|
||||
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;
|
||||
uintbuf[vertexOffset++] = color;
|
||||
}
|
||||
|
||||
// fill indice data
|
||||
for (let i = 0, count = vertexCount / 4; i < count; i++) {
|
||||
let 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) {
|
||||
let data = renderData._data,
|
||||
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,
|
||||
uintbuf = buffer._uintVData;
|
||||
|
||||
// let matrix = node._worldMatrix;
|
||||
// node.getWorldMatrix(_worldMatrix);
|
||||
|
||||
for (let i = 0; i < vertexCount; i++) {
|
||||
let vert = data[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;
|
||||
uintbuf[vertexOffset++] = color;
|
||||
}
|
||||
}
|
||||
|
||||
export function fillMeshVertices3D(node, buffer, renderData, color) {
|
||||
let data = renderData._data,
|
||||
vertexOffset = buffer.byteOffset >> 2;
|
||||
|
||||
let vertexCount = renderData.vertexCount,
|
||||
indiceOffset = buffer.indiceOffset,
|
||||
vertexId = buffer.vertexOffset;
|
||||
|
||||
buffer.request(vertexCount, renderData.indiceCount);
|
||||
|
||||
// buffer data may be realloc, need get reference after request.
|
||||
let vbuf = buffer._vData,
|
||||
uintbuf = buffer._uintVData,
|
||||
ibuf = buffer._iData;
|
||||
|
||||
// let matrix = node._worldMatrix;
|
||||
// node.getWorldMatrix(_worldMatrix);
|
||||
|
||||
for (let i = 0; i < vertexCount; i++) {
|
||||
let vert = data[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;
|
||||
uintbuf[vertexOffset++] = color;
|
||||
}
|
||||
|
||||
// fill indice data
|
||||
for (let i = 0, count = vertexCount / 4; i < count; i++) {
|
||||
let 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) {
|
||||
let data = renderData._data,
|
||||
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,
|
||||
uintbuf = buffer._uintVData;
|
||||
|
||||
for (let i = 0; i < vertexCount; i++) {
|
||||
let vert = data[i];
|
||||
vbuf[vertexOffset++] = vert.x;
|
||||
vbuf[vertexOffset++] = vert.y;
|
||||
vbuf[vertexOffset++] = vert.u;
|
||||
vbuf[vertexOffset++] = vert.v;
|
||||
uintbuf[vertexOffset++] = color;
|
||||
}
|
||||
}
|
||||
|
||||
export function fillVerticesWithoutCalc3D(node, buffer, renderData, color) {
|
||||
let data = renderData._data,
|
||||
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,
|
||||
uintbuf = buffer._uintVData;
|
||||
|
||||
for (let i = 0; i < vertexCount; i++) {
|
||||
let vert = data[i];
|
||||
vbuf[vertexOffset++] = vert.x;
|
||||
vbuf[vertexOffset++] = vert.y;
|
||||
vbuf[vertexOffset++] = vert.z;
|
||||
vbuf[vertexOffset++] = vert.u;
|
||||
vbuf[vertexOffset++] = vert.v;
|
||||
uintbuf[vertexOffset++] = color;
|
||||
}
|
||||
}
|
||||
|
||||
// module.exports = {
|
||||
// fillVertices: fillVertices,
|
||||
// fillMeshVertices: fillMeshVertices,
|
||||
// fillVertices3D: fillVertices3D,
|
||||
// fillMeshVertices3D: fillMeshVertices3D,
|
||||
// fillVerticesWithoutCalc: fillVerticesWithoutCalc,
|
||||
// fillVerticesWithoutCalc3D: fillVerticesWithoutCalc3D
|
||||
// };
|
||||
@@ -0,0 +1,802 @@
|
||||
/****************************************************************************
|
||||
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 { lerp } from '../../../core/utils/misc';
|
||||
import { Color, 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
|
||||
*/
|
||||
const 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<br/>
|
||||
* When Button state changed:<br/>
|
||||
* If Transition type is Button.Transition.NONE, Button will do nothing<br/>
|
||||
* If Transition type is Button.Transition.COLOR, Button will change target's color<br/>
|
||||
* If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite<br/>
|
||||
* If Transition type is Button.Transition.SCALE, Button will change target node's scale<br/>
|
||||
*
|
||||
* Button will trigger 5 events:<br/>
|
||||
* Button.EVENT_TOUCH_DOWN<br/>
|
||||
* Button.EVENT_TOUCH_UP<br/>
|
||||
* Button.EVENT_HOVER_IN<br/>
|
||||
* Button.EVENT_HOVER_MOVE<br/>
|
||||
* Button.EVENT_HOVER_OUT<br/>
|
||||
*
|
||||
* !#zh
|
||||
* 按钮组件。可以被按下,或者点击。<br/>
|
||||
*
|
||||
* 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:<br/>
|
||||
* -Button.Transition.NONE // 不做任何过渡<br/>
|
||||
* -Button.Transition.COLOR // 进行颜色之间过渡<br/>
|
||||
* -Button.Transition.SPRITE // 进行精灵之间过渡<br/>
|
||||
* -Button.Transition.SCALE // 进行缩放过渡<br/>
|
||||
*
|
||||
* 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):<br/>
|
||||
* // 以下事件可以在全平台上都触发<br/>
|
||||
* -cc.NodeUI.EventType.TOUCH_START // 按下时事件<br/>
|
||||
* -cc.NodeUI.EventType.TOUCH_Move // 按住移动后事件<br/>
|
||||
* -cc.NodeUI.EventType.TOUCH_END // 按下后松开后事件<br/>
|
||||
* -cc.NodeUI.EventType.TOUCH_CANCEL // 按下取消事件<br/>
|
||||
* // 以下事件只在 PC 平台上触发<br/>
|
||||
* -cc.NodeUI.EventType.MOUSE_DOWN // 鼠标按下时事件<br/>
|
||||
* -cc.NodeUI.EventType.MOUSE_MOVE // 鼠标按住移动后事件<br/>
|
||||
* -cc.NodeUI.EventType.MOUSE_ENTER // 鼠标进入目标事件<br/>
|
||||
* -cc.NodeUI.EventType.MOUSE_LEAVE // 鼠标离开目标事件<br/>
|
||||
* -cc.NodeUI.EventType.MOUSE_UP // 鼠标松开事件<br/>
|
||||
* -cc.NodeUI.EventType.MOUSE_WHEEL // 鼠标滚轮事件<br/>
|
||||
*
|
||||
* @class Button
|
||||
* @extends Component
|
||||
* @example
|
||||
*
|
||||
* // Add an event to the button.
|
||||
* button.node.on(cc.NodeUI.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 default 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: number) {
|
||||
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 = cc.color(214, 214, 214);
|
||||
@property
|
||||
public _hoverColor: Color = cc.color(211, 211, 211);
|
||||
@property
|
||||
public _pressColor: Color = cc.Color.WHITE;
|
||||
@property
|
||||
public _disabledColor: Color = cc.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 = 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 = cc.color();
|
||||
public _toColor: Color = cc.color();
|
||||
public _time: number = 0;
|
||||
public _transitionFinished: boolean = true;
|
||||
public _fromScale: Vec3 = cc.v3();
|
||||
public _toScale: Vec3 = cc.v3();
|
||||
public _originalScale: Vec3 = cc.v3();
|
||||
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', function (comp) {
|
||||
if (this._transition === Transition.SPRITE) {
|
||||
this._normalSprite = comp.spriteFrame;
|
||||
}
|
||||
}.bind(this));
|
||||
}
|
||||
}
|
||||
|
||||
public onDisable () {
|
||||
this._resetState();
|
||||
|
||||
if (!CC_EDITOR) {
|
||||
this.node.off(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
|
||||
this.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMove, this);
|
||||
this.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
|
||||
this.node.off(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
|
||||
|
||||
this.node.off(cc.NodeUI.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
|
||||
this.node.off(cc.NodeUI.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
|
||||
} else {
|
||||
this.node.off('spriteframe-changed');
|
||||
}
|
||||
}
|
||||
|
||||
public update (dt) {
|
||||
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.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
|
||||
this.node.on(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMove, this);
|
||||
this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
|
||||
this.node.on(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
|
||||
|
||||
this.node.on(cc.NodeUI.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
|
||||
this.node.on(cc.NodeUI.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.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
|
||||
const touch = event.touch;
|
||||
const hit = this.node._hitTest(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.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.
|
||||
*/
|
||||
@@ -0,0 +1,300 @@
|
||||
/****************************************************************************
|
||||
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 { 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 } from '../../../renderer/scene/camera';
|
||||
|
||||
/**
|
||||
* !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。
|
||||
* 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。
|
||||
*
|
||||
* @class Canvas
|
||||
* @extends Component
|
||||
*/
|
||||
@ccclass('cc.CanvasComponent')
|
||||
@executionOrder(100)
|
||||
@menu('UI/Canvas')
|
||||
@executeInEditMode
|
||||
// @disallowMultiple
|
||||
export class CanvasComponent extends Component {
|
||||
|
||||
@property({
|
||||
type: Size,
|
||||
})
|
||||
get designResolution () {
|
||||
return cc.size(this._designResolution);
|
||||
}
|
||||
set designResolution (value: Size) {
|
||||
this._designResolution.width = value.width;
|
||||
this._designResolution.height = value.height;
|
||||
this.applySettings();
|
||||
this.alignWithScreen();
|
||||
}
|
||||
|
||||
/**
|
||||
* !#en TODO
|
||||
* !#zh: 是否优先将设计分辨率高度撑满视图高度。
|
||||
* @property {Boolean} fitHeight
|
||||
* @default false
|
||||
*/
|
||||
@property()
|
||||
get fitHeight () {
|
||||
return this._fitHeight;
|
||||
}
|
||||
set fitHeight (value: boolean) {
|
||||
if (this._fitHeight !== value) {
|
||||
this._fitHeight = value;
|
||||
this.applySettings();
|
||||
this.alignWithScreen();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* !#en TODO
|
||||
* !#zh: 是否优先将设计分辨率宽度撑满视图宽度。
|
||||
* @property {Boolean} fitWidth
|
||||
* @default false
|
||||
*/
|
||||
@property()
|
||||
get fitWidth () {
|
||||
return this._fitWidth;
|
||||
}
|
||||
set fitWidth (value: boolean) {
|
||||
if (this._fitWidth !== value) {
|
||||
this._fitWidth = value;
|
||||
this.applySettings();
|
||||
this.alignWithScreen();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* !#en priority in render
|
||||
* !#zh 显示优先级
|
||||
*/
|
||||
@property
|
||||
get priority () {
|
||||
return this._priority;
|
||||
}
|
||||
|
||||
set priority (value: number) {
|
||||
this._priority = value;
|
||||
}
|
||||
|
||||
get visibility () {
|
||||
if (this._camere) {
|
||||
return this._camere.view.visibility;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
get camera () {
|
||||
return this._camere;
|
||||
}
|
||||
|
||||
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: Function | null = null;
|
||||
|
||||
private _camere: Camera | null = null;
|
||||
private _cameraInfo: object | 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);
|
||||
}
|
||||
|
||||
// public onLoad () {}
|
||||
|
||||
public resetInEditor () {
|
||||
// _Scene._applyCanvasPreferences(this);
|
||||
}
|
||||
|
||||
public __preload () {
|
||||
// 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.engine.on('design-resolution-changed', this._thisOnResized);
|
||||
// }
|
||||
// else {
|
||||
// TODO: Need to do editor initiative call
|
||||
if (!CC_EDITOR) {
|
||||
// if (cc.sys.isMobile) {
|
||||
// window.addEventListener('resize', this._thisOnResized);
|
||||
// }
|
||||
// else {
|
||||
// cc.view.on('canvas-resize', this._thisOnResized);
|
||||
// }
|
||||
cc.view.on('design-resolution-changed', this._thisOnResized);
|
||||
}
|
||||
|
||||
this.applySettings();
|
||||
this.alignWithScreen();
|
||||
}
|
||||
|
||||
public onEnable () {
|
||||
this._cameraInfo = {
|
||||
name: 'ui',
|
||||
clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL,
|
||||
node: this.node,
|
||||
stencil: 0,
|
||||
projection: CameraComponent.ProjectionType.ORTHO,
|
||||
orthoHeight: 10,
|
||||
far: 4096,
|
||||
near: 0.1,
|
||||
rect: new Rect(0, 0, 1, 1),
|
||||
color: cc.color(255, 255, 255, 255),
|
||||
};
|
||||
this._camere = this._getRenderScene().createCamera(this._cameraInfo);
|
||||
cc.director.root.ui.addScreen(this);
|
||||
}
|
||||
|
||||
public onDisable () {
|
||||
if (this._camere) {
|
||||
this._getRenderScene().destroyCamera(this._cameraInfo);
|
||||
cc.director.root.ui.removeScreen(this);
|
||||
}
|
||||
}
|
||||
|
||||
public onDestroy () {
|
||||
if (super.onDestroy) {
|
||||
super.onDestroy();
|
||||
}
|
||||
// if (CC_EDITOR) {
|
||||
// cc.engine.off('design-resolution-changed', this._thisOnResized);
|
||||
// }
|
||||
// else {
|
||||
// if (cc.sys.isMobile) {
|
||||
// window.removeEventListener('resize', this._thisOnResized);
|
||||
// }
|
||||
// else {
|
||||
// cc.view.off('canvas-resize', this._thisOnResized);
|
||||
// }
|
||||
// }
|
||||
|
||||
cc.view.off('design-resolution-changed', this._thisOnResized);
|
||||
|
||||
// cc.director._uiSystem.removeScreen(this);
|
||||
|
||||
// if (CanvasComponent.instance === this) {
|
||||
// CanvasComponent.instance = null;
|
||||
// }
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public alignWithScreen () {
|
||||
if (this._camere) {
|
||||
this._camere.resize(cc.game.canvas.width, cc.game.canvas.height);
|
||||
this._camere.orthoHeight = cc.game.canvas.height / cc.view._scaleY / 2;
|
||||
const viewport = this._camere.viewport;
|
||||
viewport.x = viewport.y = 0;
|
||||
viewport.width = cc.game.canvas.width;
|
||||
viewport.height = cc.game.canvas.height;
|
||||
}
|
||||
// if (CC_EDITOR) {
|
||||
// nodeSize = designSize = cc.engine.getDesignResolutionSize();
|
||||
// this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1);
|
||||
// }
|
||||
// else {
|
||||
const canvasSize = cc.visibleRect;
|
||||
const 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;
|
||||
offsetY = (designSize.height - canvasSize.height) * 0.5;
|
||||
}
|
||||
this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1);
|
||||
// }
|
||||
// let canvasSize = nodeSize = cc.visibleRect;
|
||||
// this.node.setPosition(canvasSize.width / 2, canvasSize.height / 2, 1);
|
||||
this.node.width = nodeSize.width;
|
||||
this.node.height = nodeSize.height;
|
||||
}
|
||||
|
||||
public applySettings () {
|
||||
const ResolutionPolicy = cc.ResolutionPolicy;
|
||||
let policy;
|
||||
|
||||
if (this.fitHeight && this.fitWidth) {
|
||||
policy = ResolutionPolicy.SHOW_ALL;
|
||||
} else if (!this.fitHeight && !this.fitWidth) {
|
||||
policy = ResolutionPolicy.NO_BORDER;
|
||||
} else if (this.fitWidth) {
|
||||
policy = ResolutionPolicy.FIXED_WIDTH;
|
||||
} else { // fitHeight
|
||||
policy = ResolutionPolicy.FIXED_HEIGHT;
|
||||
}
|
||||
|
||||
const designRes = this._designResolution;
|
||||
// if (CC_EDITOR) {
|
||||
// cc.engine.setDesignResolutionSize(designRes.width, designRes.height);
|
||||
// }
|
||||
// else {
|
||||
cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy);
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,861 @@
|
||||
/****************************************************************************
|
||||
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, menu, executionOrder, executeInEditMode, property } from '../../../../core/data/class-decorator';
|
||||
import Component from '../../../../components/component';
|
||||
import Color from '../../../../core/value-types/color';
|
||||
import macro from '../../../../core/platform/CCMacro';
|
||||
import EditBoxImpl from './edit-box-impl';
|
||||
import LabelComponent from '../label-component';
|
||||
// import { InputMode, InputFlag, KeyboardReturnType } from './types';
|
||||
import * as Types from './types';
|
||||
import SpriteFrame from '../../../../assets/CCSpriteFrame';
|
||||
import ComponentEventHandler from '../../../../components/CCComponentEventHandler';
|
||||
import SpriteComponent from '../sprite-component';
|
||||
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
|
||||
*/
|
||||
|
||||
@ccclass('cc.EditBoxComponent')
|
||||
@executionOrder(100)
|
||||
@menu('UI/EditBox')
|
||||
@executeInEditMode
|
||||
export default class EditBoxComponent extends Component {
|
||||
@property
|
||||
_useOriginalSize: boolean = true;
|
||||
@property
|
||||
_string: string = '';
|
||||
@property
|
||||
_tabIndex: number = 0;
|
||||
@property
|
||||
_backgroundImage: SpriteFrame | null = null;
|
||||
@property
|
||||
_returnType: number = KeyboardReturnType.DEFAULT;
|
||||
@property
|
||||
_inputFlag: number = InputFlag.DEFAULT;
|
||||
@property
|
||||
_inputMode: number = InputMode.SINGLE_LINE;
|
||||
@property
|
||||
_fontSize: number = 20;
|
||||
@property
|
||||
_lineHeight: number = 40;
|
||||
@property
|
||||
_maxLength: number = 20;
|
||||
@property
|
||||
_fontColor: Color = Color.WHITE;
|
||||
@property
|
||||
_placeholder: string = 'Enter text here...';
|
||||
@property
|
||||
_placeholderFontSize: number = 20;
|
||||
@property
|
||||
_placeholderFontColor: Color = Color.GRAY;
|
||||
@property
|
||||
_stayOnTop: boolean = false;
|
||||
@property
|
||||
editingDidBegan: ComponentEventHandler[] = [];
|
||||
@property
|
||||
editingDidEnded: ComponentEventHandler[] = [];
|
||||
@property
|
||||
editingReturn: ComponentEventHandler[] = [];
|
||||
@property
|
||||
textChanged: ComponentEventHandler[] = [];
|
||||
|
||||
_impl: EditBoxImpl | null = null;
|
||||
_textLabel: LabelComponent | null = null;
|
||||
_placeholderLabel: LabelComponent | null = null;
|
||||
_background: SpriteComponent | null = null;
|
||||
|
||||
/**
|
||||
* !#en Input string of EditBox.
|
||||
* !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。
|
||||
* @property {String} string
|
||||
*/
|
||||
@property
|
||||
get string() {
|
||||
return this._string;
|
||||
}
|
||||
|
||||
set string(value: string) {
|
||||
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: number) {
|
||||
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: number) {
|
||||
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: number) {
|
||||
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: number) {
|
||||
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: number) {
|
||||
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;
|
||||
this._textLabel.node.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: string) {
|
||||
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: number) {
|
||||
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) {
|
||||
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
|
||||
*/
|
||||
@property
|
||||
get maxLength() {
|
||||
return this._maxLength;
|
||||
}
|
||||
set maxLength(value: number) {
|
||||
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: boolean) {
|
||||
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: number) {
|
||||
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
|
||||
*/
|
||||
// @property({
|
||||
// default: [],
|
||||
// type: [ComponentEventHandler]
|
||||
// })
|
||||
// get editingDidBegan() {
|
||||
// return this._editingDidBegan;
|
||||
// }
|
||||
|
||||
// set editingDidBegan(value: ComponentEventHandler[]) {
|
||||
// this._editingDidBegan = value;
|
||||
// }
|
||||
|
||||
/**
|
||||
* !#en The event handler to be called when EditBox text changes.
|
||||
* !#zh 编辑文本输入框时触发的事件回调。
|
||||
* @property {Component.EventHandler[]} textChanged
|
||||
*/
|
||||
// @property({
|
||||
// default: [],
|
||||
// type: [ComponentEventHandler]
|
||||
// })
|
||||
// get textChanged() {
|
||||
// return this._textChanged;
|
||||
// }
|
||||
|
||||
// set textChanged(value: ComponentEventHandler[]) {
|
||||
// this._textChanged = value;
|
||||
// }
|
||||
|
||||
/**
|
||||
* !#en The event handler to be called when EditBox edit ends.
|
||||
* !#zh 结束编辑文本输入框时触发的事件回调。
|
||||
* @property {Component.EventHandler[]} editingDidEnded
|
||||
*/
|
||||
// @property({
|
||||
// default: [],
|
||||
// type: [ComponentEventHandler]
|
||||
// })
|
||||
// get editingDidEnded() {
|
||||
// return this._editingDidEnded;
|
||||
// }
|
||||
|
||||
// set editingDidEnded(value: ComponentEventHandler[]) {
|
||||
// this._editingDidEnded = value;
|
||||
// }
|
||||
|
||||
/**
|
||||
* !#en The event handler to be called when return key is pressed. Windows is not supported.
|
||||
* !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台
|
||||
* @property {Component.EventHandler[]} editingReturn
|
||||
*/
|
||||
// @property({
|
||||
// default: [],
|
||||
// type: [ComponentEventHandler]
|
||||
// })
|
||||
// get editingReturn() {
|
||||
// return this._editingReturn;
|
||||
// }
|
||||
|
||||
// set editingReturn(value: ComponentEventHandler[]) {
|
||||
// this._editingReturn = value;
|
||||
// }
|
||||
|
||||
static _EditBoxImpl = EditBoxImpl;
|
||||
static KeyboardReturnType = KeyboardReturnType;
|
||||
static InputFlag = InputFlag;
|
||||
static InputMode = InputMode;
|
||||
|
||||
onEnable() {
|
||||
this._impl && this._impl.onEnable();
|
||||
}
|
||||
|
||||
onDisable() {
|
||||
this._impl && this._impl.onDisable();
|
||||
}
|
||||
|
||||
onDestroy() {
|
||||
this._impl.clear();
|
||||
}
|
||||
|
||||
_init() {
|
||||
this._createBackgroundSprite();
|
||||
this._createLabels();
|
||||
this.node.on(cc.NodeUI.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();
|
||||
}
|
||||
|
||||
__preload() {
|
||||
if (!CC_EDITOR) {
|
||||
this._registerEvent();
|
||||
}
|
||||
this._init();
|
||||
}
|
||||
|
||||
_registerEvent() {
|
||||
this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
|
||||
this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
|
||||
}
|
||||
|
||||
_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() {
|
||||
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.NodeUI('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;
|
||||
}
|
||||
|
||||
_createLabels() {
|
||||
if (!this._textLabel) {
|
||||
let node = this.node.getChildByName('TEXT_LABEL');
|
||||
if (!node) {
|
||||
node = new cc.NodeUI('TEXT_LABEL');
|
||||
}
|
||||
node.color = this._fontColor;
|
||||
node.parent = this.node;
|
||||
node.setAnchorPoint(0, 1);
|
||||
|
||||
let textLabel = node.getComponent(LabelComponent);
|
||||
if (!textLabel) {
|
||||
textLabel = node.addComponent(LabelComponent);
|
||||
}
|
||||
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.NodeUI('PLACEHOLDER_LABEL');
|
||||
}
|
||||
node.color = this._placeholderFontColor;
|
||||
node.parent = this.node;
|
||||
node.setAnchorPoint(0, 1);
|
||||
|
||||
let placeholderLabel = node.getComponent(LabelComponent);
|
||||
if (!placeholderLabel) {
|
||||
placeholderLabel = node.addComponent(LabelComponent);
|
||||
}
|
||||
placeholderLabel.overflow = LabelComponent.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();
|
||||
ComponentEventHandler.emitEvents(this.editingDidBegan, this);
|
||||
this.node.emit('editing-did-began', this);
|
||||
}
|
||||
|
||||
editBoxEditingDidEnded() {
|
||||
if (!this.stayOnTop) {
|
||||
this._showLabels();
|
||||
}
|
||||
ComponentEventHandler.emitEvents(this.editingDidEnded, this);
|
||||
this.node.emit('editing-did-ended', this);
|
||||
}
|
||||
|
||||
editBoxTextChanged(text) {
|
||||
text = this._updateLabelStringStyle(text, true);
|
||||
this.string = text;
|
||||
ComponentEventHandler.emitEvents(this.textChanged, text, this);
|
||||
this.node.emit('text-changed', this);
|
||||
}
|
||||
|
||||
editBoxEditingReturn() {
|
||||
ComponentEventHandler.emitEvents(this.editingReturn, this);
|
||||
this.node.emit('editing-return', 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* !#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
|
||||
*/
|
||||
+284
-268
@@ -26,9 +26,15 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
const utils = require('../../platform/utils');
|
||||
const macro = require('../../platform/CCMacro');
|
||||
const Types = require('./types');
|
||||
import { ccclass } from '../../../../core/data/class-decorator';
|
||||
import { contains } from '../../../../core/utils/misc';
|
||||
import macro from '../../../../core/platform/CCMacro';
|
||||
// import { InputMode, InputFlag, KeyboardReturnType } from './types';
|
||||
import * as Types from './types';
|
||||
import * as math from '../../../../core/vmath';
|
||||
import { Size, Color } from '../../../../core/value-types';
|
||||
import { Node } from '../../../../scene-graph';
|
||||
import EditBoxComponent from './edit-box-component';
|
||||
const InputMode = Types.InputMode;
|
||||
const InputFlag = Types.InputFlag;
|
||||
const KeyboardReturnType = Types.KeyboardReturnType;
|
||||
@@ -40,9 +46,8 @@ 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 _matrix = cc.mat4();
|
||||
let _matrix_temp = cc.mat4();
|
||||
let _vec3 = cc.v3();
|
||||
|
||||
let _currentEditBoxImpl = null;
|
||||
@@ -54,11 +59,11 @@ let polyfill = {
|
||||
|
||||
if (cc.sys.OS_ANDROID === cc.sys.os &&
|
||||
(cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU ||
|
||||
cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
|
||||
cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
|
||||
polyfill.zoomInvalid = true;
|
||||
}
|
||||
|
||||
function getKeyboardReturnType (type) {
|
||||
function getKeyboardReturnType(type) {
|
||||
switch (type) {
|
||||
case KeyboardReturnType.DEFAULT:
|
||||
case KeyboardReturnType.DONE:
|
||||
@@ -75,55 +80,55 @@ function getKeyboardReturnType (type) {
|
||||
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;
|
||||
},
|
||||
@ccclass
|
||||
export default class EditBoxImpl {
|
||||
_delegate: EditBoxComponent | null = null;
|
||||
_inputMode: number = -1;
|
||||
_inputFlag: number = -1;
|
||||
_returnType: number = KeyboardReturnType.DEFAULT;
|
||||
_maxLength: number = 50;
|
||||
_text: string = '';
|
||||
_placeholderText: string = '';
|
||||
_alwaysOnTop: boolean = false;
|
||||
_size: Size = cc.size();
|
||||
_node: Node = null;
|
||||
_editing: boolean = false;
|
||||
__eventListeners: object = {};
|
||||
__fullscreen: boolean = false;
|
||||
__autoResize: boolean = false;
|
||||
__rotateScreen: boolean = false;
|
||||
__orientationChanged: Function | null = null;
|
||||
_edTxt: HTMLElement | null = null;
|
||||
_textColor: Color = Color.WHITE;
|
||||
|
||||
onEnable () {
|
||||
onEnable() {
|
||||
if (!this._edTxt) {
|
||||
return;
|
||||
}
|
||||
if (this._alwaysOnTop) {
|
||||
this._edTxt.style.display = '';
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._edTxt.style.display = 'none';
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
onDisable () {
|
||||
onDisable() {
|
||||
if (!this._edTxt) {
|
||||
return;
|
||||
}
|
||||
this._edTxt.style.display = 'none';
|
||||
},
|
||||
}
|
||||
|
||||
setTabIndex (index) {
|
||||
setTabIndex(index) {
|
||||
if (this._edTxt) {
|
||||
this._edTxt.tabIndex = index;
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
setFocus () {
|
||||
setFocus() {
|
||||
this._beginEditing();
|
||||
},
|
||||
}
|
||||
|
||||
isFocused() {
|
||||
if (this._edTxt) {
|
||||
@@ -131,23 +136,23 @@ let EditBoxImpl = cc.Class({
|
||||
}
|
||||
cc.warnID(4700);
|
||||
return false;
|
||||
},
|
||||
}
|
||||
|
||||
stayOnTop (flag) {
|
||||
if(this._alwaysOnTop === flag || !this._edTxt) return;
|
||||
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) {
|
||||
setMaxLength(maxLength) {
|
||||
if (!isNaN(maxLength)) {
|
||||
if(maxLength < 0) {
|
||||
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;
|
||||
@@ -155,40 +160,40 @@ let EditBoxImpl = cc.Class({
|
||||
this._maxLength = maxLength;
|
||||
this._edTxt && (this._edTxt.maxLength = maxLength);
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
setString (text) {
|
||||
setString(text) {
|
||||
this._text = text;
|
||||
this._edTxt && (this._edTxt.value = text);
|
||||
},
|
||||
}
|
||||
|
||||
getString () {
|
||||
getString() {
|
||||
return this._text;
|
||||
},
|
||||
}
|
||||
|
||||
setPlaceholderText (text) {
|
||||
setPlaceholderText(text) {
|
||||
this._placeholderText = text;
|
||||
},
|
||||
}
|
||||
|
||||
getPlaceholderText () {
|
||||
getPlaceholderText() {
|
||||
return this._placeholderText;
|
||||
},
|
||||
}
|
||||
|
||||
setDelegate (delegate) {
|
||||
setDelegate(delegate) {
|
||||
this._delegate = delegate;
|
||||
},
|
||||
}
|
||||
|
||||
setInputMode (inputMode) {
|
||||
setInputMode(inputMode) {
|
||||
if (this._inputMode === inputMode) return;
|
||||
|
||||
this._inputMode = inputMode;
|
||||
this.createInput();
|
||||
|
||||
|
||||
this._updateDomInputType();
|
||||
this._updateSize(this._size.width, this._size.height);
|
||||
},
|
||||
}
|
||||
|
||||
setInputFlag (inputFlag) {
|
||||
setInputFlag(inputFlag) {
|
||||
if (this._inputFlag === inputFlag) return;
|
||||
|
||||
this._inputFlag = inputFlag;
|
||||
@@ -207,55 +212,55 @@ let EditBoxImpl = cc.Class({
|
||||
this._edTxt.style.textTransform = textTransform;
|
||||
this._edTxt.value = this._text;
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
setReturnType (returnType) {
|
||||
setReturnType(returnType) {
|
||||
this._returnType = returnType;
|
||||
this._updateDomInputType();
|
||||
},
|
||||
}
|
||||
|
||||
setFontSize (fontSize) {
|
||||
setFontSize(fontSize) {
|
||||
this._edFontSize = fontSize || this._edFontSize;
|
||||
this._edTxt && (this._edTxt.style.fontSize = this._edFontSize + 'px');
|
||||
},
|
||||
|
||||
setFontColor (color) {
|
||||
}
|
||||
|
||||
setFontColor(color) {
|
||||
this._textColor = color;
|
||||
this._edTxt && (this._edTxt.style.color = color.toCSS('rgba'));
|
||||
},
|
||||
|
||||
setSize (width, height) {
|
||||
}
|
||||
|
||||
setSize(width, height) {
|
||||
this._size.width = width;
|
||||
this._size.height = height;
|
||||
this._updateSize(width, height);
|
||||
},
|
||||
}
|
||||
|
||||
setNode (node) {
|
||||
setNode(node) {
|
||||
this._node = node;
|
||||
},
|
||||
}
|
||||
|
||||
update () {
|
||||
update() {
|
||||
// TODO: find better way to update matrix
|
||||
// if (this._editing) {
|
||||
this._updateMatrix();
|
||||
this._updateMatrix();
|
||||
// }
|
||||
},
|
||||
}
|
||||
|
||||
clear () {
|
||||
clear() {
|
||||
this._node = null;
|
||||
this.setDelegate(null);
|
||||
this.removeDom();
|
||||
},
|
||||
}
|
||||
|
||||
_onTouchBegan (touch) {
|
||||
|
||||
},
|
||||
_onTouchBegan(touch) {
|
||||
|
||||
_onTouchEnded () {
|
||||
}
|
||||
|
||||
_onTouchEnded() {
|
||||
this._beginEditing();
|
||||
},
|
||||
}
|
||||
|
||||
_beginEditing () {
|
||||
_beginEditing() {
|
||||
if (cc.sys.isMobile && !this._editing) {
|
||||
// Pre adaptation
|
||||
this._beginEditingOnMobile();
|
||||
@@ -265,7 +270,7 @@ let EditBoxImpl = cc.Class({
|
||||
this._edTxt.style.display = '';
|
||||
|
||||
let self = this;
|
||||
function startFocus () {
|
||||
function startFocus() {
|
||||
self._edTxt.focus();
|
||||
}
|
||||
|
||||
@@ -279,11 +284,11 @@ let EditBoxImpl = cc.Class({
|
||||
startFocus();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this._editing = true;
|
||||
},
|
||||
|
||||
_endEditing () {
|
||||
}
|
||||
|
||||
_endEditing() {
|
||||
let self = this;
|
||||
let hideDomInputAndShowLabel = function () {
|
||||
if (!self._alwaysOnTop && self._edTxt) {
|
||||
@@ -306,100 +311,115 @@ let EditBoxImpl = cc.Class({
|
||||
}
|
||||
}
|
||||
this._editing = false;
|
||||
},
|
||||
|
||||
_updateDomInputType () {
|
||||
}
|
||||
|
||||
_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) {
|
||||
} else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) {
|
||||
type = 'number';
|
||||
} else if(inputMode === InputMode.PHONE_NUMBER) {
|
||||
} else if (inputMode === InputMode.PHONE_NUMBER) {
|
||||
type = 'number';
|
||||
edTxt.pattern = '[0-9]*';
|
||||
} else if(inputMode === InputMode.URL) {
|
||||
} else if (inputMode === InputMode.URL) {
|
||||
type = 'url';
|
||||
} else {
|
||||
type = 'text';
|
||||
|
||||
|
||||
if (this._returnType === KeyboardReturnType.SEARCH) {
|
||||
type = 'search';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
edTxt.type = type;
|
||||
},
|
||||
|
||||
_updateSize (newWidth, newHeight) {
|
||||
}
|
||||
|
||||
_updateSize(newWidth, newHeight) {
|
||||
let edTxt = this._edTxt;
|
||||
if (!edTxt) return;
|
||||
|
||||
|
||||
edTxt.style.width = newWidth + 'px';
|
||||
edTxt.style.height = newHeight + 'px';
|
||||
},
|
||||
}
|
||||
|
||||
_updateMatrix () {
|
||||
_updateMatrix() {
|
||||
if (!this._edTxt) return;
|
||||
|
||||
let node = this._node,
|
||||
|
||||
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;
|
||||
// if (CC_EDITOR) {
|
||||
// camera = cc.Camera.main;
|
||||
// }
|
||||
// else {
|
||||
// camera = cc.Camera.findCamera(node);
|
||||
// }
|
||||
let renderComp = node.getComponent(cc.RenderComponent);
|
||||
if (!renderComp) {
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
camera = cc.Camera.findCamera(node);
|
||||
let canvas = cc.CanvasComponent.findView(renderComp);
|
||||
if (!canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
camera.getWorldToCameraMatrix(_matrix_temp);
|
||||
|
||||
// camera.getWorldToCameraMatrix(_matrix_temp);
|
||||
canvas.node.getWorldRT(_matrix_temp);
|
||||
let m12 = _matrix_temp.m12;
|
||||
let m13 = _matrix_temp.m13;
|
||||
let 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;
|
||||
|
||||
|
||||
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 () {
|
||||
_adjustEditBoxPosition() {
|
||||
this._node.getWorldMatrix(_matrix);
|
||||
let y = _matrix.m13;
|
||||
let windowHeight = cc.visibleRect.height;
|
||||
@@ -408,7 +428,7 @@ let EditBoxImpl = cc.Class({
|
||||
if (windowWidth > windowHeight) {
|
||||
factor = 0.7;
|
||||
}
|
||||
setTimeout(function() {
|
||||
setTimeout(function () {
|
||||
if (window.scrollY < SCROLLY && y < windowHeight * factor) {
|
||||
let scrollOffset = windowHeight * factor - y - window.scrollY;
|
||||
if (scrollOffset < 35) scrollOffset = 35;
|
||||
@@ -417,70 +437,155 @@ let EditBoxImpl = cc.Class({
|
||||
}
|
||||
}, 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);
|
||||
createInput() {
|
||||
if (this._inputMode === InputMode.ANY) {
|
||||
this._createDomTextArea();
|
||||
}
|
||||
else {
|
||||
this._createDomInput();
|
||||
}
|
||||
this.__rotateScreen = false;
|
||||
}
|
||||
|
||||
window.removeEventListener('orientationchange', this.__orientationChanged);
|
||||
// Called before editbox focus to register cc.view status
|
||||
_beginEditingOnMobile() {
|
||||
let self = this;
|
||||
this.__orientationChanged = function () {
|
||||
self._adjustEditBoxPosition();
|
||||
};
|
||||
window.addEventListener('orientationchange', this.__orientationChanged);
|
||||
|
||||
if(this.__fullscreen) {
|
||||
cc.view.enableAutoFullScreen(true);
|
||||
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;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
};
|
||||
// Called after keyboard disappeared to readapte the game view
|
||||
_endEditingOnMobile() {
|
||||
if (this.__rotateScreen) {
|
||||
cc.game.container.style['-webkit-transform'] = 'rotate(90deg)';
|
||||
cc.game.container.style.transform = 'rotate(90deg)';
|
||||
|
||||
function _inputValueHandle (input, editBoxImpl) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
_createDomInput() {
|
||||
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;
|
||||
}
|
||||
|
||||
_createDomTextArea() {
|
||||
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;
|
||||
}
|
||||
|
||||
_addDomToGameContainer() {
|
||||
cc.game.container.appendChild(this._edTxt);
|
||||
}
|
||||
|
||||
removeDom() {
|
||||
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 = 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);
|
||||
}
|
||||
@@ -492,7 +597,7 @@ function _inputValueHandle (input, editBoxImpl) {
|
||||
}
|
||||
}
|
||||
|
||||
function registerInputEventListener (tmpEdTxt, editBoxImpl, isTextarea) {
|
||||
function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea: boolean = false) {
|
||||
let inputLock = false;
|
||||
let cbs = editBoxImpl.__eventListeners;
|
||||
cbs.compositionstart = function () {
|
||||
@@ -557,92 +662,3 @@ function registerInputEventListener (tmpEdTxt, editBoxImpl, isTextarea) {
|
||||
|
||||
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;
|
||||
@@ -180,8 +180,4 @@ let InputFlag = cc.Enum({
|
||||
DEFAULT: 5
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
KeyboardReturnType: KeyboardReturnType,
|
||||
InputMode: InputMode,
|
||||
InputFlag: InputFlag
|
||||
};
|
||||
export { KeyboardReturnType, InputMode, InputFlag }
|
||||
@@ -0,0 +1,703 @@
|
||||
/****************************************************************************
|
||||
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 macro from '../../../core/platform/CCMacro';
|
||||
import { RenderComponent } from './ui-render-component';
|
||||
import ImageAsset from '../../../assets/image-asset';
|
||||
// import { vec2, vec3, mat4, color4 } from '../../../core/vmath/index';
|
||||
import {
|
||||
ccclass,
|
||||
property,
|
||||
menu,
|
||||
executionOrder,
|
||||
executeInEditMode,
|
||||
} from '../../../core/data/class-decorator';
|
||||
import Font from '../../../assets/CCFont';
|
||||
import Texture2D from '../../../assets/texture-2d';
|
||||
import { MeshBuffer } from '../mesh-buffer';
|
||||
import { Enum } from '../../../core/value-types';
|
||||
// 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 RenderComponent
|
||||
*/
|
||||
@ccclass('cc.LabelComponent')
|
||||
@executionOrder(100)
|
||||
@menu('UI/Label')
|
||||
@executeInEditMode
|
||||
export class LabelComponent extends RenderComponent {
|
||||
|
||||
/**
|
||||
* !#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;
|
||||
private _assembler: 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 updateRenderData (buffer: MeshBuffer) {
|
||||
if (!this._assembler) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._assembler.updateRenderData(this);
|
||||
this._assembler.fillBuffers(this, buffer);
|
||||
}
|
||||
|
||||
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['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('mainTexture', 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
/****************************************************************************
|
||||
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 { Node } from '../../../scene-graph/node';
|
||||
import { RenderComponent } from './ui-render-component';
|
||||
import { UITransformComponent } from './ui-transfrom-component';
|
||||
const renderEngine = require('../../../2d/renderer/render-engine');
|
||||
const math = renderEngine.math;
|
||||
const StencilMaterial = renderEngine.StencilMaterial;
|
||||
// const RenderFlow = require('../../../2d/renderer/render-flow');
|
||||
const Graphics = require('../../../2d/graphics/graphics');
|
||||
|
||||
const _vec2_temp = cc.v2();
|
||||
const _mat4_temp = math.mat4.create();
|
||||
|
||||
/**
|
||||
* !#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 RenderComponent {
|
||||
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) {
|
||||
const 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 in Canvas Mode) <br/>
|
||||
* The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold. <br/>
|
||||
* Should be a float between 0 and 1. <br/>
|
||||
* 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 模式)<br/>
|
||||
* 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。<br/>
|
||||
* 该数值 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;
|
||||
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 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);
|
||||
}
|
||||
|
||||
// _resizeToTarget: {
|
||||
// animatable: false,
|
||||
// set (value) {
|
||||
// if (value) {
|
||||
// this._resizeNodeToTargetNode();
|
||||
// }
|
||||
// },
|
||||
// },
|
||||
|
||||
@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 _graphics: Graphics | null = null;
|
||||
|
||||
private _material: StencilMaterial | null = null;
|
||||
|
||||
public onLoad () {
|
||||
this._graphics = new Graphics();
|
||||
this._graphics.node = this.node;
|
||||
this._graphics.lineWidth = 0;
|
||||
this._graphics.strokeColor = cc.color(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
public 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();
|
||||
}
|
||||
}
|
||||
|
||||
public onEnable () {
|
||||
super.onEnable();
|
||||
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(Node.EventType.POSITION_CHANGED, this._updateGraphics, this);
|
||||
this.node.on(Node.EventType.ROTATION_CHANGED, this._updateGraphics, this);
|
||||
this.node.on(Node.EventType.SCALE_CHANGED, this._updateGraphics, this);
|
||||
this.node.on(Node.EventType.SIZE_CHANGED, this._updateGraphics, this);
|
||||
this.node.on(Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this);
|
||||
|
||||
// this.node._renderFlag |= RenderFlow.FLAG_POST_RENDER;
|
||||
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();
|
||||
this._graphics.destroy();
|
||||
}
|
||||
|
||||
// _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;
|
||||
this.markForUpdateRenderData(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 () {
|
||||
// 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) {
|
||||
const texture = this._spriteFrame;
|
||||
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);
|
||||
}
|
||||
|
||||
public _updateGraphics () {
|
||||
const node = this.node;
|
||||
const graphics = this._graphics;
|
||||
// Share render data with graphics content
|
||||
graphics.clear(false);
|
||||
const width = node._contentSize.width;
|
||||
const height = node._contentSize.height;
|
||||
const x = -width * node._anchorPoint.x;
|
||||
const y = -height * node._anchorPoint.y;
|
||||
if (this._type === MaskType.RECT) {
|
||||
graphics.rect(x, y, width, height);
|
||||
} else if (this._type === MaskType.ELLIPSE) {
|
||||
const cx = x + width / 2;
|
||||
const cy = y + height / 2;
|
||||
const rx = width / 2;
|
||||
const ry = height / 2;
|
||||
graphics.ellipse(cx, cy, rx, ry);
|
||||
}
|
||||
if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
|
||||
graphics.stroke();
|
||||
} else {
|
||||
graphics.fill();
|
||||
}
|
||||
}
|
||||
|
||||
public _hitTest (cameraPt) {
|
||||
const node = this.node;
|
||||
const size = node.getContentSize();
|
||||
const w = size.width;
|
||||
const h = size.height;
|
||||
const 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) {
|
||||
const rx = w / 2;
|
||||
const ry = h / 2;
|
||||
const px = testPt.x - 0.5 * w;
|
||||
const py = testPt.y - 0.5 * h;
|
||||
return px * px / (rx * rx) + py * py / (ry * ry) < 1;
|
||||
}
|
||||
}
|
||||
|
||||
public 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;
|
||||
// }
|
||||
}
|
||||
|
||||
public 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);
|
||||
// }
|
||||
}
|
||||
|
||||
public disableRender () {
|
||||
// this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA |
|
||||
// RenderFlow.FLAG_POST_RENDER);
|
||||
}
|
||||
}
|
||||
|
||||
// tslint:disable-next-line
|
||||
cc['MaskComponent'] = MaskComponent;
|
||||
@@ -24,8 +24,11 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
const misc = require('../utils/misc');
|
||||
const Component = require('./CCComponent');
|
||||
import { Component} from '../../../components/component';
|
||||
import { clamp01 } from '../../../core/utils/misc';
|
||||
import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator';
|
||||
import SpriteComponent from './sprite-component';
|
||||
|
||||
|
||||
/**
|
||||
* !#en Enum for ProgressBar mode
|
||||
@@ -64,7 +67,7 @@ var Mode = cc.Enum({
|
||||
* @extends Component
|
||||
* @example
|
||||
* // update progressBar
|
||||
* update: function (dt) {
|
||||
* update(dt) {
|
||||
* var progress = progressBar.progress;
|
||||
* if (progress > 0) {
|
||||
* progress += dt;
|
||||
@@ -76,18 +79,139 @@ var Mode = cc.Enum({
|
||||
* }
|
||||
*
|
||||
*/
|
||||
var ProgressBar = cc.Class({
|
||||
name: 'cc.ProgressBar',
|
||||
extends: Component,
|
||||
@ccclass('cc.ProgressBarComponent')
|
||||
@executionOrder(100)
|
||||
@menu('UI/ProgressBar')
|
||||
// @executeInEditMode
|
||||
export default class ProgressBarComponent extends Component {
|
||||
@property
|
||||
_barSprite: SpriteComponent | null = null;
|
||||
@property
|
||||
_mode: number = Mode.HORIZONTAL;
|
||||
_N$totalLength: number = 1;
|
||||
@property
|
||||
_progress: number = 0.1;
|
||||
@property
|
||||
_reverse: boolean = false;
|
||||
|
||||
editor: CC_EDITOR && {
|
||||
menu: 'i18n:MAIN_MENU.component.ui/ProgressBar',
|
||||
help: 'i18n:COMPONENT.help_url.progressbar',
|
||||
},
|
||||
/**
|
||||
* !#en The targeted Sprite which will be changed progressively.
|
||||
* !#zh 用来显示进度条比例的 Sprite 对象。
|
||||
* @property {Sprite} barSprite
|
||||
*/
|
||||
@property({
|
||||
type: SpriteComponent
|
||||
})
|
||||
get barSprite() {
|
||||
return this._barSprite;
|
||||
}
|
||||
|
||||
_initBarSprite: function() {
|
||||
if (this.barSprite) {
|
||||
var entity = this.barSprite.node;
|
||||
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: number) {
|
||||
if (this._mode === value) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._mode = value;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* !#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
|
||||
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();
|
||||
}
|
||||
|
||||
static Mode = Mode;
|
||||
|
||||
_initBarSprite() {
|
||||
if (this._barSprite) {
|
||||
var entity = this._barSprite.node;
|
||||
if (!entity) return;
|
||||
|
||||
var nodeSize = this.node.getContentSize();
|
||||
@@ -95,36 +219,36 @@ var ProgressBar = cc.Class({
|
||||
|
||||
var entitySize = entity.getContentSize();
|
||||
|
||||
if(entity.parent === this.node){
|
||||
if (entity.parent === this.node) {
|
||||
this.node.setContentSize(entitySize);
|
||||
}
|
||||
|
||||
if (this.barSprite.fillType === cc.Sprite.FillType.RADIAL) {
|
||||
this.mode = Mode.FILLED;
|
||||
if (this._barSprite.fillType === cc.SpriteComponent.FillType.RADIAL) {
|
||||
this._mode = Mode.FILLED;
|
||||
}
|
||||
|
||||
var barSpriteSize = entity.getContentSize();
|
||||
if (this.mode === Mode.HORIZONTAL) {
|
||||
if (this._mode === Mode.HORIZONTAL) {
|
||||
this.totalLength = barSpriteSize.width;
|
||||
}
|
||||
else if(this.mode === Mode.VERTICAL) {
|
||||
else if (this._mode === Mode.VERTICAL) {
|
||||
this.totalLength = barSpriteSize.height;
|
||||
}
|
||||
else {
|
||||
this.totalLength = this.barSprite.fillRange;
|
||||
this.totalLength = this._barSprite.fillRange;
|
||||
}
|
||||
|
||||
if(entity.parent === this.node){
|
||||
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;
|
||||
_updateBarStatus() {
|
||||
if (this._barSprite) {
|
||||
var entity = this._barSprite.node;
|
||||
|
||||
if (!entity) return;
|
||||
|
||||
@@ -133,14 +257,14 @@ var ProgressBar = cc.Class({
|
||||
var entityPosition = entity.getPosition();
|
||||
|
||||
var anchorPoint = cc.v2(0, 0.5);
|
||||
var progress = misc.clamp01(this.progress);
|
||||
var progress = clamp01(this._progress);
|
||||
var actualLenth = this.totalLength * progress;
|
||||
var finalContentSize;
|
||||
var totalWidth;
|
||||
var totalHeight;
|
||||
switch (this.mode) {
|
||||
switch (this._mode) {
|
||||
case Mode.HORIZONTAL:
|
||||
if (this.reverse) {
|
||||
if (this._reverse) {
|
||||
anchorPoint = cc.v2(1, 0.5);
|
||||
}
|
||||
finalContentSize = cc.size(actualLenth, entitySize.height);
|
||||
@@ -148,7 +272,7 @@ var ProgressBar = cc.Class({
|
||||
totalHeight = entitySize.height;
|
||||
break;
|
||||
case Mode.VERTICAL:
|
||||
if (this.reverse) {
|
||||
if (this._reverse) {
|
||||
anchorPoint = cc.v2(0.5, 1);
|
||||
} else {
|
||||
anchorPoint = cc.v2(0.5, 0);
|
||||
@@ -160,17 +284,17 @@ var ProgressBar = cc.Class({
|
||||
}
|
||||
|
||||
//handling filled mode
|
||||
if (this.mode === Mode.FILLED) {
|
||||
if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
|
||||
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) {
|
||||
if (this._reverse) {
|
||||
actualLenth = actualLenth * -1;
|
||||
}
|
||||
this.barSprite.fillRange = actualLenth;
|
||||
this._barSprite.fillRange = actualLenth;
|
||||
}
|
||||
} else {
|
||||
if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
|
||||
if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) {
|
||||
|
||||
var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
|
||||
var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
|
||||
@@ -184,114 +308,7 @@ var ProgressBar = cc.Class({
|
||||
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;
|
||||
@@ -0,0 +1,270 @@
|
||||
/****************************************************************************
|
||||
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, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator';
|
||||
import SpriteComponent from './sprite-component';
|
||||
import { Vec2 } from '../../../core/value-types/index';
|
||||
import ComponentEventHandler from '../../../components/CCComponentEventHandler';
|
||||
import Event from '../../../core/event/event';
|
||||
import { EventTouch } from '../../../core/platform/event-manager/CCEvent';
|
||||
/**
|
||||
* !#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
|
||||
*/
|
||||
@ccclass('cc.SliderComponent')
|
||||
@executionOrder(100)
|
||||
@menu('UI/Slider')
|
||||
// @executeInEditMode
|
||||
export default class SliderComponent extends Component {
|
||||
@property
|
||||
_handle: SpriteComponent | null = null;
|
||||
@property
|
||||
_direction: number = Direction.Horizontal;
|
||||
@property
|
||||
_progress: number = 0.1;
|
||||
@property
|
||||
_slideEvents: ComponentEventHandler[] = [];
|
||||
|
||||
_offset: Vec2 = cc.v2();
|
||||
_dragging = false;
|
||||
_touchHandle = false;
|
||||
|
||||
/**
|
||||
* !#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
|
||||
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;
|
||||
}
|
||||
|
||||
static Direction = Direction;
|
||||
|
||||
__preload() {
|
||||
this._updateHandlePosition();
|
||||
}
|
||||
|
||||
// 注册事件
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
_onHandleDragStart(event: Event | null) {
|
||||
this._dragging = true;
|
||||
this._touchHandle = true;
|
||||
this._offset = this._handle.node.convertToNodeSpaceAR(event.touch.getLocation());
|
||||
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
_onTouchBegan(event: Event | null) {
|
||||
if (!this._handle) { return; }
|
||||
this._dragging = true;
|
||||
if (!this._touchHandle) {
|
||||
this._handleSliderLogic(event.touch);
|
||||
}
|
||||
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
_onTouchMoved(event: Event | null) {
|
||||
if (!this._dragging) { return; }
|
||||
this._handleSliderLogic(event.touch);
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
_onTouchEnded(event: Event | null) {
|
||||
this._dragging = false;
|
||||
this._touchHandle = false;
|
||||
this._offset = cc.v2();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
_onTouchCancelled(event: Event | null) {
|
||||
this._dragging = false;
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
_handleSliderLogic(touch) {
|
||||
this._updateProgress(touch);
|
||||
this._emitSlideEvent();
|
||||
}
|
||||
|
||||
_emitSlideEvent() {
|
||||
cc.Component.EventHandler.emitEvents(this.slideEvents, this);
|
||||
this.node.emit('slide', this);
|
||||
}
|
||||
|
||||
_updateProgress(touch: EventTouch | null) {
|
||||
if (!this._handle) { return; }
|
||||
var localTouchPos = this.node.convertToNodeSpaceAR(touch.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);
|
||||
}
|
||||
}
|
||||
|
||||
_updateHandlePosition() {
|
||||
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.setPosition(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.
|
||||
*/
|
||||
@@ -0,0 +1,617 @@
|
||||
/****************************************************************************
|
||||
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 { RenderComponent } from './ui-render-component';
|
||||
import { Node } from '../../../scene-graph/node';
|
||||
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 RenderComponent {
|
||||
|
||||
/**
|
||||
* !#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 _assembler = 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['default-spriteframe'];
|
||||
}
|
||||
|
||||
// this.node.on(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this);
|
||||
// this.node.on(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this);
|
||||
}
|
||||
|
||||
public updateRenderData (buffer: MeshBuffer) {
|
||||
if (!this._spriteFrame || !this.material) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._assembler.updateRenderData(this);
|
||||
this._assembler.fillBuffers(this, buffer);
|
||||
}
|
||||
|
||||
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) {
|
||||
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['sprite-material'];
|
||||
material = this.material;
|
||||
if (spriteFrame && spriteFrame.textureLoaded()) {
|
||||
material.setProperty('mainTexture', spriteFrame);
|
||||
this.markForUpdateRenderData(true);
|
||||
}
|
||||
} else {
|
||||
if (spriteFrame && spriteFrame.textureLoaded()) {
|
||||
const matTexture = material.effect && material.effect.getProperty('mainTexture');
|
||||
if (matTexture !== spriteFrame) {
|
||||
material.setProperty('mainTexture', 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, function (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;
|
||||
@@ -0,0 +1,294 @@
|
||||
/****************************************************************************
|
||||
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 * as js from '../../core/utils/js';
|
||||
import RenderComponent from './render-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 default 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.
|
||||
*/
|
||||
+37
-47
@@ -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 default 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;
|
||||
}
|
||||
@@ -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 default 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;
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
/****************************************************************************
|
||||
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 { CanvasComponent } from './canvas-component';
|
||||
import { UITransformComponent } from './ui-transfrom-component';
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Base class for components which supports rendering features.
|
||||
* !#zh
|
||||
* 所有支持渲染的组件的基类
|
||||
*
|
||||
* @class RenderComponent
|
||||
* @extends Component
|
||||
*/
|
||||
@ccclass('cc.RenderComponent')
|
||||
@executionOrder(100)
|
||||
@requireComponent(UITransformComponent)
|
||||
export class RenderComponent 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);
|
||||
}
|
||||
|
||||
get color () {
|
||||
return this._color;
|
||||
}
|
||||
|
||||
set color (value) {
|
||||
if (this._color === value) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._color = value;
|
||||
}
|
||||
|
||||
get viewID () {
|
||||
return this._viewID;
|
||||
}
|
||||
|
||||
public get renderData () {
|
||||
return this._renderData;
|
||||
}
|
||||
|
||||
public static assembler = null;
|
||||
protected _renderDataPoolID: number = -1;
|
||||
protected _viewID: number = -1;
|
||||
|
||||
protected _srcBlendFactor: number = macro.BlendFactor.SRC_ALPHA;
|
||||
protected _dstBlendFactor: number = macro.BlendFactor.ONE_MINUS_SRC_ALPHA;
|
||||
@property
|
||||
protected _color: Color = Color.WHITE;
|
||||
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._viewID = 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._viewID = -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();
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
// RenderComponent._assembler = null;
|
||||
// RenderComponent._postAssembler = null;
|
||||
@@ -0,0 +1,286 @@
|
||||
import { Component} from '../../../components/component';
|
||||
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
|
||||
import Event from '../../../core/platform/event-manager/CCEvent.js';
|
||||
import Size from '../../../core/value-types/size';
|
||||
import Vec2 from '../../../core/value-types/vec2';
|
||||
import * as math from '../../../core/vmath/index';
|
||||
import { Enum } from '../../../core/value-types';
|
||||
|
||||
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)
|
||||
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 onEnable () {
|
||||
this.node.uiTransfromComp = this;
|
||||
}
|
||||
|
||||
public onDisable () {
|
||||
this.node.uiTransfromComp = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Sets the untransformed size of the node.<br/>
|
||||
* The contentSize remains the same no matter the node is scaled or rotated.<br/>
|
||||
* 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, height: number) {
|
||||
const locContentSize = this._contentSize;
|
||||
// var clone;
|
||||
if (height === undefined) {
|
||||
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. <br/>
|
||||
* anchor point is the point around which all transformations and positioning manipulations take place. <br/>
|
||||
* It's like a pin in the node where it is "attached" to its parent. <br/>
|
||||
* The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.<br/>
|
||||
* But you can use values higher than (1,1) and lower than (0,0) too.<br/>
|
||||
* The default anchor point is (0.5,0.5), so it starts at the center of the node.
|
||||
* !#zh
|
||||
* 设置锚点的百分比。<br/>
|
||||
* 锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。<br/>
|
||||
* 锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。<br/>
|
||||
* 但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。<br/>
|
||||
* 默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。<br/>
|
||||
* 注意: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, y: number) {
|
||||
const locAnchorPoint = this._anchorPoint;
|
||||
if (y === undefined) {
|
||||
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) {
|
||||
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._hitTest(cameraPt) : true;
|
||||
} else {
|
||||
listener.mask = null;
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
/****************************************************************************
|
||||
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');
|
||||
import WidgetManager from '../../../2d/base-ui/CCWidgetManager';
|
||||
import { Component} from '../../../components/component';
|
||||
import { ccclass, property, executeInEditMode, menu, executionOrder } 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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
@ccclass('cc.WidgetComponent')
|
||||
@executionOrder(100)
|
||||
@menu('UI/Widget')
|
||||
@executeInEditMode
|
||||
export default class WidgetComponent extends Component {
|
||||
/**
|
||||
* !#zh: 对齐开关,由 AlignFlags 组成
|
||||
*
|
||||
* @property _alignFlags
|
||||
* @type {Number}
|
||||
* @default 0
|
||||
* @private
|
||||
*/
|
||||
_alignFlags: number = 0;
|
||||
_wasAlignOnce: boolean = false;
|
||||
@property
|
||||
_target: Node | null = null;
|
||||
@property
|
||||
_isAlignTop: boolean = false;
|
||||
@property
|
||||
_isAlignBottom: boolean = false;
|
||||
@property
|
||||
_isAlignLeft: boolean = false;
|
||||
@property
|
||||
_isAlignRight: boolean = false;
|
||||
@property
|
||||
_left: number = 0;
|
||||
@property
|
||||
_right: number = 0;
|
||||
@property
|
||||
_top: number = 0;
|
||||
@property
|
||||
_bottom: number = 0;
|
||||
@property
|
||||
_horizontalCenter: number = 0;
|
||||
@property
|
||||
_verticalCenter: number = 0;
|
||||
@property
|
||||
_isAbsLeft: boolean = true;
|
||||
@property
|
||||
_isAbsRight: boolean = true;
|
||||
@property
|
||||
_isAbsTop: boolean = true;
|
||||
@property
|
||||
_isAbsBottom: boolean = true;
|
||||
@property
|
||||
_isAbsHorizontalCenter: boolean = true;
|
||||
@property
|
||||
_isAbsVerticalCenter: boolean = true;
|
||||
// original size before align
|
||||
@property
|
||||
_originalWidth: number = 0;
|
||||
@property
|
||||
_originalHeight: number = 0;
|
||||
@property
|
||||
_alignMode: number = AlignMode.ON_WINDOW_RESIZE;
|
||||
|
||||
/**
|
||||
* !#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: cc.NodeUI
|
||||
})
|
||||
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._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;
|
||||
}
|
||||
|
||||
static AlignMode = AlignMode;
|
||||
|
||||
onLoad() {
|
||||
if (this._wasAlignOnce) {
|
||||
// migrate for old version
|
||||
this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS;
|
||||
this._wasAlignOnce = false;
|
||||
}
|
||||
}
|
||||
|
||||
onEnable() {
|
||||
WidgetManager.add(this);
|
||||
}
|
||||
|
||||
onDisable() {
|
||||
WidgetManager.remove(this);
|
||||
}
|
||||
|
||||
_setAlign(flag: number, isAlign: boolean) {
|
||||
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() {
|
||||
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;
|
||||
@@ -0,0 +1,30 @@
|
||||
|
||||
import { CanvasComponent} from './components/canvas-component';
|
||||
import {RenderComponent} from './components/ui-render-component';
|
||||
import { SpriteComponent} from './components/sprite-component';
|
||||
import { UITransformComponent } from './components/ui-transfrom-component';
|
||||
// import LabelComponent from './components/label-component';
|
||||
// import UIRectComponent fro./components/ui-transfrom-componentent';
|
||||
// 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';
|
||||
|
||||
cc.CanvasComponent = CanvasComponent;
|
||||
cc.RenderComponent = RenderComponent;
|
||||
cc.SpriteComponent = SpriteComponent;
|
||||
// cc.LabelComponent = LabelComponent;
|
||||
// cc.UIRectComponent = UIRectComponent;
|
||||
// cc.ButtonComponent = ButtonComponent;
|
||||
// cc.ToggleGroupComponent = ToggleGroupComponent;
|
||||
// cc.ToggleComponent = ToggleComponent;
|
||||
// cc.ToggleContainerComponent = ToggleContainerComponent;
|
||||
// cc.SliderComponent = SliderComponent;
|
||||
// cc.ProgressBarComponent = ProgressBarComponent;
|
||||
// cc.WidgetComponent = WidgetComponent;
|
||||
// cc.EditBoxComponent = EditBoxComponent;
|
||||
@@ -0,0 +1,228 @@
|
||||
// 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 } from '../../gfx/define';
|
||||
import { IGFXInputAttribute } from '../../gfx/input-assembler';
|
||||
// import UISystem from '../UISystem';
|
||||
|
||||
export interface IMeshBufferInitData {
|
||||
vertexCount: number;
|
||||
indexCount: 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;
|
||||
|
||||
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.indexCount;
|
||||
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) {
|
||||
oldVData = new Uint8Array(this.vData.buffer);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
@@ -25,19 +25,37 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
import { ccclass, property } from '../core/data/class-decorator';
|
||||
import EventTarget from '../core/event/event-target';
|
||||
import textureUtil from './texture-util';
|
||||
import {addon} from '../core/utils/js';
|
||||
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 {ccclass, property} from '../core/data/class-decorator';
|
||||
|
||||
import Texture2D from './texture-2d';
|
||||
import textureUtil from './texture-util';
|
||||
|
||||
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}];
|
||||
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,35 @@ export default class SpriteFrame extends Asset {
|
||||
}
|
||||
set insetRight (value) {
|
||||
this._capInsets[INSET_RIGHT] = value;
|
||||
if (this._texture) {
|
||||
this._calculateSlicedUV();
|
||||
}
|
||||
// if (this._texture) {
|
||||
this._calculateSlicedUV();
|
||||
// }
|
||||
}
|
||||
|
||||
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 +219,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] = 1;
|
||||
this._capInsets[INSET_TOP] = 1;
|
||||
|
||||
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 +307,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 +350,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 +360,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 +394,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.<br/>
|
||||
* !#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.<br/>
|
||||
// * !#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 +478,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 +561,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 +581,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 +615,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 +630,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 +645,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 +675,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 +689,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 +708,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,18 +728,35 @@ 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);
|
||||
|
||||
@@ -29,7 +29,7 @@ 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';
|
||||
|
||||
@@ -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.
|
||||
****************************************************************************/
|
||||
|
||||
import Camera from '../camera/CCCamera';
|
||||
import { Component } from './component';
|
||||
import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from '../core/data/class-decorator';
|
||||
|
||||
/**
|
||||
* !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。
|
||||
* 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。
|
||||
*
|
||||
* @class Canvas
|
||||
* @extends Component
|
||||
*/
|
||||
@ccclass('cc.Canvas')
|
||||
@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;
|
||||
|
||||
/**
|
||||
* !#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
|
||||
})
|
||||
get designResolution () {
|
||||
return cc.size(this._designResolution);
|
||||
}
|
||||
set designResolution (value) {
|
||||
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'
|
||||
})
|
||||
get fitHeight () {
|
||||
return this._fitHeight;
|
||||
}
|
||||
set fitHeight (value) {
|
||||
if (this._fitHeight !== value) {
|
||||
this._fitHeight = value;
|
||||
this.applySettings();
|
||||
this.alignWithScreen();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* !#en TODO
|
||||
* !#zh: 是否优先将设计分辨率宽度撑满视图宽度。
|
||||
* @property {Boolean} fitWidth
|
||||
* @default false
|
||||
*/
|
||||
@property({
|
||||
tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_width'
|
||||
})
|
||||
get fitWidth () {
|
||||
return this._fitWidth;
|
||||
}
|
||||
set fitWidth (value) {
|
||||
if (this._fitWidth !== value) {
|
||||
this._fitWidth = value;
|
||||
this.applySettings();
|
||||
this.alignWithScreen();
|
||||
}
|
||||
}
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
this._thisOnResized = this.alignWithScreen.bind(this);
|
||||
}
|
||||
|
||||
resetInEditor () {
|
||||
_Scene._applyCanvasPreferences(this);
|
||||
}
|
||||
|
||||
__preload () {
|
||||
if (CC_DEV) {
|
||||
var Flags = cc.Object.Flags;
|
||||
this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked);
|
||||
}
|
||||
|
||||
if (Canvas.instance) {
|
||||
return cc.errorID(6700,
|
||||
this.node.name, Canvas.instance.node.name);
|
||||
}
|
||||
Canvas.instance = this;
|
||||
|
||||
if (CC_EDITOR) {
|
||||
cc.engine.on('design-resolution-changed', this._thisOnResized);
|
||||
}
|
||||
else {
|
||||
if (cc.sys.isMobile) {
|
||||
window.addEventListener('resize', this._thisOnResized);
|
||||
}
|
||||
else {
|
||||
cc.view.on('canvas-resize', this._thisOnResized);
|
||||
}
|
||||
}
|
||||
|
||||
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 () {
|
||||
if (CC_EDITOR) {
|
||||
cc.engine.off('design-resolution-changed', this._thisOnResized);
|
||||
}
|
||||
else {
|
||||
if (cc.sys.isMobile) {
|
||||
window.removeEventListener('resize', this._thisOnResized);
|
||||
}
|
||||
else {
|
||||
cc.view.off('canvas-resize', this._thisOnResized);
|
||||
}
|
||||
}
|
||||
|
||||
if (Canvas.instance === this) {
|
||||
Canvas.instance = null;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
alignWithScreen () {
|
||||
var designSize, nodeSize;
|
||||
if (CC_EDITOR) {
|
||||
nodeSize = designSize = cc.engine.getDesignResolutionSize();
|
||||
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;
|
||||
if (clipTopRight) {
|
||||
// offset the canvas to make it in the center of screen
|
||||
offsetX = (designSize.width - canvasSize.width) * 0.5;
|
||||
offsetY = (designSize.height - canvasSize.height) * 0.5;
|
||||
}
|
||||
this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1);
|
||||
}
|
||||
this.node.width = nodeSize.width;
|
||||
this.node.height = nodeSize.height;
|
||||
}
|
||||
|
||||
applySettings () {
|
||||
var ResolutionPolicy = cc.ResolutionPolicy;
|
||||
var policy;
|
||||
|
||||
if (this.fitHeight && this.fitWidth) {
|
||||
policy = ResolutionPolicy.SHOW_ALL;
|
||||
}
|
||||
else if (!this.fitHeight && !this.fitWidth) {
|
||||
policy = ResolutionPolicy.NO_BORDER;
|
||||
}
|
||||
else if (this.fitWidth) {
|
||||
policy = ResolutionPolicy.FIXED_WIDTH;
|
||||
}
|
||||
else { // fitHeight
|
||||
policy = ResolutionPolicy.FIXED_HEIGHT;
|
||||
}
|
||||
|
||||
var designRes = this._designResolution;
|
||||
if (CC_EDITOR) {
|
||||
cc.engine.setDesignResolutionSize(designRes.width, designRes.height);
|
||||
}
|
||||
else {
|
||||
cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cc.Canvas = Canvas;
|
||||
Vendored
+4
@@ -49,4 +49,8 @@ export class Component extends CCObject {
|
||||
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;
|
||||
}
|
||||
|
||||
Vendored
+3
-3
@@ -28,13 +28,13 @@ export class CCObject {
|
||||
protected _name: string;
|
||||
protected _objFlags: number;
|
||||
|
||||
public constructor(name: string);
|
||||
public constructor(name?: string);
|
||||
|
||||
public name: string;
|
||||
public isValid: boolean;
|
||||
public isRealValid: boolean;
|
||||
|
||||
public destroy(): boolean;
|
||||
public destroy(): any;
|
||||
public realDestroyInEditor(): void;
|
||||
public _clearDeferredDestroyTimer(): void;
|
||||
|
||||
@@ -43,6 +43,6 @@ export class CCObject {
|
||||
|
||||
protected _serialize?(): any;
|
||||
protected _deserialize?(data: any, ctx: any): any;
|
||||
protected _onPreDestroy: () => void | null;
|
||||
protected _onPreDestroy (): any;
|
||||
protected Flags: object;
|
||||
}
|
||||
|
||||
@@ -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<T = {}> = new (...args: any[]) => T;
|
||||
|
||||
class CallbackList {
|
||||
public callbacks: Array<Function | null> = [];
|
||||
|
||||
public targets: Array<Object | null> = []; // 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import * as js from '../utils/js';
|
||||
import { CallbacksInvoker } from './callbacks-invoker-base';
|
||||
import Event from './event';
|
||||
|
||||
const fastRemove = js.array.fastRemove;
|
||||
|
||||
type Constructor<T = {}> = new(...args: any[]) => T;
|
||||
|
||||
export type IEventTargetCallback = (...args: any[]) => void;
|
||||
|
||||
export function EventTarget<Base extends Constructor<{}>> (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<T extends Function>(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[];
|
||||
}
|
||||
@@ -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
|
||||
* <p>
|
||||
* Gets current target of the event <br/>
|
||||
* note: It only be available when the event listener is associated with node. <br/>
|
||||
* It returns 0 when the listener is associated with fixed priority.
|
||||
* </p>
|
||||
* !#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;
|
||||
@@ -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
|
||||
* <p>
|
||||
* Gets current target of the event <br/>
|
||||
* note: It only be available when the event listener is associated with node. <br/>
|
||||
* It returns 0 when the listener is associated with fixed priority.
|
||||
* </p>
|
||||
* !#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;
|
||||
@@ -48,7 +48,7 @@
|
||||
* @param {Number} callback
|
||||
*/
|
||||
export class EventListener {
|
||||
constructor (type, listenerID, callback) {
|
||||
constructor(type, listenerID, callback) {
|
||||
this._onEvent = callback; // Event callback function
|
||||
this._type = type || 0; // Event listener type
|
||||
this._listenerID = listenerID || ""; // Event listener ID
|
||||
@@ -74,7 +74,7 @@ export class EventListener {
|
||||
* @param {Boolean} paused
|
||||
* @private
|
||||
*/
|
||||
_setPaused (paused) {
|
||||
_setPaused(paused) {
|
||||
this._paused = paused;
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ export class EventListener {
|
||||
* @returns {Boolean}
|
||||
* @private
|
||||
*/
|
||||
_isPaused () {
|
||||
_isPaused() {
|
||||
return this._paused;
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ export class EventListener {
|
||||
* @param {Boolean} registered
|
||||
* @private
|
||||
*/
|
||||
_setRegistered (registered) {
|
||||
_setRegistered(registered) {
|
||||
this._registered = registered;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ export class EventListener {
|
||||
* @returns {Boolean}
|
||||
* @private
|
||||
*/
|
||||
_isRegistered () {
|
||||
_isRegistered() {
|
||||
return this._registered;
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ export class EventListener {
|
||||
* @returns {Number}
|
||||
* @private
|
||||
*/
|
||||
_getType () {
|
||||
_getType() {
|
||||
return this._type;
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ export class EventListener {
|
||||
* @returns {String}
|
||||
* @private
|
||||
*/
|
||||
_getListenerID () {
|
||||
_getListenerID() {
|
||||
return this._listenerID;
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ export class EventListener {
|
||||
* @param {Number} fixedPriority
|
||||
* @private
|
||||
*/
|
||||
_setFixedPriority (fixedPriority) {
|
||||
_setFixedPriority(fixedPriority) {
|
||||
this._fixedPriority = fixedPriority;
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ export class EventListener {
|
||||
* @returns {Number} 0 if it's a scene graph priority listener, non-zero for fixed priority listener
|
||||
* @private
|
||||
*/
|
||||
_getFixedPriority () {
|
||||
_getFixedPriority() {
|
||||
return this._fixedPriority;
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ export class EventListener {
|
||||
* @param {cc.Node} node
|
||||
* @private
|
||||
*/
|
||||
_setSceneGraphPriority (node) {
|
||||
_setSceneGraphPriority(node) {
|
||||
this._target = node;
|
||||
this._node = node;
|
||||
}
|
||||
@@ -159,7 +159,7 @@ export class EventListener {
|
||||
* @returns {cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener
|
||||
* @private
|
||||
*/
|
||||
_getSceneGraphPriority () {
|
||||
_getSceneGraphPriority() {
|
||||
return this._node;
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ export class EventListener {
|
||||
* @method checkAvailable
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
checkAvailable () {
|
||||
checkAvailable() {
|
||||
return this._onEvent !== null;
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ export class EventListener {
|
||||
* @method clone
|
||||
* @returns {EventListener}
|
||||
*/
|
||||
clone () {
|
||||
clone() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ export class EventListener {
|
||||
* 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){
|
||||
setEnabled(enabled) {
|
||||
this._isEnabled = enabled;
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ export class EventListener {
|
||||
* @method isEnabled
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
isEnabled(){
|
||||
isEnabled() {
|
||||
return this._isEnabled;
|
||||
}
|
||||
}
|
||||
@@ -275,7 +275,7 @@ var ListenerID = EventListener.ListenerID = {
|
||||
};
|
||||
|
||||
export class Mouse extends EventListener {
|
||||
constructor () {
|
||||
constructor() {
|
||||
super(EventListener.MOUSE, ListenerID.MOUSE);
|
||||
this._onEvent = this._callback;
|
||||
this.onMouseDown = null;
|
||||
@@ -284,7 +284,7 @@ export class Mouse extends EventListener {
|
||||
this.onMouseScroll = null;
|
||||
}
|
||||
|
||||
_callback (event) {
|
||||
_callback(event) {
|
||||
var eventType = cc.Event.EventMouse;
|
||||
switch (event._eventType) {
|
||||
case eventType.DOWN:
|
||||
@@ -308,7 +308,7 @@ export class Mouse extends EventListener {
|
||||
}
|
||||
}
|
||||
|
||||
clone () {
|
||||
clone() {
|
||||
var eventListener = new Mouse();
|
||||
eventListener.onMouseDown = this.onMouseDown;
|
||||
eventListener.onMouseUp = this.onMouseUp;
|
||||
@@ -317,17 +317,17 @@ export class Mouse extends EventListener {
|
||||
return eventListener;
|
||||
}
|
||||
|
||||
checkAvailable () {
|
||||
checkAvailable() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export class TouchOneByOne extends EventListener {
|
||||
constructor () {
|
||||
constructor() {
|
||||
super(EventListener.TOUCH_ONE_BY_ONE, ListenerID.TOUCH_ONE_BY_ONE);
|
||||
this._claimedTouches = [];
|
||||
|
||||
this._claimedTouches = null;
|
||||
// this._claimedTouches = null;
|
||||
this.swallowTouches = false;
|
||||
this.onTouchBegan = null;
|
||||
this.onTouchMoved = null;
|
||||
@@ -335,15 +335,15 @@ export class TouchOneByOne extends EventListener {
|
||||
this.onTouchCancelled = null;
|
||||
}
|
||||
|
||||
setSwallowTouches (needSwallow) {
|
||||
setSwallowTouches(needSwallow) {
|
||||
this.swallowTouches = needSwallow;
|
||||
}
|
||||
|
||||
isSwallowTouches(){
|
||||
isSwallowTouches() {
|
||||
return this.swallowTouches;
|
||||
}
|
||||
|
||||
clone () {
|
||||
clone() {
|
||||
var eventListener = new TouchOneByOne();
|
||||
eventListener.onTouchBegan = this.onTouchBegan;
|
||||
eventListener.onTouchMoved = this.onTouchMoved;
|
||||
@@ -353,8 +353,8 @@ export class TouchOneByOne extends EventListener {
|
||||
return eventListener;
|
||||
}
|
||||
|
||||
checkAvailable () {
|
||||
if(!this.onTouchBegan){
|
||||
checkAvailable() {
|
||||
if (!this.onTouchBegan) {
|
||||
cc.logID(1801);
|
||||
return false;
|
||||
}
|
||||
@@ -363,7 +363,7 @@ export class TouchOneByOne extends EventListener {
|
||||
}
|
||||
|
||||
export class TouchAllAtOnce extends EventListener {
|
||||
constructor () {
|
||||
constructor() {
|
||||
super(EventListener.TOUCH_ALL_AT_ONCE, ListenerID.TOUCH_ALL_AT_ONCE);
|
||||
|
||||
this.onTouchesBegan = null;
|
||||
@@ -372,7 +372,7 @@ export class TouchAllAtOnce extends EventListener {
|
||||
this.onTouchesCancelled = null;
|
||||
}
|
||||
|
||||
clone () {
|
||||
clone() {
|
||||
var eventListener = new TouchAllAtOnce();
|
||||
eventListener.onTouchesBegan = this.onTouchesBegan;
|
||||
eventListener.onTouchesMoved = this.onTouchesMoved;
|
||||
@@ -381,7 +381,7 @@ export class TouchAllAtOnce extends EventListener {
|
||||
return eventListener;
|
||||
}
|
||||
|
||||
checkAvailable () {
|
||||
checkAvailable() {
|
||||
if (this.onTouchesBegan === null && this.onTouchesMoved === null
|
||||
&& this.onTouchesEnded === null && this.onTouchesCancelled === null) {
|
||||
cc.logID(1802);
|
||||
@@ -393,23 +393,23 @@ export class TouchAllAtOnce extends EventListener {
|
||||
|
||||
//Acceleration
|
||||
export class Acceleration extends EventListener {
|
||||
constructor (callback) {
|
||||
constructor(callback) {
|
||||
super(EventListener.ACCELERATION, ListenerID.ACCELERATION);
|
||||
this._onEvent = this._callback;
|
||||
this._onAccelerationEvent = callback;
|
||||
this_onAccelerationEvent = null;
|
||||
}
|
||||
|
||||
_callback (event) {
|
||||
_callback(event) {
|
||||
this._onAccelerationEvent(event.acc, event);
|
||||
}
|
||||
|
||||
checkAvailable () {
|
||||
checkAvailable() {
|
||||
cc.assertID(this._onAccelerationEvent, 1803);
|
||||
return true;
|
||||
}
|
||||
|
||||
clone () {
|
||||
clone() {
|
||||
return new Acceleration(this._onAccelerationEvent);
|
||||
}
|
||||
}
|
||||
@@ -417,14 +417,14 @@ export class Acceleration extends EventListener {
|
||||
|
||||
//Keyboard
|
||||
export class Keyboard extends EventListener {
|
||||
constructor () {
|
||||
constructor() {
|
||||
super(EventListener.KEYBOARD, ListenerID.KEYBOARD);
|
||||
this._onEvent = this._callback;
|
||||
this.onKeyPressed = null;
|
||||
this.onKeyReleased = null;
|
||||
}
|
||||
|
||||
_callback (event) {
|
||||
_callback(event) {
|
||||
if (event.isPressed) {
|
||||
if (this.onKeyPressed)
|
||||
this.onKeyPressed(event.keyCode, event);
|
||||
@@ -434,14 +434,14 @@ export class Keyboard extends EventListener {
|
||||
}
|
||||
}
|
||||
|
||||
clone () {
|
||||
clone() {
|
||||
var eventListener = new Keyboard();
|
||||
eventListener.onKeyPressed = this.onKeyPressed;
|
||||
eventListener.onKeyReleased = this.onKeyReleased;
|
||||
return eventListener;
|
||||
}
|
||||
|
||||
checkAvailable () {
|
||||
checkAvailable() {
|
||||
if (this.onKeyPressed === null && this.onKeyReleased === null) {
|
||||
cc.logID(1800);
|
||||
return false;
|
||||
@@ -464,29 +464,29 @@ export class Keyboard extends EventListener {
|
||||
* @example {@link cocos2d/core/event-manager/CCEventListener/create.js}
|
||||
*/
|
||||
EventListener.create = function (argObj) {
|
||||
cc.assertID(argObj&&argObj.event, 1900);
|
||||
cc.assertID(argObj && argObj.event, 1900);
|
||||
|
||||
var listenerType = argObj.event;
|
||||
delete argObj.event;
|
||||
|
||||
var listener = null;
|
||||
if(listenerType === cc.EventListener.TOUCH_ONE_BY_ONE)
|
||||
if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE)
|
||||
listener = new TouchOneByOne();
|
||||
else if(listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE)
|
||||
else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE)
|
||||
listener = new TouchAllAtOnce();
|
||||
else if(listenerType === cc.EventListener.MOUSE)
|
||||
else if (listenerType === cc.EventListener.MOUSE)
|
||||
listener = new Mouse();
|
||||
else if(listenerType === cc.EventListener.KEYBOARD)
|
||||
else if (listenerType === cc.EventListener.KEYBOARD)
|
||||
listener = new Keyboard();
|
||||
else if(listenerType === cc.EventListener.ACCELERATION){
|
||||
else if (listenerType === cc.EventListener.ACCELERATION) {
|
||||
listener = new Acceleration(argObj.callback);
|
||||
delete argObj.callback;
|
||||
}
|
||||
|
||||
for(var key in argObj) {
|
||||
for (var key in argObj) {
|
||||
listener[key] = argObj[key];
|
||||
}
|
||||
return listener;
|
||||
}
|
||||
|
||||
cc.EventListener = EventListener;
|
||||
cc.EventListener = EventListener;
|
||||
|
||||
@@ -25,49 +25,49 @@
|
||||
****************************************************************************/
|
||||
|
||||
import * as js from '../../utils/js';
|
||||
import {EventListener} from './CCEventListener';
|
||||
import { EventListener } from './CCEventListener';
|
||||
const ListenerID = EventListener.ListenerID;
|
||||
|
||||
class _EventListenerVector {
|
||||
constructor () {
|
||||
constructor() {
|
||||
this._fixedListeners = [];
|
||||
this._sceneGraphListeners = [];
|
||||
this.gt0Index = 0;
|
||||
}
|
||||
|
||||
size () {
|
||||
size() {
|
||||
return this._fixedListeners.length + this._sceneGraphListeners.length;
|
||||
}
|
||||
|
||||
empty () {
|
||||
empty() {
|
||||
return (this._fixedListeners.length === 0) && (this._sceneGraphListeners.length === 0);
|
||||
}
|
||||
|
||||
push (listener) {
|
||||
push(listener) {
|
||||
if (listener._getFixedPriority() === 0)
|
||||
this._sceneGraphListeners.push(listener);
|
||||
else
|
||||
this._fixedListeners.push(listener);
|
||||
}
|
||||
|
||||
clearSceneGraphListeners () {
|
||||
clearSceneGraphListeners() {
|
||||
this._sceneGraphListeners.length = 0;
|
||||
}
|
||||
|
||||
clearFixedListeners () {
|
||||
clearFixedListeners() {
|
||||
this._fixedListeners.length = 0;
|
||||
}
|
||||
|
||||
clear () {
|
||||
clear() {
|
||||
this._sceneGraphListeners.length = 0;
|
||||
this._fixedListeners.length = 0;
|
||||
}
|
||||
|
||||
getFixedPriorityListeners () {
|
||||
getFixedPriorityListeners() {
|
||||
return this._fixedListeners;
|
||||
}
|
||||
|
||||
getSceneGraphPriorityListeners () {
|
||||
getSceneGraphPriorityListeners() {
|
||||
return this._sceneGraphListeners;
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ var __getListenerID = function (event) {
|
||||
return ListenerID.KEYBOARD;
|
||||
if (type.startsWith(eventType.MOUSE))
|
||||
return ListenerID.MOUSE;
|
||||
if (type.startsWith(eventType.TOUCH)){
|
||||
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);
|
||||
@@ -125,16 +125,16 @@ var eventManager = {
|
||||
_inDispatch: 0,
|
||||
_isEnabled: false,
|
||||
_nodePriorityIndex: 0,
|
||||
_internalCustomListenerIDs:[],
|
||||
_internalCustomListenerIDs: [],
|
||||
|
||||
_setDirtyForNode (node) {
|
||||
_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++)
|
||||
if (node.children.length > 0) {
|
||||
var _children = node.children;
|
||||
for (var i = 0, len = _children ? _children.length : 0; i < len; i++)
|
||||
this._setDirtyForNode(_children[i]);
|
||||
}
|
||||
},
|
||||
@@ -146,7 +146,7 @@ var eventManager = {
|
||||
* @param {Node} node
|
||||
* @param {Boolean} [recursive=false]
|
||||
*/
|
||||
pauseTarget (node, recursive) {
|
||||
pauseTarget(node, recursive) {
|
||||
if (!(node instanceof cc._BaseNode)) {
|
||||
cc.warnID(3506);
|
||||
return;
|
||||
@@ -157,7 +157,7 @@ var eventManager = {
|
||||
listeners[i]._setPaused(true);
|
||||
}
|
||||
if (recursive === true) {
|
||||
var locChildren = node.getChildren();
|
||||
var locChildren = node.children;
|
||||
for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++)
|
||||
this.pauseTarget(locChildren[i], true);
|
||||
}
|
||||
@@ -170,32 +170,32 @@ var eventManager = {
|
||||
* @param {Node} node
|
||||
* @param {Boolean} [recursive=false]
|
||||
*/
|
||||
resumeTarget (node, recursive) {
|
||||
resumeTarget(node, recursive) {
|
||||
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++)
|
||||
if (listeners) {
|
||||
for (i = 0, len = listeners.length; i < len; i++)
|
||||
listeners[i]._setPaused(false);
|
||||
}
|
||||
this._setDirtyForNode(node);
|
||||
if (recursive === true && node.getChildren) {
|
||||
var locChildren = node.getChildren();
|
||||
if (recursive === true && node.children.length > 0) {
|
||||
var locChildren = node.children;
|
||||
for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++)
|
||||
this.resumeTarget(locChildren[i], true);
|
||||
}
|
||||
},
|
||||
|
||||
_addListener (listener) {
|
||||
_addListener(listener) {
|
||||
if (this._inDispatch === 0)
|
||||
this._forceAddEventListener(listener);
|
||||
else
|
||||
this._toAddedListeners.push(listener);
|
||||
},
|
||||
|
||||
_forceAddEventListener (listener) {
|
||||
_forceAddEventListener(listener) {
|
||||
var listenerID = listener._getListenerID();
|
||||
var listeners = this._listenersMap[listenerID];
|
||||
if (!listeners) {
|
||||
@@ -218,11 +218,11 @@ var eventManager = {
|
||||
this._setDirty(listenerID, DIRTY_FIXED_PRIORITY);
|
||||
},
|
||||
|
||||
_getListeners (listenerID) {
|
||||
_getListeners(listenerID) {
|
||||
return this._listenersMap[listenerID];
|
||||
},
|
||||
|
||||
_updateDirtyFlagForSceneGraph () {
|
||||
_updateDirtyFlagForSceneGraph() {
|
||||
if (this._dirtyNodes.length === 0)
|
||||
return;
|
||||
|
||||
@@ -240,7 +240,7 @@ var eventManager = {
|
||||
this._dirtyNodes.length = 0;
|
||||
},
|
||||
|
||||
_removeAllListenersInVector (listenerVector) {
|
||||
_removeAllListenersInVector(listenerVector) {
|
||||
if (!listenerVector)
|
||||
return;
|
||||
var selListener;
|
||||
@@ -259,7 +259,7 @@ var eventManager = {
|
||||
}
|
||||
},
|
||||
|
||||
_removeListenersForListenerID (listenerID) {
|
||||
_removeListenersForListenerID(listenerID) {
|
||||
var listeners = this._listenersMap[listenerID], i;
|
||||
if (listeners) {
|
||||
var fixedPriorityListeners = listeners.getFixedPriorityListeners();
|
||||
@@ -288,7 +288,7 @@ var eventManager = {
|
||||
}
|
||||
},
|
||||
|
||||
_sortEventListeners (listenerID) {
|
||||
_sortEventListeners(listenerID) {
|
||||
var dirtyFlag = DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap;
|
||||
if (locFlagMap[listenerID])
|
||||
dirtyFlag = locFlagMap[listenerID];
|
||||
@@ -300,15 +300,15 @@ var eventManager = {
|
||||
if (dirtyFlag & DIRTY_FIXED_PRIORITY)
|
||||
this._sortListenersOfFixedPriority(listenerID);
|
||||
|
||||
if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY){
|
||||
if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY) {
|
||||
var rootEntity = cc.director.getScene();
|
||||
if(rootEntity)
|
||||
if (rootEntity)
|
||||
this._sortListenersOfSceneGraphPriority(listenerID, rootEntity);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
_sortListenersOfSceneGraphPriority (listenerID, rootNode) {
|
||||
_sortListenersOfSceneGraphPriority(listenerID, rootNode) {
|
||||
var listeners = this._getListeners(listenerID);
|
||||
if (!listeners)
|
||||
return;
|
||||
@@ -327,7 +327,7 @@ var eventManager = {
|
||||
listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes);
|
||||
},
|
||||
|
||||
_sortEventListenersOfSceneGraphPriorityDes (l1, l2) {
|
||||
_sortEventListenersOfSceneGraphPriorityDes(l1, l2) {
|
||||
var locNodePriorityMap = eventManager._nodePriorityMap,
|
||||
node1 = l1._getSceneGraphPriority(),
|
||||
node2 = l2._getSceneGraphPriority();
|
||||
@@ -338,13 +338,13 @@ var eventManager = {
|
||||
return locNodePriorityMap[node2._id] - locNodePriorityMap[node1._id];
|
||||
},
|
||||
|
||||
_sortListenersOfFixedPriority (listenerID) {
|
||||
_sortListenersOfFixedPriority(listenerID) {
|
||||
var listeners = this._listenersMap[listenerID];
|
||||
if (!listeners)
|
||||
return;
|
||||
|
||||
var fixedListeners = listeners.getFixedPriorityListeners();
|
||||
if(!fixedListeners || fixedListeners.length === 0)
|
||||
if (!fixedListeners || fixedListeners.length === 0)
|
||||
return;
|
||||
// After sort: priority < 0, > 0
|
||||
fixedListeners.sort(this._sortListenersOfFixedPriorityAsc);
|
||||
@@ -359,11 +359,11 @@ var eventManager = {
|
||||
listeners.gt0Index = index;
|
||||
},
|
||||
|
||||
_sortListenersOfFixedPriorityAsc (l1, l2) {
|
||||
_sortListenersOfFixedPriorityAsc(l1, l2) {
|
||||
return l1._getFixedPriority() - l2._getFixedPriority();
|
||||
},
|
||||
|
||||
_onUpdateListeners (listeners) {
|
||||
_onUpdateListeners(listeners) {
|
||||
var fixedPriorityListeners = listeners.getFixedPriorityListeners();
|
||||
var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
|
||||
var i, selListener, idx, toRemovedListeners = this._toRemovedListeners;
|
||||
@@ -375,7 +375,7 @@ var eventManager = {
|
||||
cc.js.array.remove(sceneGraphPriorityListeners, selListener);
|
||||
// if item in toRemove list, remove it from the list
|
||||
idx = toRemovedListeners.indexOf(selListener);
|
||||
if(idx !== -1)
|
||||
if (idx !== -1)
|
||||
toRemovedListeners.splice(idx, 1);
|
||||
} else
|
||||
++i;
|
||||
@@ -389,7 +389,7 @@ var eventManager = {
|
||||
cc.js.array.remove(fixedPriorityListeners, selListener);
|
||||
// if item in toRemove list, remove it from the list
|
||||
idx = toRemovedListeners.indexOf(selListener);
|
||||
if(idx !== -1)
|
||||
if (idx !== -1)
|
||||
toRemovedListeners.splice(idx, 1);
|
||||
}
|
||||
else
|
||||
@@ -404,7 +404,7 @@ var eventManager = {
|
||||
listeners.clearFixedListeners();
|
||||
},
|
||||
|
||||
frameUpdateListeners () {
|
||||
frameUpdateListeners() {
|
||||
var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap;
|
||||
for (var selKey in locListenersMap) {
|
||||
if (locListenersMap[selKey].empty()) {
|
||||
@@ -424,7 +424,7 @@ var eventManager = {
|
||||
}
|
||||
},
|
||||
|
||||
_updateTouchListeners (event) {
|
||||
_updateTouchListeners(event) {
|
||||
var locInDispatch = this._inDispatch;
|
||||
cc.assertID(locInDispatch > 0, 3508);
|
||||
|
||||
@@ -456,7 +456,7 @@ var eventManager = {
|
||||
},
|
||||
|
||||
//Remove all listeners in _toRemoveListeners list and cleanup
|
||||
_cleanToRemovedListeners () {
|
||||
_cleanToRemovedListeners() {
|
||||
var toRemovedListeners = this._toRemovedListeners;
|
||||
for (var i = 0; i < toRemovedListeners.length; i++) {
|
||||
var selListener = toRemovedListeners[i];
|
||||
@@ -483,7 +483,7 @@ var eventManager = {
|
||||
toRemovedListeners.length = 0;
|
||||
},
|
||||
|
||||
_onTouchEventCallback (listener, argsObj) {
|
||||
_onTouchEventCallback(listener, argsObj) {
|
||||
// Skip if the listener was removed.
|
||||
if (!listener._isRegistered)
|
||||
return false;
|
||||
@@ -531,7 +531,7 @@ var eventManager = {
|
||||
return false;
|
||||
},
|
||||
|
||||
_dispatchTouchEvent (event) {
|
||||
_dispatchTouchEvent(event) {
|
||||
this._sortEventListeners(ListenerID.TOUCH_ONE_BY_ONE);
|
||||
this._sortEventListeners(ListenerID.TOUCH_ALL_AT_ONCE);
|
||||
|
||||
@@ -543,7 +543,7 @@ var eventManager = {
|
||||
return;
|
||||
|
||||
var originalTouches = event.getTouches(), mutableTouches = cc.js.array.copy(originalTouches);
|
||||
var oneByOneArgsObj = {event: event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null};
|
||||
var oneByOneArgsObj = { event: event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null };
|
||||
|
||||
//
|
||||
// process the target handlers 1st
|
||||
@@ -560,14 +560,14 @@ var eventManager = {
|
||||
// process standard handlers 2nd
|
||||
//
|
||||
if (allAtOnceListeners && mutableTouches.length > 0) {
|
||||
this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, {event: event, touches: mutableTouches});
|
||||
this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, { event: event, touches: mutableTouches });
|
||||
if (event.isStopped())
|
||||
return;
|
||||
}
|
||||
this._updateTouchListeners(event);
|
||||
},
|
||||
|
||||
_onTouchesEventCallback (listener, callbackParams) {
|
||||
_onTouchesEventCallback(listener, callbackParams) {
|
||||
// Skip if the listener was removed.
|
||||
if (!listener._registered)
|
||||
return false;
|
||||
@@ -591,7 +591,7 @@ var eventManager = {
|
||||
return false;
|
||||
},
|
||||
|
||||
_associateNodeAndEventListener (node, listener) {
|
||||
_associateNodeAndEventListener(node, listener) {
|
||||
var listeners = this._nodeListenersMap[node._id];
|
||||
if (!listeners) {
|
||||
listeners = [];
|
||||
@@ -600,7 +600,7 @@ var eventManager = {
|
||||
listeners.push(listener);
|
||||
},
|
||||
|
||||
_dissociateNodeAndEventListener (node, listener) {
|
||||
_dissociateNodeAndEventListener(node, listener) {
|
||||
var listeners = this._nodeListenersMap[node._id];
|
||||
if (listeners) {
|
||||
cc.js.array.remove(listeners, listener);
|
||||
@@ -609,7 +609,7 @@ var eventManager = {
|
||||
}
|
||||
},
|
||||
|
||||
_dispatchEventToListeners (listeners, onEvent, eventOrArgs) {
|
||||
_dispatchEventToListeners(listeners, onEvent, eventOrArgs) {
|
||||
var shouldStopPropagation = false;
|
||||
var fixedPriorityListeners = listeners.getFixedPriorityListeners();
|
||||
var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
|
||||
@@ -648,7 +648,7 @@ var eventManager = {
|
||||
}
|
||||
},
|
||||
|
||||
_setDirty (listenerID, flag) {
|
||||
_setDirty(listenerID, flag) {
|
||||
var locDirtyFlagMap = this._priorityDirtyFlagMap;
|
||||
if (locDirtyFlagMap[listenerID] == null)
|
||||
locDirtyFlagMap[listenerID] = flag;
|
||||
@@ -656,12 +656,12 @@ var eventManager = {
|
||||
locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID];
|
||||
},
|
||||
|
||||
_visitTarget (node, isRootNode) {
|
||||
_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 children = node.children, i = 0;
|
||||
var childrenCount = children.length, locGlobalZOrderNodeMap = this._globalZOrderNodeMap, locNodeListenersMap = this._nodeListenersMap;
|
||||
|
||||
if (childrenCount > 0) {
|
||||
@@ -693,7 +693,7 @@ var eventManager = {
|
||||
}
|
||||
},
|
||||
|
||||
_sortNumberAsc (a, b) {
|
||||
_sortNumberAsc(a, b) {
|
||||
return a - b;
|
||||
},
|
||||
|
||||
@@ -704,7 +704,7 @@ var eventManager = {
|
||||
* @param {String|Number} listenerID - The listener id.
|
||||
* @return {Boolean} true or false
|
||||
*/
|
||||
hasEventListener (listenerID) {
|
||||
hasEventListener(listenerID) {
|
||||
return !!this._getListeners(listenerID);
|
||||
},
|
||||
|
||||
@@ -731,7 +731,7 @@ var eventManager = {
|
||||
* except calls removeAllListeners().
|
||||
* @return {EventListener} Return the listener. Needed in order to remove the event from the dispatcher.
|
||||
*/
|
||||
addListener (listener, nodeOrPriority) {
|
||||
addListener(listener, nodeOrPriority) {
|
||||
cc.assertID(listener && nodeOrPriority, 3503);
|
||||
if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode)) {
|
||||
cc.warnID(3506);
|
||||
@@ -779,10 +779,10 @@ var eventManager = {
|
||||
* @param {Function} callback
|
||||
* @return {EventListener} the generated event. Needed in order to remove the event from the dispatcher
|
||||
*/
|
||||
addCustomListener (eventName, callback) {
|
||||
addCustomListener(eventName, callback) {
|
||||
var listener = new cc.EventListener.create({
|
||||
event: cc.EventListener.CUSTOM,
|
||||
eventName: eventName,
|
||||
eventName: eventName,
|
||||
callback: callback
|
||||
});
|
||||
this.addListener(listener, 1);
|
||||
@@ -796,7 +796,7 @@ var eventManager = {
|
||||
* @param {EventListener} listener - an event listener or a registered node target
|
||||
* @example {@link cocos2d/core/event-manager/CCEventManager/removeListener.js}
|
||||
*/
|
||||
removeListener (listener) {
|
||||
removeListener(listener) {
|
||||
if (listener == null)
|
||||
return;
|
||||
|
||||
@@ -806,10 +806,10 @@ var eventManager = {
|
||||
var fixedPriorityListeners = listeners.getFixedPriorityListeners(), 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)
|
||||
this._setDirty(listener._getListenerID(), DIRTY_FIXED_PRIORITY);
|
||||
@@ -837,7 +837,7 @@ var eventManager = {
|
||||
}
|
||||
},
|
||||
|
||||
_removeListenerInCallback(listeners, callback){
|
||||
_removeListenerInCallback(listeners, callback) {
|
||||
if (listeners == null)
|
||||
return false;
|
||||
|
||||
@@ -845,7 +845,7 @@ var eventManager = {
|
||||
var selListener = listeners[i];
|
||||
if (selListener._onCustomEvent === callback || selListener._onEvent === callback) {
|
||||
selListener._setRegistered(false);
|
||||
if (selListener._getSceneGraphPriority() != null){
|
||||
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.
|
||||
}
|
||||
@@ -860,7 +860,7 @@ var eventManager = {
|
||||
return false;
|
||||
},
|
||||
|
||||
_removeListenerInVector (listeners, listener) {
|
||||
_removeListenerInVector(listeners, listener) {
|
||||
if (listeners == null)
|
||||
return false;
|
||||
|
||||
@@ -901,7 +901,7 @@ var eventManager = {
|
||||
* @param {Number|Node} listenerType - listenerType or a node
|
||||
* @param {Boolean} [recursive=false]
|
||||
*/
|
||||
removeListeners (listenerType, recursive) {
|
||||
removeListeners(listenerType, recursive) {
|
||||
var i, _t = this;
|
||||
if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) {
|
||||
cc.warnID(3506);
|
||||
@@ -926,7 +926,7 @@ var eventManager = {
|
||||
// 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; ) {
|
||||
for (i = 0; i < locToAddedListeners.length;) {
|
||||
var listener = locToAddedListeners[i];
|
||||
if (listener._getSceneGraphPriority() === listenerType) {
|
||||
listener._setSceneGraphPriority(null); // Ensure no dangling ptr to the target node.
|
||||
@@ -938,7 +938,7 @@ var eventManager = {
|
||||
|
||||
if (recursive === true) {
|
||||
var locChildren = listenerType.getChildren(), len;
|
||||
for (i = 0, len = locChildren.length; i< len; i++)
|
||||
for (i = 0, len = locChildren.length; i < len; i++)
|
||||
_t.removeListeners(locChildren[i], true);
|
||||
}
|
||||
} else {
|
||||
@@ -963,7 +963,7 @@ var eventManager = {
|
||||
* @method removeCustomListeners
|
||||
* @param {String} customEventName
|
||||
*/
|
||||
removeCustomListeners (customEventName) {
|
||||
removeCustomListeners(customEventName) {
|
||||
this._removeListenersForListenerID(customEventName);
|
||||
},
|
||||
|
||||
@@ -972,10 +972,10 @@ var eventManager = {
|
||||
* !#zh 移除所有事件监听器。
|
||||
* @method removeAllListeners
|
||||
*/
|
||||
removeAllListeners () {
|
||||
removeAllListeners() {
|
||||
var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs;
|
||||
for (var selKey in locListeners){
|
||||
if(locInternalCustomEventIDs.indexOf(selKey) === -1)
|
||||
for (var selKey in locListeners) {
|
||||
if (locInternalCustomEventIDs.indexOf(selKey) === -1)
|
||||
this._removeListenersForListenerID(selKey);
|
||||
}
|
||||
},
|
||||
@@ -987,7 +987,7 @@ var eventManager = {
|
||||
* @param {EventListener} listener
|
||||
* @param {Number} fixedPriority
|
||||
*/
|
||||
setPriority (listener, fixedPriority) {
|
||||
setPriority(listener, fixedPriority) {
|
||||
if (listener == null)
|
||||
return;
|
||||
|
||||
@@ -998,7 +998,7 @@ var eventManager = {
|
||||
if (fixedPriorityListeners) {
|
||||
var 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);
|
||||
@@ -1016,7 +1016,7 @@ var eventManager = {
|
||||
* @method setEnabled
|
||||
* @param {Boolean} enabled
|
||||
*/
|
||||
setEnabled (enabled) {
|
||||
setEnabled(enabled) {
|
||||
this._isEnabled = enabled;
|
||||
},
|
||||
|
||||
@@ -1026,7 +1026,7 @@ var eventManager = {
|
||||
* @method isEnabled
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
isEnabled () {
|
||||
isEnabled() {
|
||||
return this._isEnabled;
|
||||
},
|
||||
|
||||
@@ -1036,7 +1036,7 @@ var eventManager = {
|
||||
* @method dispatchEvent
|
||||
* @param {Event} event
|
||||
*/
|
||||
dispatchEvent (event) {
|
||||
dispatchEvent(event) {
|
||||
if (!this._isEnabled)
|
||||
return;
|
||||
|
||||
@@ -1063,7 +1063,7 @@ var eventManager = {
|
||||
this._inDispatch--;
|
||||
},
|
||||
|
||||
_onListenerCallback(listener, event){
|
||||
_onListenerCallback(listener, event) {
|
||||
event.currentTarget = listener._target;
|
||||
listener._onEvent(event);
|
||||
return event.isStopped();
|
||||
@@ -1076,7 +1076,7 @@ var eventManager = {
|
||||
* @param {String} eventName
|
||||
* @param {*} optionalUserData
|
||||
*/
|
||||
dispatchCustomEvent (eventName, optionalUserData) {
|
||||
dispatchCustomEvent(eventName, optionalUserData) {
|
||||
var ev = new cc.Event.EventCustom(eventName);
|
||||
ev.setUserData(optionalUserData);
|
||||
this.dispatchEvent(ev);
|
||||
@@ -1085,4 +1085,4 @@ var eventManager = {
|
||||
|
||||
cc.eventManager = eventManager;
|
||||
|
||||
export default eventManager
|
||||
export default eventManager
|
||||
|
||||
@@ -31,13 +31,13 @@
|
||||
* !#zh
|
||||
* AffineTransform 类代表一个仿射变换矩阵。它基本上是由平移旋转,缩放转变所组成。<br/>
|
||||
* @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, <br/>
|
||||
* 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;
|
||||
|
||||
@@ -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|string|object} [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);
|
||||
};
|
||||
}
|
||||
|
||||
export { color };
|
||||
|
||||
cc.color = color;
|
||||
|
||||
cc.Color = Color;
|
||||
@@ -38,9 +38,9 @@ import * as js from '../utils/js';
|
||||
* 定义一个枚举类型。<br/>
|
||||
* 用户可以把枚举值设为任意的整数,如果设为 -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<T>(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
|
||||
*/
|
||||
@@ -120,7 +120,7 @@ if (CC_DEV) {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Object} enumx
|
||||
* @param enumx
|
||||
*/
|
||||
export function ccenum(enumx) {
|
||||
if ('__enums__' in enumx) {
|
||||
|
||||
@@ -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
|
||||
* 近似判断两个矩阵是否相等。<br/>
|
||||
* 判断 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);
|
||||
};
|
||||
@@ -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
|
||||
* 近似判断两个矩阵是否相等。<br/>
|
||||
* 判断 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;
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
};
|
||||
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;
|
||||
@@ -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 对象的帮助函数。<br/>
|
||||
* 注意:可以使用 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.<br/>
|
||||
* Please use cc.p or cc.v2 instead, it will soon replace cc.Size.
|
||||
* !#zh
|
||||
* 创建一个 cc.Size 对象的帮助函数。<br/>
|
||||
* 注意:可以使用 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;
|
||||
@@ -36,9 +36,9 @@ export class ValueType {
|
||||
/**
|
||||
* !#en This method returns an exact copy of current value.
|
||||
* !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。
|
||||
* @method clone
|
||||
*
|
||||
*/
|
||||
public clone (): this {
|
||||
public clone (): ValueType {
|
||||
cc.errorID('0100', js.getClassName(this) + '.clone');
|
||||
return this;
|
||||
}
|
||||
@@ -64,7 +64,7 @@ export class ValueType {
|
||||
* @param ratio - the interpolation coefficient
|
||||
* @returns
|
||||
*/
|
||||
public lerp (to: this, ratio: this) {
|
||||
public lerp (to: this, ratio: number) {
|
||||
cc.errorID('0100', js.getClassName(this) + '.lerp');
|
||||
return this.clone();
|
||||
}
|
||||
|
||||
@@ -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
|
||||
* 近似判断两个点是否相等。<br/>
|
||||
* 判断 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。<br/>
|
||||
* 向量小于 min_inclusive 则返回 min_inclusive。<br/>
|
||||
* 否则返回自身。
|
||||
* @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.<br/>
|
||||
* <br/>
|
||||
* 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
|
||||
* 返回归一化后的向量。<br/>
|
||||
* <br/>
|
||||
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 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);
|
||||
};
|
||||
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;
|
||||
@@ -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
|
||||
* 近似判断两个点是否相等。<br/>
|
||||
* 判断 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。<br/>
|
||||
* 向量小于 min_inclusive 则返回 min_inclusive。<br/>
|
||||
* 否则返回自身。
|
||||
* @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.<br/>
|
||||
* <br/>
|
||||
* 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
|
||||
* 返回归一化后的向量。<br/>
|
||||
* <br/>
|
||||
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 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);
|
||||
};
|
||||
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;
|
||||
@@ -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
|
||||
* 近似判断两个点是否相等。<br/>
|
||||
* 判断 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。<br/>
|
||||
* 向量小于 min_inclusive 则返回 min_inclusive。<br/>
|
||||
* 否则返回自身。
|
||||
* @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.<br/>
|
||||
* <br/>
|
||||
* 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
|
||||
* 返回归一化后的向量。<br/>
|
||||
* <br/>
|
||||
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 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);
|
||||
};
|
||||
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;
|
||||
@@ -682,7 +682,7 @@ export default class quat {
|
||||
* @param q - the quaternion to be converted
|
||||
* @return out.
|
||||
*/
|
||||
public static toEuler<Out extends IQuatLike>(out: Out, q: quat) {
|
||||
public static toEuler<Out extends IVec3Like>(out: Out, q: quat) {
|
||||
const { x, y, z, w } = q;
|
||||
let heading: number = NaN;
|
||||
let attitude: number = NaN;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { GFXAttributeName, GFXFormat } from './define';
|
||||
|
||||
const vfmt = [
|
||||
{
|
||||
name: GFXAttributeName.ATTR_POSITION,
|
||||
format: GFXFormat.RGB32F,
|
||||
},
|
||||
{
|
||||
name: GFXAttributeName.ATTR_COLOR,
|
||||
format: GFXFormat.RGB32F,
|
||||
},
|
||||
{
|
||||
name: GFXAttributeName.ATTR_TEX_COORD,
|
||||
format: GFXFormat.RGB32F,
|
||||
},
|
||||
];
|
||||
|
||||
export {
|
||||
vfmt,
|
||||
};
|
||||
@@ -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];
|
||||
|
||||
@@ -48,10 +48,10 @@ export class Camera {
|
||||
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 _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 _node: Node | null = null;
|
||||
private _view: RenderView;
|
||||
|
||||
@@ -121,7 +121,7 @@ export class RenderScene {
|
||||
this._pointLights = [];
|
||||
}
|
||||
|
||||
public createModel<T extends Model> (clazz: new () => T): Model {
|
||||
public createModel<T extends Model> (clazz: new () => T): T {
|
||||
const model = new clazz();
|
||||
model.initialize();
|
||||
model.scene = this;
|
||||
|
||||
@@ -79,7 +79,7 @@ export class RenderData extends BaseRenderData {
|
||||
}
|
||||
}
|
||||
|
||||
const _dataPool = new RecyclePool(128, () => {
|
||||
const _dataPool = new RecyclePool(() => {
|
||||
return {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
@@ -88,8 +88,8 @@ const _dataPool = new RecyclePool(128, () => {
|
||||
v: 0.0,
|
||||
color: 0,
|
||||
};
|
||||
});
|
||||
}, 128);
|
||||
|
||||
const _pool = new RecyclePool(32, () => {
|
||||
const _pool = new RecyclePool( () => {
|
||||
return new RenderData();
|
||||
});
|
||||
}, 32);
|
||||
|
||||
+88
-13
@@ -1,7 +1,9 @@
|
||||
|
||||
// import { vfmt3D } from '../../2d/renderer/webgl/vertex-format';
|
||||
import RecyclePool from '../../3d/memop/recycle-pool';
|
||||
import { CachedArray } from '../../core/memop/cached-array';
|
||||
import { MeshBuffer, IMeshBufferInitData } from '../../3d/ui/mesh-buffer';
|
||||
import { Material } from '../../3d/assets/material';
|
||||
import { SpriteFrame } from '../../assets/CCSpriteFrame';
|
||||
import { Root } from '../../core/root';
|
||||
import { GFXBindingLayout } from '../../gfx/binding-layout';
|
||||
import { GFXBuffer } from '../../gfx/buffer';
|
||||
@@ -14,7 +16,15 @@ import { GFXPipelineState } from '../../gfx/pipeline-state';
|
||||
import { Pass } from '../core/pass';
|
||||
import { Camera } from '../scene/camera';
|
||||
import { RenderScene } from '../scene/render-scene';
|
||||
import { CanvasComponent } from '../../3d/ui/components/canvas-component';
|
||||
import { LabelComponent } from '../../3d/ui/components/label-component';
|
||||
import { SpriteComponent } from '../../3d/ui/components/sprite-component';
|
||||
import { UIBatchModel } from './ui-batch-model';
|
||||
import { vfmt } from '../../gfx/vertex-format-sample';
|
||||
// import { GFXBuffer } from '../../gfx/buffer';
|
||||
// import { RenderComponent } from '../../3d/ui/components/ui-render-component';
|
||||
|
||||
// import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define';
|
||||
|
||||
export interface IUIBufferBatch {
|
||||
vb: GFXBuffer;
|
||||
@@ -30,17 +40,25 @@ export interface IUIRenderItem {
|
||||
inputAssembler: GFXInputAssembler;
|
||||
}
|
||||
|
||||
export class UI {
|
||||
// private _buffer: MeshBuffer | null = new MeshBuffer(this, vfmt3D);
|
||||
private _batchedModels: UIBatchModel[] = [];
|
||||
private _iaPool: RecyclePool | null = new RecyclePool(16, () => {
|
||||
// return this._root.device.createInputAssembler({
|
||||
export interface IUIRenderData {
|
||||
meshBuffer: MeshBuffer;
|
||||
material: Material;
|
||||
}
|
||||
|
||||
// });
|
||||
});
|
||||
private _modelPool: RecyclePool = new RecyclePool(16, () => {
|
||||
return this._scene.createModel(UIBatchModel);
|
||||
});
|
||||
export class UI {
|
||||
private _screens: CanvasComponent[] = [];
|
||||
private _bufferPool: RecyclePool = new RecyclePool(() => {
|
||||
return new MeshBuffer();
|
||||
}, 128);
|
||||
|
||||
// private _currScreen: CanvasComponent | null = null;
|
||||
// private _currMaterail: Material | null = null;
|
||||
// private _currSpriteFrame: SpriteFrame | null = null;
|
||||
// private _currUserKey = 0;
|
||||
// private _dummyNode: Node | null = null;
|
||||
// private _batchedModels: UIBatchModel[] = [];
|
||||
// private _iaPool: RecyclePool | null = null;
|
||||
// private _modelPool: RecyclePool | null = null;
|
||||
private _device: GFXDevice;
|
||||
private _cmdBuff: GFXCommandBuffer | null = null;
|
||||
private _renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 };
|
||||
@@ -48,6 +66,7 @@ export class UI {
|
||||
private _attributes: IGFXInputAttribute[] = [];
|
||||
private _bufferBatches: IUIBufferBatch[] = [];
|
||||
private _items: CachedArray<IUIRenderItem>;
|
||||
private _commitBuffers: any[] = [];
|
||||
|
||||
constructor (private _root: Root) {
|
||||
this._device = _root.device;
|
||||
@@ -91,21 +110,77 @@ export class UI {
|
||||
}
|
||||
|
||||
public addScreen (comp) {
|
||||
this._screens.push(comp);
|
||||
}
|
||||
|
||||
public removeScreen (comp) {
|
||||
const idx = this._screens.indexOf(comp);
|
||||
if (idx !== -1) {
|
||||
this._screens.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
public update (dt: number) {
|
||||
this._items.clear();
|
||||
|
||||
// TODO: Merge batch here.
|
||||
this._renderScreens();
|
||||
|
||||
this.render();
|
||||
}
|
||||
|
||||
private _emit (): UIBatchModel[] {
|
||||
return this._batchedModels;
|
||||
public _walk (node, fn1, fn2, level = 0) {
|
||||
level += 1;
|
||||
const len = node.children.length;
|
||||
|
||||
for (let i = 0; i < len; ++i) {
|
||||
const child = node.children[i];
|
||||
const continueWalk = fn1(child, node, level);
|
||||
|
||||
if (continueWalk === false) {
|
||||
fn2(child, node, level);
|
||||
break;
|
||||
}
|
||||
|
||||
this._walk(child, fn1, fn2, level);
|
||||
// fn2(child, node, level);
|
||||
}
|
||||
}
|
||||
|
||||
private _renderScreens () {
|
||||
for (const screen of this._screens) {
|
||||
if (!screen.enabledInHierarchy) {
|
||||
continue;
|
||||
}
|
||||
// this._currScreen = screen;
|
||||
|
||||
this._walk(screen.node, (c) => {
|
||||
const image = c.getComponent(SpriteComponent);
|
||||
if (image && image.enabledInHierarchy) {
|
||||
this._commitComp(image);
|
||||
}
|
||||
|
||||
const label = c.getComponent(LabelComponent);
|
||||
if (label && label.enabledInHierarchy) {
|
||||
this._commitComp(label);
|
||||
}
|
||||
}, null);
|
||||
}
|
||||
}
|
||||
|
||||
private _commitComp (comp) {
|
||||
const buffer = this._bufferPool.add();
|
||||
buffer.initialize({
|
||||
vertexCount: comp.renderData.vertexCount,
|
||||
indexCount: comp.renderData.indiceCount,
|
||||
attributes: vfmt,
|
||||
} as IMeshBufferInitData);
|
||||
comp.updateRenderData(buffer);
|
||||
this._emit({ meshBuffer: buffer, material: comp.material} as IUIRenderData);
|
||||
}
|
||||
|
||||
private _emit (renderData: IUIRenderData) {
|
||||
this._commitBuffers.push(renderData);
|
||||
}
|
||||
|
||||
private render () {
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
Vendored
-77
@@ -1,77 +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 { CCObject } from '../core/data/object';
|
||||
import { Component } from '../components/component';
|
||||
|
||||
export class BaseNode extends CCObject {
|
||||
protected static _setScene(node: BaseNode): void;
|
||||
|
||||
protected _parent: this | null;
|
||||
protected _children: this[];
|
||||
protected _active: boolean;
|
||||
protected _level: number;
|
||||
protected _components: Component[];
|
||||
protected _persistNode: boolean;
|
||||
|
||||
protected uuid: string;
|
||||
protected children: this[];
|
||||
protected childrenCount: number;
|
||||
protected active: boolean;
|
||||
protected parent: this;
|
||||
|
||||
public getParent(): this;
|
||||
public setParent(value: this): void;
|
||||
public getChildByUuid(uuid: string): this;
|
||||
public getChildByName(name: string): this;
|
||||
public getChildByPath(path: string): this;
|
||||
public addChild(child: this): void;
|
||||
public insertChild(child: this, siblingIndex: number): void;
|
||||
public getSiblingIndex(): number;
|
||||
public setSiblingIndex(index: number): void;
|
||||
public walk(prefunc: (target: this) => any, postfunc: (target: this) => any): void;
|
||||
public removeFromParent(cleanup: boolean): void;
|
||||
public removeChild(child: this, cleanup: boolean): void;
|
||||
public removeAllChildren(cleanup: boolean): void;
|
||||
public isChildOf(parent: this): boolean;
|
||||
|
||||
public getComponent(typeOrClassName: object | string): Component | null;
|
||||
public getComponents(typeOrClassName: object | string): Component[];
|
||||
public getComponentInChildren(typeOrClassName: object | string): Component | null;
|
||||
public getComponentsInChildren(typeOrClassName: object | string): Component[];
|
||||
public addComponent(typeOrClassName: object | string): Component | null;
|
||||
public removeComponent(typeOrClassName: object | string): void;
|
||||
public destroyAllChildren(): void;
|
||||
public cleanup(): void;
|
||||
public onRestore(): void;
|
||||
|
||||
protected _onSetParent(oldParent: this): void;
|
||||
protected _onPostActivated(): void;
|
||||
protected _onBatchRestored(): void;
|
||||
protected _onBatchCreated(): void;
|
||||
protected _onHierarchyChanged(oldParent: this): void;
|
||||
protected _onHierarchyChangedBase(oldParent: this): void;
|
||||
protected _instantiate(cloned: this): this;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+393
-346
File diff suppressed because it is too large
Load Diff
+617
-5
@@ -1,21 +1,216 @@
|
||||
import { ccclass, mixins, property } from '../core/data/class-decorator';
|
||||
import { EventTarget } from '../core/event';
|
||||
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 { UITransformComponent } from '../3d/ui/components/ui-transfrom-component';
|
||||
import { BaseNode } from './base-node';
|
||||
import { Layers } from './layers';
|
||||
import { EventTarget } from '../core/event/event-target-base';
|
||||
|
||||
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,
|
||||
@@ -23,7 +218,7 @@ enum NodeSpace {
|
||||
|
||||
@ccclass('cc.Node')
|
||||
@mixins(EventTarget)
|
||||
class Node extends BaseNode {
|
||||
class Node extends EventTarget(BaseNode) {
|
||||
public static EventType = EventType;
|
||||
public static NodeSpace = NodeSpace;
|
||||
|
||||
@@ -31,6 +226,8 @@ class Node extends BaseNode {
|
||||
public static isNode (obj: object) {
|
||||
return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene));
|
||||
}
|
||||
public uiTransfromComp: UITransformComponent | null = null;
|
||||
|
||||
// local transform
|
||||
@property
|
||||
protected _lpos = new Vec3();
|
||||
@@ -57,6 +254,9 @@ class Node extends BaseNode {
|
||||
protected _matDirty = false;
|
||||
protected _eulerDirty = false;
|
||||
|
||||
protected _bubblingListeners: EventTarget|null = null;
|
||||
protected _capturingListeners: EventTarget | null = null;
|
||||
|
||||
@property({
|
||||
type: Vec3,
|
||||
})
|
||||
@@ -79,9 +279,72 @@ class Node extends BaseNode {
|
||||
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);
|
||||
// EventTarget.call(this);
|
||||
}
|
||||
|
||||
// ===============================
|
||||
@@ -575,9 +838,9 @@ class Node extends BaseNode {
|
||||
*/
|
||||
public setWorldScale (val: Vec3 | number, y?: number, z?: number) {
|
||||
if (y === undefined || z === undefined) {
|
||||
vec3.copy(this._scale, val);
|
||||
vec3.copy(this._scale, val as Vec3);
|
||||
} else if (arguments.length === 3) {
|
||||
vec3.set(this._scale, val, y, z);
|
||||
vec3.set(this._scale, val as number, y, z);
|
||||
}
|
||||
if (this._parent) {
|
||||
this._parent.getWorldScale(v3_a);
|
||||
@@ -646,6 +909,355 @@ class Node extends BaseNode {
|
||||
}
|
||||
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 = 0) {
|
||||
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.<br/>
|
||||
* Use this method to register touch or mouse event permit propagation based on scene graph,<br/>
|
||||
* These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:<br/>
|
||||
* 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target<br/>
|
||||
* 2. At target phase: dispatch to the listeners of the real target<br/>
|
||||
* 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root<br/>
|
||||
* In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.<br/>
|
||||
* It's the recommended way to register touch/mouse event for Node,<br/>
|
||||
* please do not use cc.eventManager directly for Node.<br/>
|
||||
* You can also register custom event and use `emit` to trigger custom event on Node.<br/>
|
||||
* 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.<br/>
|
||||
* You can also pass event callback parameters with `emit` by passing parameters after `type`.
|
||||
* !#zh
|
||||
* 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。<br/>
|
||||
* 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:<br/>
|
||||
* 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。<br/>
|
||||
* 2. 目标阶段:派发给目标节点的监听器。<br/>
|
||||
* 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。<br/>
|
||||
* 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。<br/>
|
||||
* 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。<br/>
|
||||
* 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器<br/>
|
||||
* 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
|
||||
* @method on
|
||||
* @param {String|Node.EventType} type - A string representing the event type to listen for.<br>See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
|
||||
* @param {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<T extends Function>(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) {
|
||||
const forDispatch = this._checknSetupSysEvent(type);
|
||||
if (forDispatch) {
|
||||
return this._onDispatch(type, callback, target, useCapture);
|
||||
} else {
|
||||
// switch (type) {
|
||||
// case EventType.POSITION_CHANGED:
|
||||
// this._eventMask |= POSITION_ON;
|
||||
// break;
|
||||
// case EventType.SCALE_CHANGED:
|
||||
// this._eventMask |= SCALE_ON;
|
||||
// break;
|
||||
// case EventType.ROTATION_CHANGED:
|
||||
// this._eventMask |= ROTATION_ON;
|
||||
// break;
|
||||
// case EventType.SIZE_CHANGED:
|
||||
// this._eventMask |= SIZE_ON;
|
||||
// break;
|
||||
// case EventType.ANCHOR_CHANGED:
|
||||
// this._eventMask |= ANCHOR_ON;
|
||||
// break;
|
||||
// }
|
||||
if (!this._bubblingListeners) {
|
||||
this._bubblingListeners = new EventTarget();
|
||||
}
|
||||
return this._bubblingListeners.on(type, callback, target);
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * !#en
|
||||
// * Register an callback of a specific event type on the Node,
|
||||
// * the callback will remove itself after the first time it is triggered.
|
||||
// * !#zh
|
||||
// * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
|
||||
// *
|
||||
// * @method once
|
||||
// * @param {String} type - A string representing the event type to listen for.
|
||||
// * @param {Function} callback - The callback that will be invoked when the event is dispatched.
|
||||
// * The callback is ignored if it is a duplicate (the callbacks are unique).
|
||||
// * @param {Event|any} [callback.event] event or first argument when emit
|
||||
// * @param {any} [callback.arg2] arg2
|
||||
// * @param {any} [callback.arg3] arg3
|
||||
// * @param {any} [callback.arg4] arg4
|
||||
// * @param {any} [callback.arg5] arg5
|
||||
// * @param {Object} [target] - The target (this object) to invoke the callback, can be null
|
||||
// * @typescript
|
||||
// * once<T extends Function>(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 EventTarget();
|
||||
// }
|
||||
// else {
|
||||
// listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget();
|
||||
// }
|
||||
|
||||
// let hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target);
|
||||
// if (!hasOnceListener) {
|
||||
// let self = this;
|
||||
// let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) {
|
||||
// self.off(type, onceWrapper, target);
|
||||
// listeners.remove(eventType_hasOnceListener, callback, target);
|
||||
// callback.call(this, 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 EventTarget();
|
||||
} else {
|
||||
listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget();
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
|
||||
@@ -62,21 +62,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');
|
||||
@@ -92,7 +92,7 @@ export default class Scene extends Node {
|
||||
this.walk(BaseNode._setScene);
|
||||
}
|
||||
|
||||
_activate (active) {
|
||||
_activate(active) {
|
||||
active = (active !== false);
|
||||
if (CC_EDITOR || CC_TEST) {
|
||||
// register all nodes to editor
|
||||
|
||||
Reference in New Issue
Block a user