diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 95967ed013..9aff349942 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -22,9 +22,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -require('../label/CCSGLabel'); -require('../label/CCSGLabelCanvasRenderCmd'); -require('../label/CCSGLabelWebGLRenderCmd'); + + const RenderComponent = require('./CCRenderComponent'); + const renderer = require('../renderer'); + const renderEngine = require('../renderer/render-engine'); + const RenderData = renderEngine.RenderData; + const SpriteMaterial = renderEngine.SpriteMaterial; + /** * !#en Enum for text alignment. * !#zh 文本横向对齐类型 @@ -94,7 +98,12 @@ var VerticalAlign = cc.VerticalTextAlignment; * !#zh 在 RESIZE_HEIGHT 模式下,只能更改文本的宽度,高度是自动改变的。 * @property {Number} RESIZE_HEIGHT */ -var Overflow = _ccsg.Label.Overflow; +var Overflow = cc.Enum({ + NONE: 0, + CLAMP: 1, + SHRINK: 2, + RESIZE_HEIGHT: 3 +});; /** * !#en Enum for font type. @@ -146,15 +155,14 @@ function debounce (func, wait, immediate) { */ var Label = cc.Class({ name: 'cc.Label', - extends: cc.Component, + extends: RenderComponent, ctor: function() { - if(CC_EDITOR) { - this._userDefinedFontSize = 40; + if (CC_EDITOR) { this._userDefinedFont = null; - this._debouncedUpdateSgNodeString = debounce(this._updateSgNodeString, 200); - this._debouncedUpdateFontSize = debounce(this._updateSgNodeFontSize, 200); } + + this._actualFontSize = 0; }, editor: CC_EDITOR && { @@ -163,19 +171,6 @@ var Label = cc.Class({ inspector: 'packages://inspector/inspectors/comps/label.js', }, - _updateSgNodeString: function() { - return; - this._sgNode.setString(this.string); - this._updateNodeSize(); - }, - - _updateSgNodeFontSize: function() { - if (this._sgNode) { - this._sgNode.setFontSize(this._fontSize); - this._updateNodeSize(); - } - }, - properties: { _useOriginalSize: true, /** @@ -188,16 +183,7 @@ var Label = cc.Class({ multiline: true, tooltip: CC_DEV && 'i18n:COMPONENT.label.string', notify: function () { - if (this._sgNode) { - if (CC_EDITOR) { - if(this.overflow === cc.Label.Overflow.SHRINK) { - this.fontSize = this._userDefinedFontSize; - } - this._debouncedUpdateSgNodeString(); - } else { - this._updateSgNodeString(); - } - } + this._updateRenderData(); } }, @@ -211,9 +197,7 @@ var Label = cc.Class({ type: HorizontalAlign, tooltip: CC_DEV && 'i18n:COMPONENT.label.horizontal_align', notify: function () { - if (this._sgNode) { - this._sgNode.setHorizontalAlign( this.horizontalAlign ); - } + this._updateRenderData(); }, animatable: false }, @@ -228,16 +212,11 @@ var Label = cc.Class({ type: VerticalAlign, tooltip: CC_DEV && 'i18n:COMPONENT.label.vertical_align', notify: function () { - if (this._sgNode) { - this._sgNode.setVerticalAlign( this.verticalAlign ); - } + this._updateRenderData(); }, animatable: false }, - _actualFontSize: { - default: 40, - }, /** * !#en The actual rendering font size in shrink mode @@ -249,9 +228,6 @@ var Label = cc.Class({ animatable: false, readonly: true, get: function () { - if (this._sgNode) { - this._actualFontSize = this._sgNode.getFontSize(); - } return this._actualFontSize; } }, @@ -268,12 +244,7 @@ var Label = cc.Class({ }, set: function(value){ this._fontSize = value; - if(CC_EDITOR) { - this._userDefinedFontSize = value; - this._debouncedUpdateFontSize(); - } else { - this._updateSgNodeFontSize(); - } + this._updateRenderData(); }, tooltip: CC_DEV && 'i18n:COMPONENT.label.font_size', }, @@ -287,9 +258,7 @@ var Label = cc.Class({ default: "Arial", tooltip: CC_DEV && 'i18n:COMPONENT.label.font_family', notify: function () { - if (this._sgNode) { - this._sgNode.setFontFamily(this.fontFamily); - } + this._updateRenderData(); }, animatable: false }, @@ -302,18 +271,11 @@ var Label = cc.Class({ */ lineHeight: { get: function(){ - if (this._sgNode) { - this._lineHeight = this._sgNode.getLineHeight(); - } return this._lineHeight; }, set: function(value){ this._lineHeight = value; - - if (this._sgNode) { - this._sgNode.setLineHeight(value); - this._updateNodeSize(); - } + this._updateRenderData(); }, tooltip: CC_DEV && 'i18n:COMPONENT.label.line_height', }, @@ -327,10 +289,7 @@ var Label = cc.Class({ type: Overflow, tooltip: CC_DEV && 'i18n:COMPONENT.label.overflow', notify: function () { - if (this._sgNode) { - this._sgNode.setOverflow(this.overflow); - this._updateNodeSize(); - } + this._updateRenderData(); }, animatable: false }, @@ -343,16 +302,11 @@ var Label = cc.Class({ */ enableWrapText: { get: function(){ - if (this._sgNode) { - this._enableWrapText = this._sgNode.isWrapTextEnabled(); - } return this._enableWrapText; }, set: function(value){ this._enableWrapText = value; - if (this._sgNode) { - this._sgNode.enableWrapText(value); - } + this._updateRenderData(); }, animatable: false, tooltip: CC_DEV && 'i18n:COMPONENT.label.wrap', @@ -385,38 +339,18 @@ var Label = cc.Class({ if (value && this._isSystemFontUsed) this._isSystemFontUsed = false; - if (this._sgNode) { - if ( typeof value === 'string' ) { - cc.warnID(4000); - } - - var font = this.font; - if (font instanceof cc.BitmapFont) { - if (font.spriteFrame) { - if (!CC_JSB) { - this._sgNode.setFontAsset(font); - } else { - if (font.spriteFrame.textureLoaded()) { - this._sgNode.setFontAsset(font); - } - else { - cc.warnID(4012, font.name); - this._sgNode.setFontFamily(''); - } - } - } else { - cc.warnID(4011, font.name); - this._sgNode.setFontFamily(''); - } - } else { - this._sgNode.setFontAsset(font); - } + if ( typeof value === 'string' ) { + cc.warnID(4000); } if (value instanceof cc.BitmapFont) { this._bmFontOriginalSize = value.fontSize; } + + this._clearData(); + this._activateMaterial(); + this._updateRenderData(); }, type: cc.Font, tooltip: CC_DEV && 'i18n:COMPONENT.label.font', @@ -431,12 +365,17 @@ var Label = cc.Class({ * @property {Boolean} isSystemFontUsed */ useSystemFont: { - get: function(){ + get: function() { return this._isSystemFontUsed; }, - set: function(value){ - if(CC_EDITOR) { - if(!value && this._isSystemFontUsed && this._userDefinedFont) { + set: function(value) { + if (this._isSystemFontUsed === value) return; + + RenderData.free(this._renderData); + this._renderData = null; + + if (CC_EDITOR) { + if (!value && this._isSystemFontUsed && this._userDefinedFont) { this.font = this._userDefinedFont; this.spacingX = this._spacingX; return; @@ -446,9 +385,6 @@ var Label = cc.Class({ this._isSystemFontUsed = !!value; if (value) { this.font = null; - if (this._sgNode) { - this._sgNode.setFontFamily(this.fontFamily); - } } }, @@ -472,10 +408,7 @@ var Label = cc.Class({ }, set: function(value) { this._spacingX = value; - if (this._sgNode) { - this._sgNode.setSpacingX(this.spacingX); - this._updateNodeSize(); - } + this._updateRenderData(); } } @@ -487,103 +420,67 @@ var Label = cc.Class({ Overflow: Overflow, }, - __preload: function () { - return; - // node should be resize whenever font changed, needed only on web - if (!CC_JSB) { - this._sgNode.on('load', this._updateNodeSize, this); - } - - this._updateNodeSize(); + onEnable: function () { + this._activateMaterial(); + this.node._renderComponent = this; }, - _createSgNode: function () { - return null; + onDisable: function () { + this._clearData(); + + this._material = null; + this.node._renderComponent = null; }, - _initSgNode: function () { - return; - var font = this.font; - if (typeof font === 'string' ) { - cc.warnID(4000); - } + _clearData: function () { + RenderData.free(this._renderData); + this._renderData = null; + this._fontData = null; + }, - var sgNode; + _activateMaterial: function () { + let material; + + let font = this.font; if (font instanceof cc.BitmapFont) { - if (font.spriteFrame) { - if (CC_JSB) { - if (font.spriteFrame.textureLoaded()) { - sgNode = this._sgNode = new _ccsg.Label(this.string, JSON.stringify(font._fntConfig), font.spriteFrame); - } else { - cc.warnID(4012, font.name); - sgNode = this._sgNode = new _ccsg.Label(this.string, null, null, this._fontSize); - } - } else { - sgNode = this._sgNode = _ccsg.Label.pool.get(this.string, font); - } - } else { - cc.warnID(4011, font.name); - sgNode = this._sgNode = _ccsg.Label.pool.get(this.string); + let spriteFrame = this.font.spriteFrame; + // cannot be activated if texture not loaded yet + if (!spriteFrame.textureLoaded()) { + return; } - } else { - sgNode = this._sgNode = _ccsg.Label.pool.get(this.string, font, null, this._fontSize); + let texture = spriteFrame.getTexture(); + let url = texture.url; + material = renderer.materialUtil.get(url); + + // Get material + if (!material) { + material = new SpriteMaterial(); + material.texture = texture.getImpl(); + renderer.materialUtil.register(url, material); + } + } + else { + material = new SpriteMaterial(); + this._texture = new cc.Texture2D(); + this._canvas = document.createElement("canvas"); + this._texture.initWithElement(this._canvas); + this._context = this._canvas.getContext("2d"); + + material.texture = this._texture.getImpl(); } - if (CC_JSB) { - sgNode.retain(); + this._material = material; + }, + + _updateRenderData: function () { + let renderData = this._renderData; + if (renderData) { + renderData.vertDirty = true; + renderData.uvDirty = true; } - if (font instanceof cc.BitmapFont) { - this._bmFontOriginalSize = font.fontSize; - } - - sgNode.setVisible(false); - sgNode.setHorizontalAlign( this.horizontalAlign ); - sgNode.setVerticalAlign( this.verticalAlign ); - sgNode.setFontSize( this._fontSize ); - if (this.useSystemFont) { - sgNode.setFontFamily(this.fontFamily); - } - sgNode.setOverflow( this.overflow ); - sgNode.enableWrapText( this._enableWrapText ); - sgNode.setLineHeight(this._lineHeight); - sgNode.setString(this.string); - if (font instanceof cc.BitmapFont) { - sgNode.setSpacingX(this.spacingX); - } if (CC_EDITOR) { - this._userDefinedFontSize = this.fontSize; - this._userDefinedFont = font; - } - if (CC_EDITOR && this._useOriginalSize) { - this.node.setContentSize(sgNode.getContentSize()); - if (font instanceof cc.BitmapFont) { - this.lineHeight = sgNode.getBMFontLineHeight(); - } - this._useOriginalSize = false; - } else { - sgNode.setContentSize(this.node.getContentSize()); - } - sgNode.setColor(this.node.color); - }, - - // update node size (this will also invoke the size-changed event) - _updateNodeSize: function () { - return; - var initialized = this._sgNode && this._sgNode.parent; - if (initialized) { - if (this.overflow === Overflow.NONE || this.overflow === Overflow.RESIZE_HEIGHT) { - this.node.setContentSize(this._sgNode.getContentSize()); - } - } - }, - - onDestroy: function () { - return; - var sgNodeBeforeDestroy = this._sgNode; - if (sgNodeBeforeDestroy) { - sgNodeBeforeDestroy.removeFromParent(true); - _ccsg.Label.pool.put(sgNodeBeforeDestroy); + Label._assembler.updateRenderData(this); } } }); diff --git a/cocos2d/core/components/CCLabelOutline.js b/cocos2d/core/components/CCLabelOutline.js index 1baf226591..471873d9a7 100644 --- a/cocos2d/core/components/CCLabelOutline.js +++ b/cocos2d/core/components/CCLabelOutline.js @@ -49,6 +49,9 @@ var LabelOutline = cc.Class({ }, properties: { + _color: cc.color(255,255,255,255), + _width: 1, + /** * !#en Change the outline color * !#zh 改变描边的颜色 @@ -57,19 +60,15 @@ var LabelOutline = cc.Class({ * @example * outline.color = new cc.Color(0.5, 0.3, 0.7, 1.0);; */ - _color: cc.color(255,255,255,255), - _width: 1, color: { - get: function() { + get: function () { return this._color; }, - set:function(value) { + set: function (value) { this._color = cc.color(value); - if(this._labelSGNode) { - this._labelSGNode.setOutlineColor(cc.color(this._color)); - } } }, + /** * !#en Change the outline width * !#zh 改变描边的宽度 @@ -79,39 +78,14 @@ var LabelOutline = cc.Class({ * outline.width = 3; */ width: { - get: function() { + get: function () { return this._width; }, - set: function(value) { + set: function (value) { this._width = value; - if(this._labelSGNode) { - this._labelSGNode.setOutlineWidth(value); - this._labelSGNode.setMargin(value); - } } - }, - }, - - onEnable: function () { - var label = this.node.getComponent('cc.Label'); - var sgNode = this._labelSGNode = label && label._sgNode; - if(this._labelSGNode) { - sgNode.setOutlined(true); - sgNode.setOutlineColor(cc.color(this._color)); - sgNode.setOutlineWidth(this._width); - sgNode.setMargin(this._width); } - }, - - onDisable: function () { - if(this._labelSGNode) { - this._labelSGNode.setOutlined(false); - this._labelSGNode.setMargin(0); - } - - this._labelSGNode = null; - }, - + } }); cc.LabelOutline = module.exports = LabelOutline; diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js deleted file mode 100644 index 7f0acc8818..0000000000 --- a/cocos2d/core/label/CCSGLabel.js +++ /dev/null @@ -1,1341 +0,0 @@ -/*global cc */ - -/**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -require('./CCTextUtils'); -var EventTarget = require("../event/event-target"); -var JS = require("../platform/js"); - - -var FontLetterDefinition = function() { - this._u = 0; - this._v = 0; - this._width = 0; - this._height = 0; - this._offsetX = 0; - this._offsetY = 0; - this._textureID = 0; - this._validDefinition = false; - this._xAdvance = 0; -}; - -cc.FontAtlas = function(fntConfig) { - this._lineHeight = fntConfig.commonHeight; - this._fontSize = fntConfig.fontSize; - this._letterDefinitions = {}; - this._fntConfig = fntConfig; -}; - -cc.FontAtlas.prototype = { - constructor: cc.FontAtlas, - setFontSize: function(fontSize) { - this._fontSize = fontSize; - }, - getOriginalFontSize: function() { - return this._fntConfig.fontSize; - }, - addLetterDefinitions: function(letter, letterDefinition) { - this._letterDefinitions[letter] = letterDefinition; - }, - cloneLetterDefinition: function() { - var copyLetterDefinitions = {}; - for (var key in this._letterDefinitions) { - var value = new FontLetterDefinition(); - cc.js.mixin(value, this._letterDefinitions[key]); - copyLetterDefinitions[key] = value; - } - return copyLetterDefinitions; - }, - assignLetterDefinitions: function(letterDefinition) { - for (var key in this._letterDefinitions) { - var newValue = letterDefinition[key]; - var oldValue = this._letterDefinitions[key]; - cc.js.mixin(oldValue, newValue); - } - }, - scaleFontLetterDefinition: function(scaleFactor) { - for (var fontDefinition in this._letterDefinitions) { - var letterDefinitions = this._letterDefinitions[fontDefinition]; - letterDefinitions._width *= scaleFactor; - letterDefinitions._height *= scaleFactor; - letterDefinitions._offsetX *= scaleFactor; - letterDefinitions._offsetY *= scaleFactor; - letterDefinitions._xAdvance *= scaleFactor; - } - }, - - getLetterDefinitionForChar: function(char) { - var hasKey = this._letterDefinitions.hasOwnProperty(char.charCodeAt(0)); - var letterDefinition; - if (hasKey) { - letterDefinition = this._letterDefinitions[char.charCodeAt(0)]; - } else { - letterDefinition = null; - } - return letterDefinition; - } -}; - -var LetterInfo = function() { - this._char = ''; - this._valid = true; - this._positionX = 0; - this._positionY = 0; - this._lineIndex = 0; -}; - -_ccsg.Label = _ccsg.Node.extend({ - _hAlign: cc.TextAlignment.LEFT, //0 left, 1 center, 2 right - _vAlign: cc.VerticalTextAlignment.TOP, //0 bottom,1 center, 2 top - _string: "", - _fontSize: 40, - _drawFontsize: 40, - _overFlow: 0, //see _ccsg.Label.Overflow - _isWrapText: true, - _spacingX: 0, - - _blendFunc: null, - _labelType: 0, //0 is ttf, 1 is bmfont. - _fontHandle: "", //a ttf font name or a bmfont file path. - _lineSpacing: 0, - - _maxLineWidth: 0, - _labelDimensions: cc.size(0, 0), - _labelWidth: 0, - _labelHeight: 0, - - _lineHeight: 40, - _outlined: false, - _outlineColor: null, - _outlineWidth: 1, - _gradientEnabled: false, - _gradientStartColor: cc.color(255, 255, 255, 255), - _gradientEndColor: cc.color(255, 255, 255, 255), - _gradientDirection: 0, - _className: "Label", - //used for left and right margin - _margin : 0, - //bold,italic, underline - _isBold: false, - _isItalic: false, - _isUnderline: false, - _fontAsset: null, - - //fontHandle it is a system font name, ttf file path or bmfont file path. - ctor: function(string, fontAsset) { - EventTarget.call(this); - var isAsset = fontAsset instanceof cc.Font; - var fontHandle = isAsset ? fontAsset.rawUrl : ''; - - this._fontHandle = fontHandle; - if (typeof string !== 'string') { - string = '' + string; - } - - this._string = string; - - _ccsg.Node.prototype.ctor.call(this); - this.setAnchorPoint(0.5, 0.5); - _ccsg.Node.prototype.setContentSize.call(this, 128, 128); - this._blendFunc = cc.BlendFunc._alphaNonPremultiplied(); - - this._imageOffset = cc.p(0, 0); - this._numberOfLines = 0; - this._lettersInfo = []; - this._linesWidth = []; - this._linesOffsetX = []; - this._horizontalKernings = []; - this._reusedRect = cc.rect(0, 0, 0, 0); - if (isAsset) { - this.setFontAsset(fontAsset); - } else { - this.setFontFamily(fontHandle); - } - this.setString(this._string); - }, - - _resetBMFont: function() { - this._imageOffset.x = this._imageOffset.y = 0; - this._cascadeColorEnabled = true; - this._cascadeOpacityEnabled = true; - this._fontAtlas = null; - this._config = null; - this._numberOfLines = 0; - this._lettersInfo.length = 0; - this._linesWidth.length = 0; - this._linesOffsetX.length = 0; - this._textDesiredHeight = 0; - this._letterOffsetY = 0; - this._tailoredTopY = 0; - this._tailoredBottomY = 0; - this._bmfontScale = 1.0; - this._horizontalKernings.length = 0; - this._lineBreakWithoutSpaces = false; - - this._reusedRect.x = this._reusedRect.y = this._reusedRect.width = this._reusedRect.height = 0; - this._textureLoaded = false; - - if (this._spriteBatchNode) { - this.removeChild(this._spriteBatchNode); - this._spriteBatchNode = null; - } - }, - - setHorizontalAlign: function(align) { - if (this._hAlign === align) return; - - this._hAlign = align; - this._notifyLabelSkinDirty(); - }, - - getHorizontalAlign: function() { - return this._hAlign; - }, - - setVerticalAlign: function(align) { - if (this._vAlign === align) return; - - this._vAlign = align; - this._notifyLabelSkinDirty(); - }, - - getVerticalAlign: function() { - return this._vAlign; - }, - - setString: function(string) { - //convert param to string - if (typeof string !== 'string') { - string = '' + string; - } - - if (this._string === string) return; - - this._string = string; - this._notifyLabelSkinDirty(); - }, - - setMargin: function(value) { - if(this._margin === value) return; - - this._margin = value; - this._notifyLabelSkinDirty(); - }, - - getString: function() { - return this._string; - }, - getStringLength: function() { - return this._string.length; - }, - - enableWrapText: function(enabled) { - if (this._isWrapText === enabled) return; - - //when label is in resize mode, wrap is disabled. - if (this._overFlow === _ccsg.Label.Overflow.RESIZE_HEIGHT || - this._overFlow === _ccsg.Label.Overflow.NONE) { - return; - } - this._isWrapText = enabled; - this._rescaleWithOriginalFontSize(); - - this._notifyLabelSkinDirty(); - }, - - enableItalics: function (enabled) { - this._isItalic = enabled; - if(enabled) { - this.setSkewX(12); - } else { - this.setSkewX(0); - } - }, - - enableBold: function (enabled) { - if(this._isBold === enabled) return; - - this._isBold = enabled; - this._notifyLabelSkinDirty(); - }, - - enableUnderline: function (enabled) { - if(this._isUnderline === enabled) return; - - this._isUnderline = enabled; - this._notifyLabelSkinDirty(); - }, - - isWrapTextEnabled: function() { - return this._isWrapText; - }, - getFontName: function() { - return this._fontHandle; - }, - setFontSize: function(fntSize) { - if(this._fontSize === fntSize) return; - - this._fontSize = fntSize; - this._drawFontsize = fntSize; - this._notifyLabelSkinDirty(); - }, - - getFontSize: function() { - return this._fontSize; - }, - - isOutlined: function() { - return this._outlined; - }, - - setOutlined: function(value) { - if(this._outlined === value) return; - - this._outlined = !!value; - this._notifyLabelSkinDirty(); - }, - - setFillColorGradientEnabled: function(value) { - if(this._gradientEnabled === value) return; - - this._gradientEnabled = !!value; - this._notifyLabelSkinDirty(); - }, - getFillColorGradientEnabled: function () { - return this._gradientEnabled; - }, - - setGradientStartColor: function (value) { - if(this._gradientStartColor === value) return; - this._gradientStartColor = value; - this._notifyLabelSkinDirty(); - }, - - getGradientStartColor: function () { - return this._gradientStartColor; - }, - - setGradientEndColor: function (value) { - if(this._gradientEndColor === value) return; - this._gradientEndColor = value; - this._notifyLabelSkinDirty(); - }, - - getGradientEndColor: function () { - return this._gradientEndColor; - }, - - setFillColorGradientDirection: function (direction) { - this._gradientDirection = direction; - this._notifyLabelSkinDirty(); - }, - - getFillColorGradientDirection: function () { - return this._gradientDirection; - }, - - getOutlineColor: function() { - return this._outlineColor; - }, - - setOutlineColor: function(value) { - if(this._outlineColor === value) return; - - this._outlineColor = cc.color(value); - this._notifyLabelSkinDirty(); - }, - - setOutlineWidth: function(value) { - if(this._outlineWidth === value) return; - - this._outlineWidth = value; - this._notifyLabelSkinDirty(); - }, - - getOutlineWidth: function() { - return this._outlineWidth; - }, - - _updateWrapText: function(overflow){ - if ( overflow === _ccsg.Label.Overflow.RESIZE_HEIGHT) { - this._isWrapText = true; - } - - if (overflow === _ccsg.Label.Overflow.NONE) { - this._isWrapText = false; - } - }, - - - _setOverflowBMFont: function () { - if (this._labelType === _ccsg.Label.Type.BMFont) { - - if ( this._overFlow === _ccsg.Label.Overflow.RESIZE_HEIGHT) { - this._setDimensions(this._labelDimensions.width, 0); - } - - if (this._overFlow === _ccsg.Label.Overflow.NONE) { - this._setDimensions(0, 0); - } - - this._rescaleWithOriginalFontSize(); - } - }, - - setOverflow: function(overflow) { - if (this._overFlow === overflow) return; - - this._overFlow = overflow; - - this._updateWrapText(this._overFlow); - - this._setOverflowBMFont(); - - this._notifyLabelSkinDirty(); - }, - - getOverflow: function() { - return this._overFlow; - }, - - setSpacingX: function(spacing) { - if (this._spacingX === spacing) return; - this._spacingX = spacing; - this._notifyLabelSkinDirty(); - }, - - setLineHeight: function(lineHeight) { - if (this._lineHeight === lineHeight) return; - - this._lineHeight = lineHeight; - this._notifyLabelSkinDirty(); - }, - setLineBreakWithoutSpace: function(lineBreakFlag) { - if (this._lineBreakWithoutSpaces === lineBreakFlag) return; - - this._lineBreakWithoutSpaces = lineBreakFlag; - this._notifyLabelSkinDirty(); - }, - getSpacingX: function() { - return this._spacingX; - }, - - getLineHeight: function() { - return this._lineHeight; - }, - - getBMFontLineHeight : function() { - if(this._fontAtlas) { - return this._fontAtlas._lineHeight; - } - }, - - setFontFamily: function (fontFamily) { - this._resetBMFont(); - this._fontHandle = fontFamily || "Arial"; - this._labelType = _ccsg.Label.Type.SystemFont; - this._blendFunc = cc.BlendFunc._alphaPremultiplied(); - this._renderCmd._needDraw = true; - this._notifyLabelSkinDirty(); - this.emit('load'); - }, - - setFontAsset: function(fontAsset) { - this._fontAsset = fontAsset; - var isAsset = fontAsset instanceof cc.Font; - if (!isAsset) { - this.setFontFamily(''); - return; - } - var fontHandle = isAsset ? fontAsset.rawUrl : ''; - var extName = cc.path.extname(fontHandle); - - this._resetBMFont(); - - if (extName === ".ttf") { - this._labelType = _ccsg.Label.Type.TTF; - this._blendFunc = cc.BlendFunc._alphaPremultiplied(); - this._renderCmd._needDraw = true; - this._fontHandle = this._loadTTFFont(fontHandle); - } else if (fontAsset.spriteFrame) { - //todo add bmfont here - this._labelType = _ccsg.Label.Type.BMFont; - this._blendFunc = cc.BlendFunc._alphaNonPremultiplied(); - this._renderCmd._needDraw = false; - this._initBMFontWithString(this._string, fontAsset); - } - this._notifyLabelSkinDirty(); - }, - - _loadTTFFont: function(fontHandle) { - var self = this; - - var fontFamilyName = cc.CustomFontLoader._getFontFamily(fontHandle); - var callback = function () { - self._notifyLabelSkinDirty(); - self.emit('load'); - }; - cc.CustomFontLoader.loadTTF(fontHandle, callback); - - return fontFamilyName; - }, - - setContentSize: function(size, height) { - if (this._overFlow === _ccsg.Label.Overflow.NONE) { - return; - } - - this._setDimensions(size, height); - }, - - setBlendFunc: function(src, dst) { - var locBlendFunc = this._blendFunc; - if (dst === undefined) { - locBlendFunc.src = src.src; - locBlendFunc.dst = src.dst; - } else { - locBlendFunc.src = src; - locBlendFunc.dst = dst; - } - }, - - - getBlendFunc: function() { - return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst); - }, - - _setupBMFontOverflowMetrics: function(newWidth, newHeight) { - if (this._overFlow === _ccsg.Label.Overflow.RESIZE_HEIGHT) { - newHeight = 0; - } - - if (this._overFlow === _ccsg.Label.Overflow.NONE) { - newWidth = 0; - newHeight = 0; - } - - this._labelWidth = newWidth; - this._labelHeight = newHeight; - this._labelDimensions.width = newWidth; - this._labelDimensions.height = newHeight; - this._maxLineWidth = newWidth; - }, - - _updateLabel: function () { - if (this._labelType === _ccsg.Label.Type.BMFont) { - var contentSize = this._contentSize; - var newWidth = contentSize.width; - var newHeight = contentSize.height; - this._setupBMFontOverflowMetrics(newWidth, newHeight); - - this._updateContent(); - this.setColor(this.color); - } else if (this._labelType === _ccsg.Label.Type.TTF - || this._labelType === _ccsg.Label.Type.SystemFont) { - this._renderCmd._bakeLabel(); - } - }, - - _notifyLabelSkinDirty: function() { - if (CC_EDITOR) { - this._updateLabel(); - } else { - this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.textDirty - |_ccsg.Node._dirtyFlags.contentDirty); - } - }, - _createRenderCmd: function() { - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - return new _ccsg.Label.WebGLRenderCmd(this); - } else { - return new _ccsg.Label.CanvasRenderCmd(this); - } - }, - - getContentSize: function() { - var locFlag = this._renderCmd._dirtyFlag; - if (locFlag & _ccsg.Node._dirtyFlags.textDirty) { - this._updateLabel(); - this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; - } - return _ccsg.Node.prototype.getContentSize.call(this); - }, - _getWidth: function () { - var locFlag = this._renderCmd._dirtyFlag; - if (locFlag & _ccsg.Node._dirtyFlags.textDirty) { - this._updateLabel(); - this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; - } - return _ccsg.Node.prototype._getWidth.call(this); - }, - _getHeight: function () { - var locFlag = this._renderCmd._dirtyFlag; - if (locFlag & _ccsg.Node._dirtyFlags.textDirty) { - this._updateLabel(); - this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; - } - return _ccsg.Node.prototype._getHeight.call(this); - }, - _alignText: function() { - var ret = true; - - do { - if (!this._spriteBatchNode) return true; - - - this._textDesiredHeight = 0; - this._linesWidth = []; - if (!this._lineBreakWithoutSpaces) { - this._multilineTextWrapByWord(); - } else { - this._multilineTextWrapByChar(); - } - - this._computeAlignmentOffset(); - - //shrink - if (this._overFlow === _ccsg.Label.Overflow.SHRINK) { - var fontSize = this.getFontSize(); - - if (fontSize > 0 && this._isVerticalClamp()) { - this._shrinkLabelToContentSize(this._isVerticalClamp.bind(this)); - } - } - - if (!this._updateQuads()) { - ret = false; - if (this._overFlow === _ccsg.Label.Overflow.SHRINK) { - this._shrinkLabelToContentSize(this._isHorizontalClamp.bind(this)); - } - break; - } - } while (0); - - return ret; - }, - - _isHorizontalClamped : function(px, lineIndex){ - var wordWidth = this._linesWidth[lineIndex]; - var letterOverClamp = (px > this._contentSize.width || px < 0); - - if(!this._isWrapText){ - return letterOverClamp; - }else{ - return (wordWidth > this._contentSize.width && letterOverClamp); - } - }, - - _updateQuads: function() { - var ret = true; - - this._spriteBatchNode.removeAllChildren(); - for (var ctr = 0; ctr < this._string.length; ++ctr) { - if (this._lettersInfo[ctr]._valid) { - var letterDef = this._fontAtlas._letterDefinitions[this._lettersInfo[ctr]._char]; - - this._reusedRect.height = letterDef._height; - this._reusedRect.width = letterDef._width; - this._reusedRect.x = letterDef._u; - this._reusedRect.y = letterDef._v; - - var py = this._lettersInfo[ctr]._positionY + this._letterOffsetY; - - if (this._labelHeight > 0) { - if (py > this._tailoredTopY) { - var clipTop = py - this._tailoredTopY; - this._reusedRect.y += clipTop; - this._reusedRect.height -= clipTop; - py = py - clipTop; - } - - if (py - letterDef._height * this._bmfontScale < this._tailoredBottomY) { - this._reusedRect.height = (py < this._tailoredBottomY) ? 0 : (py - this._tailoredBottomY); - } - } - - var lineIndex = this._lettersInfo[ctr]._lineIndex; - var px = this._lettersInfo[ctr]._positionX + letterDef._width / 2 * this._bmfontScale + this._linesOffsetX[lineIndex]; - - - if (this._labelWidth > 0) { - if (this._isHorizontalClamped(px, lineIndex)) { - if (this._overFlow === _ccsg.Label.Overflow.CLAMP) { - this._reusedRect.width = 0; - } else if (this._overFlow === _ccsg.Label.Overflow.SHRINK) { - if (this._contentSize.width > letterDef._width) { - ret = false; - break; - } else { - this._reusedRect.width = 0; - } - } - } - } - - - if (this._reusedRect.height > 0 && this._reusedRect.width > 0) { - var fontChar = this.getChildByTag(ctr); - var locTexture = this._spriteBatchNode._texture; - var spriteFrame = this._spriteFrame; - - var isRotated = this._spriteFrame.isRotated(); - - var originalSize = spriteFrame._originalSize; - var rect = spriteFrame._rect; - var offset = spriteFrame._offset; - var trimmedLeft = offset.x + (originalSize.width - rect.width) / 2; - var trimmedTop = offset.y - (originalSize.height - rect.height) / 2; - - - if(!isRotated) { - this._reusedRect.x += (rect.x - trimmedLeft); - this._reusedRect.y += (rect.y + trimmedTop); - } else { - var originalX = this._reusedRect.x; - this._reusedRect.x = rect.x + rect.height - this._reusedRect.y - this._reusedRect.height - trimmedTop; - this._reusedRect.y = originalX + rect.y - trimmedLeft; - if (this._reusedRect.y < 0) { - this._reusedRect.height = this._reusedRect.height + trimmedTop; - } - } - - if (!fontChar) { - fontChar = new _ccsg.Sprite(); - fontChar.initWithTexture(locTexture, this._reusedRect, isRotated); - fontChar.setAnchorPoint(cc.p(0, 1)); - } else { - fontChar.setTextureRect(this._reusedRect, isRotated); - } - - - var letterPositionX = this._lettersInfo[ctr]._positionX + this._linesOffsetX[this._lettersInfo[ctr]._lineIndex]; - fontChar.setPosition(letterPositionX, py); - - this._updateLetterSpriteScale(fontChar); - - this._spriteBatchNode.addChild(fontChar); - - } - } - } - - return ret; - }, - - _updateLetterSpriteScale: function(sprite) { - if (this._labelType === _ccsg.Label.Type.BMFont && this._fontSize > 0) { - sprite.setScale(this._bmfontScale); - } - }, - - _recordPlaceholderInfo: function(letterIndex, char) { - if (letterIndex >= this._lettersInfo.length) { - var tmpInfo = new LetterInfo(); - this._lettersInfo.push(tmpInfo); - } - - this._lettersInfo[letterIndex]._char = char; - this._lettersInfo[letterIndex]._valid = false; - }, - - _recordLetterInfo: function(letterPosition, character, letterIndex, lineIndex) { - if (letterIndex >= this._lettersInfo.length) { - var tmpInfo = new LetterInfo(); - this._lettersInfo.push(tmpInfo); - } - character = character.charCodeAt(0); - - this._lettersInfo[letterIndex]._lineIndex = lineIndex; - this._lettersInfo[letterIndex]._char = character; - this._lettersInfo[letterIndex]._valid = this._fontAtlas._letterDefinitions[character]._validDefinition; - this._lettersInfo[letterIndex]._positionX = letterPosition.x; - this._lettersInfo[letterIndex]._positionY = letterPosition.y; - }, - - _setDimensions: function(size, height) { - var newWidth = (typeof size.width === 'number') ? size.width : size; - var newHeight = (typeof size.height === 'number') ? size.height : height; - - var oldSize = this.getContentSize(); - _ccsg.Node.prototype.setContentSize.call(this, size, height); - - if (newHeight !== oldSize.height || newWidth !== oldSize.width) { - - this._setupBMFontOverflowMetrics(newWidth, newHeight); - - if (this._drawFontsize > 0) { - this._restoreFontSize(); - } - - this._notifyLabelSkinDirty(); - } - }, - - _restoreFontSize: function() { - this._fontSize = this._drawFontsize; - }, - - _multilineTextWrap: function(nextTokenFunc) { - var textLen = this.getStringLength(); - var lineIndex = 0; - var nextTokenX = 0; - var nextTokenY = 0; - var longestLine = 0; - var letterRight = 0; - - var lineSpacing = this._lineSpacing; - var highestY = 0; - var lowestY = 0; - var letterDef = null; - var letterPosition = cc.p(0, 0); - - this._updateBMFontScale(); - - for (var index = 0; index < textLen;) { - var character = this._string.charAt(index); - if (character === "\n") { - this._linesWidth.push(letterRight); - letterRight = 0; - lineIndex++; - nextTokenX = 0; - nextTokenY -= this._lineHeight * this._bmfontScale + lineSpacing; - this._recordPlaceholderInfo(index, character); - index++; - continue; - } - - var tokenLen = nextTokenFunc(this._string, index, textLen); - var tokenHighestY = highestY; - var tokenLowestY = lowestY; - var tokenRight = letterRight; - var nextLetterX = nextTokenX; - var newLine = false; - - for (var tmp = 0; tmp < tokenLen; ++tmp) { - var letterIndex = index + tmp; - character = this._string.charAt(letterIndex); - if (character === "\r") { - this._recordPlaceholderInfo(letterIndex, character); - continue; - } - letterDef = this._fontAtlas.getLetterDefinitionForChar(character); - if (!letterDef) { - this._recordPlaceholderInfo(letterIndex, character); - console.log("Can't find letter definition in texture atlas " + this._config.atlasName + " for letter:" + character); - continue; - } - - var letterX = nextLetterX + letterDef._offsetX * this._bmfontScale; - - if (this._isWrapText - && this._maxLineWidth > 0 - && nextTokenX > 0 - && letterX + letterDef._width * this._bmfontScale > this._maxLineWidth - && !cc.TextUtils.isUnicodeSpace(character)) { - this._linesWidth.push(letterRight); - letterRight = 0; - lineIndex++; - nextTokenX = 0; - nextTokenY -= (this._lineHeight * this._bmfontScale + lineSpacing); - newLine = true; - break; - } else { - letterPosition.x = letterX; - } - - letterPosition.y = nextTokenY - letterDef._offsetY * this._bmfontScale; - this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex); - - if (letterIndex + 1 < this._horizontalKernings.length && letterIndex < textLen - 1) { - nextLetterX += this._horizontalKernings[letterIndex + 1]; - } - - nextLetterX += letterDef._xAdvance * this._bmfontScale + this._spacingX; - - tokenRight = letterPosition.x + letterDef._width * this._bmfontScale; - - if (tokenHighestY < letterPosition.y) { - tokenHighestY = letterPosition.y; - } - - if (tokenLowestY > letterPosition.y - letterDef._height * this._bmfontScale) { - tokenLowestY = letterPosition.y - letterDef._height * this._bmfontScale; - } - - } //end of for loop - - if (newLine) continue; - - nextTokenX = nextLetterX; - letterRight = tokenRight; - - if (highestY < tokenHighestY) { - highestY = tokenHighestY; - } - if (lowestY > tokenLowestY) { - lowestY = tokenLowestY; - } - if (longestLine < letterRight) { - longestLine = letterRight; - } - - index += tokenLen; - } //end of for loop - - this._linesWidth.push(letterRight); - - this._numberOfLines = lineIndex + 1; - this._textDesiredHeight = this._numberOfLines * this._lineHeight * this._bmfontScale; - if (this._numberOfLines > 1) { - this._textDesiredHeight += (this._numberOfLines - 1) * this._lineSpacing; - } - - var contentSize = cc.size(this._labelWidth, this._labelHeight); - if (this._labelWidth <= 0) { - contentSize.width = parseFloat(longestLine.toFixed(2)); - } - if (this._labelHeight <= 0) { - contentSize.height = parseFloat(this._textDesiredHeight.toFixed(2)); - } - - _ccsg.Node.prototype.setContentSize.call(this, contentSize); - - this._tailoredTopY = contentSize.height; - this._tailoredBottomY = 0; - if (highestY > 0) { - this._tailoredTopY = contentSize.height + highestY; - } - if (lowestY < -this._textDesiredHeight) { - this._tailoredBottomY = this._textDesiredHeight + lowestY; - } - - return true; - }, - - _multilineTextWrapByWord: function() { - return this._multilineTextWrap(this._getFirstWordLen.bind(this)); - }, - - _multilineTextWrapByChar: function() { - return this._multilineTextWrap(this._getFirstCharLen.bind(this)); - }, - - _isVerticalClamp: function() { - if (this._textDesiredHeight > this._contentSize.height) { - return true; - } else { - return false; - } - }, - - _isHorizontalClamp: function() { - var letterClamp = false; - - for (var ctr = 0; ctr < this.getStringLength(); ++ctr) { - if (this._lettersInfo[ctr]._valid) { - var letterDef = this._fontAtlas._letterDefinitions[this._lettersInfo[ctr]._char]; - - var px = this._lettersInfo[ctr]._positionX + letterDef._width / 2 * this._bmfontScale; - var lineIndex = this._lettersInfo[ctr]._lineIndex; - if (this._labelWidth > 0) { - if (!this._isWrapText) { - if(px > this._contentSize.width){ - letterClamp = true; - break; - } - }else{ - var wordWidth = this._linesWidth[lineIndex]; - if(wordWidth > this._contentSize.width && (px > this._contentSize.width || px < 0)){ - letterClamp = true; - break; - } - } - } - } - } - - return letterClamp; - }, - - _shrinkLabelToContentSize: function(lambda) { - var fontSize = this.getFontSize(); - - var i = 0; - var tempLetterDefinition = this._fontAtlas.cloneLetterDefinition(); - var originalLineHeight = this._lineHeight; - var flag = true; - - while (lambda()) { - ++i; - - var newFontSize = fontSize - i; - flag = false; - if (newFontSize <= 0) { - break; - } - - var scale = newFontSize / fontSize; - this._fontAtlas.assignLetterDefinitions(tempLetterDefinition); - this._fontAtlas.scaleFontLetterDefinition(scale); - this._lineHeight = originalLineHeight * scale; - if (!this._lineBreakWithoutSpaces) { - this._multilineTextWrapByWord(); - } else { - this._multilineTextWrapByChar(); - } - this._computeAlignmentOffset(); - } - - this._lineHeight = originalLineHeight; - this._fontAtlas.assignLetterDefinitions(tempLetterDefinition); - - if (!flag) { - if (fontSize - i >= 0) { - this._scaleFontSizeDown(fontSize - i); - } - } - }, - - _scaleFontSizeDown: function(fontSize) { - var shouldUpdateContent = true; - if (this._labelType === _ccsg.Label.Type.BMFont) { - if (!fontSize) { - fontSize = 0.1; - shouldUpdateContent = false; - } - this._fontSize = fontSize; - - if (shouldUpdateContent) { - this._updateContent(); - } - } - }, - - _updateContent: function() { - if (this._fontAtlas) { - this._computeHorizontalKerningForText(this._string); - this._alignText(); - } - }, - - - _computeAlignmentOffset: function() { - this._linesOffsetX = []; - switch (this._hAlign) { - case cc.TextAlignment.LEFT: - for (var i = 0; i < this._numberOfLines; ++i) { - this._linesOffsetX.push(0); - } - break; - case cc.TextAlignment.CENTER: - this._linesWidth.forEach(function(lineWidth) { - this._linesOffsetX.push((this._contentSize.width - lineWidth) / 2); - }.bind(this)); - break; - case cc.TextAlignment.RIGHT: - this._linesWidth.forEach(function(lineWidth) { - this._linesOffsetX.push(this._contentSize.width - lineWidth); - }.bind(this)); - break; - default: - break; - } - - switch (this._vAlign) { - case cc.VerticalTextAlignment.TOP: - this._letterOffsetY = this._contentSize.height; - break; - case cc.VerticalTextAlignment.CENTER: - this._letterOffsetY = (this._contentSize.height + this._textDesiredHeight) / 2; - break; - case cc.VerticalTextAlignment.BOTTOM: - this._letterOffsetY = this._textDesiredHeight; - break; - default: - break; - } - }, - - _getFirstCharLen: function() { - return 1; - }, - - _getFirstWordLen: function(text, startIndex, textLen) { - var character = text.charAt(startIndex); - if (cc.TextUtils.isUnicodeCJK(character) - || character === "\n" - || cc.TextUtils.isUnicodeSpace(character)) { - return 1; - } - - var len = 1; - letterDef = this._fontAtlas.getLetterDefinitionForChar(character); - if (!letterDef) { - return len; - } - var nextLetterX = letterDef._xAdvance * this._bmfontScale + this._spacingX; - var letterDef; - var letterX; - for (var index = startIndex + 1; index < textLen; ++index) { - character = text.charAt(index); - - letterDef = this._fontAtlas.getLetterDefinitionForChar(character); - if (!letterDef) { - break; - } - letterX = nextLetterX + letterDef._offsetX * this._bmfontScale; - - if(letterX + letterDef._width * this._bmfontScale > this._maxLineWidth - && !cc.TextUtils.isUnicodeSpace(character) - && this._maxLineWidth > 0) { - return len; - } - nextLetterX += letterDef._xAdvance * this._bmfontScale + this._spacingX; - if (character === "\n" - || cc.TextUtils.isUnicodeSpace(character) - || cc.TextUtils.isUnicodeCJK(character)) { - break; - } - len++; - } - - return len; - }, - - _updateBMFontScale: function() { - if (this._labelType === _ccsg.Label.Type.BMFont) { - var originalFontSize = this._fontAtlas._fontSize; - this._bmfontScale = this._fontSize / originalFontSize; - } else { - this._bmfontScale = 1; - } - - }, - - _initBMFontWithString: function(str, fontAsset) { - var self = this; - if (self._config) { - cc.logID(4002); - return false; - } - this._string = str; - this._setBMFontFile(fontAsset); - }, - - _createSpriteBatchNode: function(texture) { - - this._spriteBatchNode = new cc.SpriteBatchNode(texture, this._string.length); - this._spriteBatchNode.setCascadeColorEnabled(true); - this._spriteBatchNode.setCascadeOpacityEnabled(true); - this.addChild(this._spriteBatchNode); - - this._updateContent(); - this.setColor(this.color); - }, - //this method is used as createFontAtlas - _createFontChars: function() { - if (!this._config) { - return; - } - - this._fontAtlas = new cc.FontAtlas(this._config); - - if(!this._lineHeight){ - this._lineHeight = this._fontAtlas._lineHeight; - } - - var locCfg = this._config; - var locFontDict = locCfg.fontDefDictionary; - - for (var fontDef in locFontDict) { - var letterDefinition = new FontLetterDefinition(); - - var tempRect = locFontDict[fontDef].rect; - - letterDefinition._offsetX = locFontDict[fontDef].xOffset; - letterDefinition._offsetY = locFontDict[fontDef].yOffset; - letterDefinition._width = tempRect.width; - letterDefinition._height = tempRect.height; - letterDefinition._u = tempRect.x + this._imageOffset.x; - letterDefinition._v = tempRect.y + this._imageOffset.y; - //FIXME: only one texture supported for now - letterDefinition._textureID = 0; - letterDefinition._validDefinition = true; - letterDefinition._xAdvance = locFontDict[fontDef].xAdvance; - - this._fontAtlas.addLetterDefinitions(fontDef, letterDefinition); - } - }, - - _rescaleWithOriginalFontSize: function() { - var renderingFontSize = this.getFontSize(); - if (this._drawFontsize - renderingFontSize >= 1 && this._overFlow === _ccsg.Label.Overflow.SHRINK) { - if(this._labelType === _ccsg.Label.Type.BMFont) { - this._scaleFontSizeDown(this._drawFontsize); - } else { - this._fontSize = this._drawFontsize; - } - } - }, - - _computeHorizontalKerningForText: function() { - var stringLen = this.getStringLength(); - var locKerningDict = this._config.kerningDict; - - var prev = -1; - for (var i = 0; i < stringLen; ++i) { - var key = this._string.charCodeAt(i); - var kerningAmount = locKerningDict[(prev << 16) | (key & 0xffff)] || 0; - if (i < stringLen - 1) { - this._horizontalKernings[i] = kerningAmount; - } else { - this._horizontalKernings[i] = 0; - } - prev = key; - } - }, - - _setBMFontFile: function(fontAsset) { - if (fontAsset) { - if (this._labelType === _ccsg.Label.Type.BMFont) { - var self = this; - this._resetBMFont(); - - var fntConfig = this._fontAsset._fntConfig; - if (fntConfig) { - self._config = fntConfig; - } else { - cc.warn('Invalid BMFont Assets!'); - } - var spriteFrame = fontAsset.spriteFrame; - self._createFontChars(); - self._spriteFrame = spriteFrame; - - var createLabelSprites = function () { - var texture = spriteFrame.getTexture(); - self._textureLoaded = texture.loaded; - self._createSpriteBatchNode(texture); - self.emit("load"); - }; - - if (spriteFrame.textureLoaded()) { - createLabelSprites(); - } else { - spriteFrame.once('load', createLabelSprites); - spriteFrame.ensureLoadTexture(); - } - } - } - } -}); - -_ccsg.Label.pool = new JS.Pool(function (label) { - if (CC_EDITOR || !(label instanceof _ccsg.Label)) { - return false; - } - label._string = ""; - label._fontAsset = null; - label._fontHandle = ""; - label._labelType = 0; - label._resetBMFont(); - label._renderCmd._labelCanvas.width = 1; - label._renderCmd._labelCanvas.height = 1; - if (CC_DEV) { - cc.assert(!label._parent, 'Recycling label\'s parent should be null!'); - } - label._updateLabel(); - return true; -}, 20); - -_ccsg.Label.pool.get = function (string, fontAsset) { - var label = this._get(); - if (label) { - var isAsset = fontAsset instanceof cc.Font; - var fontHandle = isAsset ? fontAsset.rawUrl : ''; - label._fontHandle = fontHandle; - if (typeof string !== 'string') { - string = '' + string; - } - label._string = string; - - label._position.x = 0; - label._position.y = 0; - label.setAnchorPoint(0.5, 0.5); - _ccsg.Node.prototype.setContentSize.call(label, 128, 128); - - if (isAsset) { - label.setFontAsset(fontAsset); - } else { - label.setFontFamily("Arial"); - } - - label.setString(string); - label.setHorizontalAlign(cc.TextAlignment.LEFT); - label.setVerticalAlign(cc.VerticalTextAlignment.TOP); - label.setFontSize(40); - label.setOverflow(0); - label.enableWrapText(true); - label.setVisible(true); - label.setLineHeight(40); - label.setOutlined(false); - label.enableBold(false); - label.enableItalics(false); - label.enableUnderline(false); - - return label; - } - else { - return new _ccsg.Label(string || "", fontAsset); - } -}; - - -var _p = _ccsg.Label.prototype; -cc.js.addon(_p, EventTarget.prototype); - -_ccsg.Label.Type = cc.Enum({ - TTF: 0, - BMFont: 1, - SystemFont: 2 -}); -_ccsg.Label.Overflow = cc.Enum({ - NONE: 0, - CLAMP: 1, - SHRINK: 2, - RESIZE_HEIGHT: 3 -}); - - -// fireball#2856 - -var labelPro = _ccsg.Label.prototype; -Object.defineProperty(labelPro, 'width', { - get: labelPro._getWidth, - set: _ccsg.Node.prototype._setWidth -}); - -Object.defineProperty(labelPro, 'height', { - get: labelPro._getHeight, - set: _ccsg.Node.prototype._setHeight -}); diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js deleted file mode 100644 index ec628bf1db..0000000000 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ /dev/null @@ -1,566 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - ****************************************************************************/ -(function () { - _ccsg.Label.TTFLabelBaker = function () {}; - - var proto = _ccsg.Label.TTFLabelBaker.prototype = Object.create(Object.prototype); - - proto.updateStatus = function () { - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - - if (colorDirty) { - this._updateDisplayColor(); - } - - if (opacityDirty) { - this._updateDisplayOpacity(); - this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); - } - - if(locFlag & flags.contentDirty) { - this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); - this._dirtyFlag &= ~flags.contentDirty; - } - - if (colorDirty || (locFlag & flags.textDirty)) { - this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); - this._rebuildLabelSkin(); - } - - if (this._dirtyFlag & flags.transformDirty) { - this.transform(this.getParentRenderCmd(), true); - this._dirtyFlag &= ~flags.transformDirty; - } - }; - - - proto._syncStatus = function (parentCmd) { - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var parentNode = parentCmd ? parentCmd._node : null; - - if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) - locFlag |= flags.colorDirty; - - if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) - locFlag |= flags.opacityDirty; - - if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) - locFlag |= flags.transformDirty; - - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - - this._dirtyFlag = locFlag; - - if (colorDirty) - this._syncDisplayColor(); - if (opacityDirty) - this._syncDisplayOpacity(); - - if (colorDirty || opacityDirty || (this._dirtyFlag & flags.textDirty)) { - this._rebuildLabelSkin(); - } - - if (this._dirtyFlag & flags.transformDirty) { - this.transform(parentCmd); - } - }; - - proto._getLineHeight = function () { - var nodeSpacingY = this._node.getLineHeight(); - var node = this._node; - if (nodeSpacingY === 0) { - nodeSpacingY = node._fontSize; - } else { - nodeSpacingY = nodeSpacingY * node._fontSize / this._drawFontsize; - } - - var lineHeight = nodeSpacingY | 0; - return lineHeight; - }; - - proto._constructFontDesc = function () { - var node = this._node; - var fontDesc = node._fontSize.toString() + 'px '; - var fontFamily = node._fontHandle.length === 0 ? 'serif' : node._fontHandle; - fontDesc = fontDesc + fontFamily; - if(node._isBold) { - fontDesc = "bold " + fontDesc; - } - - return fontDesc; - }; - - proto._measureText = function (ctx) { - return function(string) { - return ctx.measureText(string).width; - }; - }; - - - proto._calculateLabelFont = function() { - var node = this._node; - var paragraphedStrings = node._string.split('\n'); - - node._fontSize = node._drawFontsize; - var fontDesc = this._constructFontDesc(); - this._labelContext.font = fontDesc; - - var paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._labelContext); - - if (_ccsg.Label.Overflow.SHRINK === node._overFlow) { - this._splitedStrings = paragraphedStrings; - var i = 0; - var totalHeight = 0; - var maxLength = 0; - - if (node._isWrapText) { - - var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin(); - var canvasHeightNoMargin = this._canvasSize.height - 2 * this._getMargin(); - if(canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) { - fontDesc = this._constructFontDesc(); - this._labelContext.font = fontDesc; - return fontDesc; - } - totalHeight = canvasHeightNoMargin + 1; - maxLength = canvasWidthNoMargin + 1; - var actualFontSize = this._drawFontsize + 1; - var textFragment = ""; - var tryDivideByTwo = true; - var startShrinkFontSize = actualFontSize | 0; - - while (totalHeight > canvasHeightNoMargin || maxLength > canvasWidthNoMargin) { - if (tryDivideByTwo) { - actualFontSize = (startShrinkFontSize / 2) | 0; - } else { - actualFontSize = startShrinkFontSize - 1; - startShrinkFontSize = actualFontSize; - } - if(actualFontSize <= 0) { - cc.logID(4003); - break; - } - node._fontSize = actualFontSize; - fontDesc = this._constructFontDesc(); - this._labelContext.font = fontDesc; - - this._splitedStrings = []; - totalHeight = 0; - for (i = 0; i < paragraphedStrings.length; ++i) { - var j = 0; - var allWidth = this._labelContext.measureText(paragraphedStrings[i]).width; - textFragment = cc.TextUtils.fragmentText(paragraphedStrings[i], - allWidth, - canvasWidthNoMargin, - this._measureText(this._labelContext)); - while(j < textFragment.length) { - var measureWidth = this._labelContext.measureText(textFragment[j]).width; - maxLength = measureWidth; - totalHeight += this._getLineHeight(); - ++j; - } - this._splitedStrings = this._splitedStrings.concat(textFragment); - } - - if(tryDivideByTwo) { - if (totalHeight > canvasHeightNoMargin) { - startShrinkFontSize = actualFontSize | 0; - } else { - tryDivideByTwo = false; - totalHeight = canvasHeightNoMargin + 1; - } - } - } - } - else { - totalHeight = paragraphedStrings.length * this._getLineHeight(); - - for (i = 0; i < paragraphedStrings.length; ++i) { - if (maxLength < paragraphLength[i]) { - maxLength = paragraphLength[i]; - } - } - var scaleX = (this._canvasSize.width - 2 * this._getMargin()) / maxLength; - var scaleY = this._canvasSize.height / totalHeight; - - node._fontSize = (this._drawFontsize * Math.min(1, scaleX, scaleY)) | 0; - fontDesc = this._constructFontDesc(); - this._labelContext.font = fontDesc; - } - } - - return fontDesc; - }; - - proto._getMargin = function() { - return (this._node && this._node._margin) || 0; - }; - - proto._calculateParagraphLength = function(paragraphedStrings, ctx) { - var paragraphLength = []; - - for (var i = 0; i < paragraphedStrings.length; ++i) { - var textMetric = ctx.measureText(paragraphedStrings[i]); - paragraphLength.push(textMetric.width); - } - - return paragraphLength; - }; - - proto._calculateCanvasSize = function() { - var node = this._node; - var canvasWidth = node._contentSize.width; - var canvasHeight = node._contentSize.height; - if (canvasWidth <= 0) canvasWidth = 1; - if (canvasHeight <= 0) canvasHeight = 1; - - return cc.size(canvasWidth, canvasHeight); - }; - - proto._calculateSplitedStrings = function() { - var node = this._node; - - var paragraphedStrings = node._string.split('\n'); - - var i; - if (node._isWrapText) { - this._splitedStrings = []; - var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin(); - for (i = 0; i < paragraphedStrings.length; ++i) { - var allWidth = this._labelContext.measureText(paragraphedStrings[i]).width; - var textFragment = cc.TextUtils.fragmentText(paragraphedStrings[i], - allWidth, - canvasWidthNoMargin, - this._measureText(this._labelContext)); - this._splitedStrings = this._splitedStrings.concat(textFragment); - } - } - else { - this._splitedStrings = paragraphedStrings; - } - - }; - - proto._updateLabelDimensions = function() { - var node = this._node; - var paragraphedStrings = node._string.split('\n'); - var i; - var ctx = this._labelContext; - - if (_ccsg.Label.Overflow.RESIZE_HEIGHT === node._overFlow) { - this._canvasSize.height = this._splitedStrings.length * this._getLineHeight(); - _ccsg.Node.prototype.setContentSize.call(node, this._canvasSize); - } - else if(_ccsg.Label.Overflow.NONE === node._overFlow) { - this._splitedStrings = paragraphedStrings; - var canvasSizeX = 0; - var canvasSizeY = 0; - for (i = 0; i < paragraphedStrings.length; ++i) { - var paraLength = ctx.measureText(paragraphedStrings[i]).width; - canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength; - } - canvasSizeY = this._splitedStrings.length * this._getLineHeight(); - - this._canvasSize.width = parseFloat(canvasSizeX.toFixed(2)) + 2 * this._getMargin(); - this._canvasSize.height = parseFloat(canvasSizeY.toFixed(2)); - if(node._isItalic) { - //0.0174532925 = 3.141592653 / 180 - this._canvasSize.width += node._drawFontsize * Math.tan(12 * 0.0174532925); - } - _ccsg.Node.prototype.setContentSize.call(node, this._canvasSize); - } - - this._labelCanvas.width = this._canvasSize.width; - this._labelCanvas.height = this._canvasSize.height; - - }; - - proto._calculateFillTextStartPosition = function() { - var node = this._node; - var lineHeight = this._getLineHeight(); - var lineCount = this._splitedStrings.length; - var labelX; - var firstLinelabelY; - - if (cc.TextAlignment.RIGHT === node._hAlign) { - labelX = this._canvasSize.width - this._getMargin(); - } - else if (cc.TextAlignment.CENTER === node._hAlign) { - labelX = this._canvasSize.width / 2; - } - else { - labelX = 0 + this._getMargin(); - } - - if (cc.VerticalTextAlignment.TOP === node._vAlign) { - firstLinelabelY = 0; - } - else if (cc.VerticalTextAlignment.CENTER === node._vAlign) { - firstLinelabelY = this._canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2; - } - else { - firstLinelabelY = this._canvasSize.height - lineHeight * (lineCount - 1); - } - - return cc.p(labelX, firstLinelabelY); - }; - - proto._calculateTextBaseline = function() { - var node = this._node; - var hAlign; - var vAlign; - - if (cc.TextAlignment.RIGHT === node._hAlign) { - hAlign = 'right'; - } - else if (cc.TextAlignment.CENTER === node._hAlign) { - hAlign = 'center'; - } - else { - hAlign = 'left'; - } - - this._labelContext.textAlign = hAlign; - if (cc.VerticalTextAlignment.TOP === node._vAlign) { - vAlign = 'top'; - } - else if (cc.VerticalTextAlignment.CENTER === node._vAlign) { - vAlign = 'middle'; - } - else { - vAlign = 'bottom'; - } - this._labelContext.textBaseline = vAlign; - }; - - proto._bakeLabel = function () { - var node = this._node; - this._drawFontsize = node._drawFontsize; - this._canvasSize = this._calculateCanvasSize(); - - //Note: don't change the calling order of the following 3 statements - this._fontDesc = this._calculateLabelFont(); - this._calculateSplitedStrings(); - this._updateLabelDimensions(); - - this._calculateTextBaseline(); - - this._updateTexture(); - }; - - - proto._calculateUnderlineStartPosition = function () { - var node = this._node; - var lineHeight = this._getLineHeight(); - var lineCount = this._splitedStrings.length; - var labelX; - var firstLinelabelY; - - labelX = 0 + this._getMargin(); - - if (cc.VerticalTextAlignment.TOP === node._vAlign) { - firstLinelabelY = node._fontSize; - } - else if (cc.VerticalTextAlignment.CENTER === node._vAlign) { - firstLinelabelY = this._canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 + node._fontSize / 2; - } - else { - firstLinelabelY = this._canvasSize.height - lineHeight * (lineCount - 1); - } - - return cc.p(labelX, firstLinelabelY); - }; - - proto._updateTexture = function() { - this._labelContext.clearRect(0, 0, this._labelCanvas.width, this._labelCanvas.height); - - this._labelContext.font = this._fontDesc; - - var startPosition = this._calculateFillTextStartPosition(); - var lineHeight = this._getLineHeight(); - //use round for line join to avoid sharp intersect point - this._labelContext.lineJoin = 'round'; - var color = this._displayedColor; - this._labelContext.fillStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')'; - var underlineStartPosition; - - //do real rendering - for (var i = 0; i < this._splitedStrings.length; ++i) { - if(this._node.isOutlined()) - { - var strokeColor = this._node.getOutlineColor() || cc.color(255,255,255,255); - this._labelContext.globalCompositeOperation = 'source-over'; - this._labelContext.strokeStyle = 'rgb(' + strokeColor.r + ',' + strokeColor.g + ',' + strokeColor.b + ')'; - this._labelContext.lineWidth = this._node.getOutlineWidth() * 2; - this._labelContext.strokeText(this._splitedStrings[i], - startPosition.x, startPosition.y + i * lineHeight); - } - if(this._node.getFillColorGradientEnabled()) { - var gradientStartColor = this._node.getGradientStartColor() || cc.color(255, 255, 255, 255); - var gradientEndColor = this._node.getGradientEndColor() || cc.color(255, 255, 255, 255); - var gradientArgument = this._getGradientArgs(); - var gradient = this._labelContext.createLinearGradient(gradientArgument.left, gradientArgument.top, gradientArgument.right, gradientArgument.bottom); - gradient.addColorStop(0, cc.colorToHex(gradientStartColor)); - gradient.addColorStop(1, cc.colorToHex(gradientEndColor)); - this._labelContext.fillStyle = gradient; - } - this._labelContext.fillText(this._splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); - if(this._node._isUnderline) { - underlineStartPosition = this._calculateUnderlineStartPosition(); - this._labelContext.save(); - this._labelContext.beginPath(); - this._labelContext.lineWidth = this._node._fontSize / 8; - this._labelContext.strokeStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')'; - this._labelContext.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 1); - this._labelContext.lineTo(underlineStartPosition.x + this._labelCanvas.width, underlineStartPosition.y + i * lineHeight - 1); - this._labelContext.stroke(); - this._labelContext.restore(); - } - } - - this._texture.loaded = false; - // Hack. because we delete _image after usage in WEBGL mode - this._texture._image = this._labelCanvas; - this._texture.handleLoadedTexture(true); - }; - - proto._getGradientArgs = function () { - this._gradientArgument = {}; - this._gradientArgument.left = 0; - this._gradientArgument.top = 0; - var contentSize = this._node._contentSize; - switch(this._node.getFillColorGradientDirection()) { - //horizontal - case 0: - this._gradientArgument.right = contentSize.width; - this._gradientArgument.bottom = 0; - break; - case 1: - this._gradientArgument.right = 0; - this._gradientArgument.bottom = contentSize.height; - break; - case 2: - this._gradientArgument.right = contentSize.width; - this._gradientArgument.bottom = contentSize.height; - break; - default: - break; - } - return this._gradientArgument; - }; - - proto._rebuildLabelSkin = function () { - this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; - var node = this._node; - node._updateLabel(); - }; -})(); - -(function () { - _ccsg.Label.CanvasRenderCmd = function (renderableObject) { - this._rootCtor(renderableObject); - this._needDraw = true; - this._texture = new cc.Texture2D(); - this._labelCanvas = document.createElement('canvas'); - this._labelCanvas.width = 1; - this._labelCanvas.height = 1; - this._labelContext = this._labelCanvas.getContext('2d'); - this._texture.initWithElement(this._labelCanvas); - this._splitedStrings = null; - }; - - var proto = _ccsg.Label.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); - cc.js.mixin(proto, _ccsg.Label.TTFLabelBaker.prototype); - - proto.constructor = _ccsg.Label.CanvasRenderCmd; - - proto._doCulling = function () { - var rect = cc.visibleRect, - bb = this._currentRegion, - l = bb._minX, r = bb._maxX, b = bb._minY, t = bb._maxY, - vl = rect.left.x, vr = rect.right.x, vt = rect.top.y, vb = rect.bottom.y; - - this._needDraw = !(r < vl || l > vr || t < vb || b > vt); - }; - - proto.rendering = function (ctx, scaleX, scaleY) { - var node = this._node; - - if (node._labelType === _ccsg.Label.Type.TTF || - node._labelType === _ccsg.Label.Type.SystemFont) { - var locDisplayOpacity = this._displayedOpacity; - var alpha = locDisplayOpacity / 255; - - if (locDisplayOpacity === 0) - return; - - var wrapper = ctx || cc._renderContext, - context = wrapper.getContext(); - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.setCompositeOperation(_ccsg.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(node._blendFunc)); - wrapper.setGlobalAlpha(alpha); - - if (this._texture) { - var sx, sy, sw, sh; - var x, y, w, h; - - x = 0; - y = -this._node._contentSize.height; - w = this._node._contentSize.width; - h = this._node._contentSize.height; - - - var textureWidth = this._texture.width; - var textureHeight = this._texture.height; - - sx = 0; - sy = 0; - sw = textureWidth; - sh = textureHeight; - - var image = this._texture._image; - if (this._texture._pattern !== '') { - wrapper.setFillStyle(context.createPattern(image, this._texture._pattern)); - context.fillRect(x, y, w, h); - } - else { - if(sw !== 0 && sh !== 0 && w !== 0 && h !== 0) { - context.drawImage(image, - sx, sy, sw, sh, - x, y, w, h); - } - } - } - cc.g_NumberOfDraws = cc.g_NumberOfDraws + 1; - } - - }; - -})(); diff --git a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js deleted file mode 100644 index 680c467594..0000000000 --- a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js +++ /dev/null @@ -1,142 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - Use any of these editors to generate BMFonts: - http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) - http://www.n4te.com/hiero/hiero.jnlp (Free, Java) - http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) - http://www.angelcode.com/products/bmfont/ (Free, Windows only) - ****************************************************************************/ - -_ccsg.Label.WebGLRenderCmd = function(renderableObject){ - this._rootCtor(renderableObject); - this._needDraw = true; - - this._texture = new cc.Texture2D(); - this._labelCanvas = document.createElement("canvas"); - this._texture.initWithElement(this._labelCanvas); - this._labelContext = this._labelCanvas.getContext("2d"); - - this._labelCanvas.width = 1; - this._labelCanvas.height = 1; - this._splitedStrings = null; - this._drawFontsize = 0; - - this._vertices = [ - {x: 0, y: 0, u: 0, v: 0}, // tl - {x: 0, y: 0, u: 0, v: 1}, // bl - {x: 0, y: 0, u: 1, v: 0}, // tr - {x: 0, y: 0, u: 1, v: 1} // br - ]; - this._color = new Uint32Array(1); - this._dirty = false; - - this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); -}; - -var proto = _ccsg.Label.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); -cc.js.mixin(proto, _ccsg.Label.TTFLabelBaker.prototype); - -proto.constructor = _ccsg.Label.WebGLRenderCmd; - -proto.updateTransform = function (parentCmd) { - this.originUpdateTransform(parentCmd); - - var node = this._node, - lx = 0, rx = this._labelCanvas.width, - by = 0, ty = this._labelCanvas.height, - wt = this._worldTransform; - - var vert = this._vertices; - vert[0].x = lx * wt.a + ty * wt.c + wt.tx; // tl - vert[0].y = lx * wt.b + ty * wt.d + wt.ty; - vert[1].x = lx * wt.a + by * wt.c + wt.tx; // bl - vert[1].y = lx * wt.b + by * wt.d + wt.ty; - vert[2].x = rx * wt.a + ty * wt.c + wt.tx; // tr - vert[2].y = rx * wt.b + ty * wt.d + wt.ty; - vert[3].x = rx * wt.a + by * wt.c + wt.tx; // br - vert[3].y = rx * wt.b + by * wt.d + wt.ty; -}; - -proto._doCulling = function () { - var node = this._node; - if (!node._string || (node._labelType !== _ccsg.Label.Type.TTF && - node._labelType !== _ccsg.Label.Type.SystemFont)) { - // No culling for bmfont - return; - } - - var rect = cc.visibleRect; - if (this._cameraFlag > 0) { - rect = cc.Camera.main.visibleRect; - } - - var vl = rect.left.x; - var vr = rect.right.x; - var vt = rect.top.y; - var vb = rect.bottom.y; - - var vert = this._vertices; - if (((vert[0].x-vl) & (vert[1].x-vl) & (vert[2].x-vl) & (vert[3].x-vl)) >> 31 || // All outside left - ((vr-vert[0].x) & (vr-vert[1].x) & (vr-vert[2].x) & (vr-vert[3].x)) >> 31 || // All outside right - ((vert[0].y-vb) & (vert[1].y-vb) & (vert[2].y-vb) & (vert[3].y-vb)) >> 31 || // All outside bottom - ((vt-vert[0].y) & (vt-vert[1].y) & (vt-vert[2].y) & (vt-vert[3].y)) >> 31) // All outside top - { - this._needDraw = false; - } - else { - this._needDraw = true; - } -}; - -proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { - var node = this._node; - if (!node._string || (node._labelType !== _ccsg.Label.Type.TTF && - node._labelType !== _ccsg.Label.Type.SystemFont)) - return 0; - - // Fill in vertex data with quad information (4 vertices for sprite) - // Use 255 because color has been set when baking label - // premultiplied alpha is used for labelTTF and system font - var opacity = this._displayedOpacity; - this._color[0] = ((opacity<<24) | (opacity<<16) | (opacity<<8) | opacity); - - var z = node._vertexZ; - - var vertices = this._vertices; - var i, len = vertices.length, vertex, offset = vertexDataOffset; - for (i = 0; i < len; ++i) { - vertex = vertices[i]; - f32buffer[offset] = vertex.x; - f32buffer[offset + 1] = vertex.y; - f32buffer[offset + 2] = z; - ui32buffer[offset + 3] = this._color[0]; - f32buffer[offset + 4] = vertex.u; - f32buffer[offset + 5] = vertex.v; - offset += 6; - } - - return len; -}; diff --git a/cocos2d/core/renderer/assemblers/index.js b/cocos2d/core/renderer/assemblers/index.js index eebfa70496..774f81978e 100644 --- a/cocos2d/core/renderer/assemblers/index.js +++ b/cocos2d/core/renderer/assemblers/index.js @@ -1,3 +1,4 @@ require('./sprite-assembler'); require('./motion-streak-assembler'); -require('./graphics/graphics-assembler'); \ No newline at end of file +require('./graphics/graphics-assembler'); +require('./label/label-assembler'); \ No newline at end of file diff --git a/cocos2d/core/renderer/assemblers/label/bmfont-assembler.js b/cocos2d/core/renderer/assemblers/label/bmfont-assembler.js new file mode 100644 index 0000000000..2b3d4987e3 --- /dev/null +++ b/cocos2d/core/renderer/assemblers/label/bmfont-assembler.js @@ -0,0 +1,804 @@ +const renderEngine = require('../../render-engine'); +const RenderData = renderEngine.RenderData; + +const Label = require('../../../components/CCLabel'); +const Overflow = Label.Overflow; + + +let FontLetterDefinition = function() { + this._u = 0; + this._v = 0; + this._width = 0; + this._height = 0; + this._offsetX = 0; + this._offsetY = 0; + this._textureID = 0; + this._validDefinition = false; + this._xAdvance = 0; +}; + +cc.FontAtlas = function (fntConfig) { + this._letterDefinitions = {}; +}; + +cc.FontAtlas.prototype = { + constructor: cc.FontAtlas, + addLetterDefinitions: function(letter, letterDefinition) { + this._letterDefinitions[letter] = letterDefinition; + }, + cloneLetterDefinition: function() { + let copyLetterDefinitions = {}; + for (let key in this._letterDefinitions) { + let value = new FontLetterDefinition(); + cc.js.mixin(value, this._letterDefinitions[key]); + copyLetterDefinitions[key] = value; + } + return copyLetterDefinitions; + }, + assignLetterDefinitions: function(letterDefinition) { + for (let key in this._letterDefinitions) { + let newValue = letterDefinition[key]; + let oldValue = this._letterDefinitions[key]; + cc.js.mixin(oldValue, newValue); + } + }, + scaleFontLetterDefinition: function(scaleFactor) { + for (let fontDefinition in this._letterDefinitions) { + let letterDefinitions = this._letterDefinitions[fontDefinition]; + letterDefinitions._width *= scaleFactor; + letterDefinitions._height *= scaleFactor; + letterDefinitions._offsetX *= scaleFactor; + letterDefinitions._offsetY *= scaleFactor; + letterDefinitions._xAdvance *= scaleFactor; + } + }, + getLetterDefinitionForChar: function(char) { + let hasKey = this._letterDefinitions.hasOwnProperty(char.charCodeAt(0)); + let letterDefinition; + if (hasKey) { + letterDefinition = this._letterDefinitions[char.charCodeAt(0)]; + } else { + letterDefinition = null; + } + return letterDefinition; + } +}; + +let LetterInfo = function() { + this._char = ''; + this._valid = true; + this._positionX = 0; + this._positionY = 0; + this._lineIndex = 0; +}; + +let _tmpRect = cc.rect(); + +let _comp = null; + +let _horizontalKernings = []; +let _lettersInfo = []; +let _linesWidth = []; +let _linesOffsetX = []; +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 _spriteFrame = null; +let _lineSpacing = 0; +let _string = ''; +let _fontSize = 0; +let _originFontSize = 0; +let _overflow = 0; +let _contentSize = cc.size(); + +module.exports = { + createData (comp) { + return new RenderData(); + }, + + update (comp) { + if (!comp._renderData.vertDirty) 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(); + }, + + fillVertexBuffer (comp, index, vbuf, uintbuf) { + let off = index * comp._vertexFormat._bytes / 4; + let node = comp.node; + let renderData = comp._renderData; + let data = renderData._data; + let z = node._position.z; + let color = node._color._val; + + 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; + + let vert; + let length = renderData.dataLength; + for (let i = 0; i < length; i++) { + vert = data[i]; + vbuf[off + 0] = vert.x * a + vert.y * c + tx; + vbuf[off + 1] = vert.x * b + vert.y * d + ty; + vbuf[off + 2] = z; + vbuf[off + 4] = vert.u; + vbuf[off + 5] = vert.v; + uintbuf[off + 3] = color; + off += 6; + } + }, + + fillIndexBuffer (comp, offset, vertexId, ibuf) { + let renderData = comp._renderData; + let length = renderData.indiceCount; + for (let i = 0; i < length; i+=6) { + ibuf[offset++] = vertexId; + ibuf[offset++] = vertexId+1; + ibuf[offset++] = vertexId+2; + ibuf[offset++] = vertexId+1; + ibuf[offset++] = vertexId+3; + ibuf[offset++] = vertexId+2; + vertexId += 4; + } + }, + + _updateFontScale () { + _bmfontScale = _fontSize / _originFontSize; + }, + + _updateProperties () { + let fontAsset = _comp.font; + _spriteFrame = fontAsset.spriteFrame; + _fntConfig = fontAsset._fntConfig; + + _fontAtlas = _comp._fontAtlas; + if (!_fontAtlas) { + _fontAtlas = new cc.FontAtlas(_fntConfig); + + let fontDict = _fntConfig.fontDefDictionary; + + for (let fontDef in fontDict) { + let letterDefinition = new FontLetterDefinition(); + + let rect = fontDict[fontDef].rect; + + letterDefinition._offsetX = fontDict[fontDef].xOffset; + letterDefinition._offsetY = fontDict[fontDef].yOffset; + letterDefinition._width = rect.width; + letterDefinition._height = rect.height; + letterDefinition._u = rect.x; + letterDefinition._v = rect.y; + //FIXME: only one texture supported for now + letterDefinition._textureID = 0; + letterDefinition._validDefinition = true; + letterDefinition._xAdvance = fontDict[fontDef].xAdvance; + + _fontAtlas.addLetterDefinitions(fontDef, letterDefinition); + } + + comp._fontAtlas = _fontAtlas; + } + + _string = comp.string; + _fontSize = comp.fontSize; + _originFontSize = _fntConfig.fontSize; + _contentSize = comp.node._contentSize; + _hAlign = comp.horizontalAlign; + _vAlign = comp.verticalAlign; + _spacingX = comp.spacingX; + _overflow = comp.overflow; + _lineHeight = comp._lineHeight; + + // should wrap text + if (_overflow === Overflow.NONE) { + _isWrapText = false; + } + else if (_overflow === Overflow.RESIZE_HEIGHT) { + _isWrapText = true; + } + else { + _isWrapText = comp.enableWrapText; + } + + this._setupBMFontOverflowMetrics(); + }, + + _resetProperties () { + _fontAtlas = null; + _fntConfig = null; + _spriteFrame = null; + }, + + _updateContent () { + this._updateFontScale(); + this._computeHorizontalKerningForText(); + this._alignText(); + }, + + _computeHorizontalKerningForText () { + let string = _string; + let stringLen = string.length; + + let kerningDict = _fntConfig.kerningDict; + let horizontalKernings = _horizontalKernings; + + let prev = -1; + for (let i = 0; i < stringLen; ++i) { + let key = string.charCodeAt(i); + let kerningAmount = kerningDict[(prev << 16) | (key & 0xffff)] || 0; + if (i < stringLen - 1) { + horizontalKernings[i] = kerningAmount; + } else { + horizontalKernings[i] = 0; + } + prev = key; + } + }, + + _multilineTextWrap: function(nextTokenFunc) { + let textLen = _string.length; + + let lineIndex = 0; + let nextTokenX = 0; + let nextTokenY = 0; + let longestLine = 0; + let letterRight = 0; + + let highestY = 0; + let lowestY = 0; + let letterDef = null; + let letterPosition = cc.p(0, 0); + + this._updateFontScale(comp); + + let letterDefinitions = _fontAtlas._letterDefinitions; + + for (let index = 0; index < textLen;) { + let character = _string.charAt(index); + if (character === "\n") { + _linesWidth.push(letterRight); + letterRight = 0; + lineIndex++; + nextTokenX = 0; + nextTokenY -= _lineHeight * _bmfontScale + _lineSpacing; + this._recordPlaceholderInfo(index, character); + index++; + continue; + } + + let tokenLen = nextTokenFunc(_string, index, textLen); + let tokenHighestY = highestY; + let tokenLowestY = lowestY; + let tokenRight = letterRight; + let nextLetterX = nextTokenX; + let newLine = false; + + for (let tmp = 0; tmp < tokenLen; ++tmp) { + let letterIndex = index + tmp; + character = _string.charAt(letterIndex); + if (character === "\r") { + this._recordPlaceholderInfo(letterIndex, character); + continue; + } + letterDef = _fontAtlas.getLetterDefinitionForChar(character); + if (!letterDef) { + this._recordPlaceholderInfo(letterIndex, character); + console.log("Can't find letter definition in texture atlas " + _fntConfig.atlasName + " for letter:" + character); + continue; + } + + let letterX = nextLetterX + letterDef._offsetX * _bmfontScale; + + if (_isWrapText + && _maxLineWidth > 0 + && nextTokenX > 0 + && letterX + letterDef._width * _bmfontScale > _maxLineWidth + && !cc.TextUtils.isUnicodeSpace(character)) { + _linesWidth.push(letterRight); + letterRight = 0; + lineIndex++; + nextTokenX = 0; + nextTokenY -= (_lineHeight * _bmfontScale + _lineSpacing); + newLine = true; + break; + } else { + letterPosition.x = letterX; + } + + letterPosition.y = nextTokenY - letterDef._offsetY * _bmfontScale; + this._recordLetterInfo(letterDefinitions, letterPosition, character, letterIndex, lineIndex); + + if (letterIndex + 1 < _horizontalKernings.length && letterIndex < textLen - 1) { + nextLetterX += _horizontalKernings[letterIndex + 1]; + } + + nextLetterX += letterDef._xAdvance * _bmfontScale + _spacingX; + + tokenRight = letterPosition.x + letterDef._width * _bmfontScale; + + if (tokenHighestY < letterPosition.y) { + tokenHighestY = letterPosition.y; + } + + if (tokenLowestY > letterPosition.y - letterDef._height * _bmfontScale) { + tokenLowestY = letterPosition.y - letterDef._height * _bmfontScale; + } + + } //end of for loop + + if (newLine) continue; + + nextTokenX = nextLetterX; + letterRight = tokenRight; + + if (highestY < tokenHighestY) { + highestY = tokenHighestY; + } + if (lowestY > tokenLowestY) { + lowestY = tokenLowestY; + } + if (longestLine < letterRight) { + longestLine = letterRight; + } + + index += tokenLen; + } //end of for loop + + _linesWidth.push(letterRight); + + _numberOfLines = lineIndex + 1; + _textDesiredHeight = _numberOfLines * _lineHeight * _bmfontScale; + if (_numberOfLines > 1) { + _textDesiredHeight += (_numberOfLines - 1) * _lineSpacing; + } + + _contentSize.width = _labelWidth; + _contentSize.height = _labelHeight; + if (_labelWidth <= 0) { + _contentSize.width = parseFloat(longestLine.toFixed(2)); + } + if (_labelHeight <= 0) { + _contentSize.height = parseFloat(_textDesiredHeight.toFixed(2)); + } + + _tailoredTopY = _contentSize.height; + _tailoredBottomY = 0; + if (highestY > 0) { + _tailoredTopY = _contentSize.height + highestY; + } + if (lowestY < -_textDesiredHeight) { + _tailoredBottomY = _textDesiredHeight + lowestY; + } + + return true; + }, + + _getFirstCharLen: function() { + return 1; + }, + + _getFirstWordLen: function(text, startIndex, textLen) { + let character = text.charAt(startIndex); + if (cc.TextUtils.isUnicodeCJK(character) + || character === "\n" + || cc.TextUtils.isUnicodeSpace(character)) { + return 1; + } + + let len = 1; + let letterDef = _fontAtlas.getLetterDefinitionForChar(character); + if (!letterDef) { + return len; + } + let nextLetterX = letterDef._xAdvance * _bmfontScale + _spacingX; + let letterX; + for (let index = startIndex + 1; index < textLen; ++index) { + character = text.charAt(index); + + letterDef = _fontAtlas.getLetterDefinitionForChar(character); + if (!letterDef) { + break; + } + letterX = nextLetterX + letterDef._offsetX * _bmfontScale; + + if(letterX + letterDef._width * _bmfontScale > _maxLineWidth + && !cc.TextUtils.isUnicodeSpace(character) + && _maxLineWidth > 0) { + return len; + } + nextLetterX += letterDef._xAdvance * _bmfontScale + _spacingX; + if (character === "\n" + || cc.TextUtils.isUnicodeSpace(character) + || cc.TextUtils.isUnicodeCJK(character)) { + break; + } + len++; + } + + return len; + }, + + _multilineTextWrapByWord: function() { + return this._multilineTextWrap(this._getFirstWordLen); + }, + + _multilineTextWrapByChar: function() { + return this._multilineTextWrap(this._getFirstCharLen); + }, + + _recordPlaceholderInfo: function(letterIndex, char) { + if (letterIndex >= _lettersInfo.length) { + let tmpInfo = new LetterInfo(); + _lettersInfo.push(tmpInfo); + } + + _lettersInfo[letterIndex]._char = char; + _lettersInfo[letterIndex]._valid = false; + }, + + _recordLetterInfo: function(letterDefinitions, letterPosition, character, letterIndex, lineIndex) { + if (letterIndex >= _lettersInfo.length) { + let tmpInfo = new LetterInfo(); + _lettersInfo.push(tmpInfo); + } + character = character.charCodeAt(0); + + _lettersInfo[letterIndex]._lineIndex = lineIndex; + _lettersInfo[letterIndex]._char = character; + _lettersInfo[letterIndex]._valid = letterDefinitions[character]._validDefinition; + _lettersInfo[letterIndex]._positionX = letterPosition.x; + _lettersInfo[letterIndex]._positionY = letterPosition.y; + }, + + _alignText: function() { + _textDesiredHeight = 0; + _linesWidth.length = 0; + + if (!_lineBreakWithoutSpaces) { + this._multilineTextWrapByWord(); + } else { + this._multilineTextWrapByChar(); + } + + this._computeAlignmentOffset(); + + //shrink + if (_overflow === Overflow.SHRINK) { + if (_fontSize > 0 && this._isVerticalClamp()) { + this._shrinkLabelToContentSize(this._isVerticalClamp); + } + } + + if (!this._updateQuads()) { + if (_overflow === Overflow.SHRINK) { + this._shrinkLabelToContentSize(this._isHorizontalClamp); + } + } + }, + + _scaleFontSizeDown (fontSize) { + let shouldUpdateContent = true; + if (!fontSize) { + fontSize = 0.1; + shouldUpdateContent = false; + } + _fontSize = fontSize; + + if (shouldUpdateContent) { + this._updateContent(); + } + }, + + _shrinkLabelToContentSize (lambda) { + let fontData = comp._fontData; + let fontSize = _fontSize; + let originalLineHeight = _lineHeight; + let fontAtlas = _fontAtlas; + + let i = 0; + let tempLetterDefinition = fontAtlas.cloneLetterDefinition(); + let flag = true; + + while (lambda(fontData)) { + ++i; + + let newFontSize = fontSize - i; + flag = false; + if (newFontSize <= 0) { + break; + } + + let scale = newFontSize / fontSize; + fontAtlas.assignLetterDefinitions(tempLetterDefinition); + fontAtlas.scaleFontLetterDefinition(scale); + _lineHeight = originalLineHeight * scale; + if (!_lineBreakWithoutSpaces) { + this._multilineTextWrapByWord(); + } else { + this._multilineTextWrapByChar(); + } + this._computeAlignmentOffset(fontData); + } + + _lineHeight = originalLineHeight; + fontAtlas.assignLetterDefinitions(tempLetterDefinition); + + if (!flag) { + if (fontSize - i >= 0) { + this._scaleFontSizeDown(fontSize - i); + } + } + }, + + _isVerticalClamp () { + if (_textDesiredHeight > _contentSize.height) { + return true; + } else { + return false; + } + }, + + _isHorizontalClamp () { + let letterDefinitions = _fontAtlas._letterDefinitions; + let letterClamp = false; + for (let ctr = 0, l = _string.length; ctr < l; ++ctr) { + let letterInfo = _lettersInfo[ctr]; + if (letterInfo._valid) { + let letterDef = letterDefinitions[letterInfo._char]; + + let px = letterInfo._positionX + letterDef._width / 2 * _bmfontScale; + let lineIndex = letterInfo._lineIndex; + if (_labelWidth > 0) { + if (!_isWrapText) { + if(px > _contentSize.width){ + letterClamp = true; + break; + } + }else{ + let wordWidth = _linesWidth[lineIndex]; + if (wordWidth > _contentSize.width && (px > _contentSize.width || px < 0)) { + letterClamp = true; + break; + } + } + } + } + } + + return letterClamp; + }, + + _isHorizontalClamped (px, lineIndex) { + let wordWidth = _linesWidth[lineIndex]; + let letterOverClamp = (px > _contentSize.width || px < 0); + + if(!_isWrapText){ + return letterOverClamp; + }else{ + return (wordWidth > _contentSize.width && letterOverClamp); + } + }, + + _updateQuads () { + let letterDefinitions = _fontAtlas._letterDefinitions; + + let texture = _spriteFrame._texture; + + let renderData = _comp._renderData; + renderData.dataLength = renderData.vertexCount = renderData.indiceCount = 0; + + let contentSize = _contentSize, + appx = renderData._pivotX * contentSize.width, + appy = renderData._pivotY * contentSize.height; + + let ret = true; + for (let ctr = 0, l = _string.length; ctr < l; ++ctr) { + let letterInfo = _lettersInfo[ctr]; + if (!letterInfo._valid) continue; + let letterDef = letterDefinitions[letterInfo._char]; + + _tmpRect.height = letterDef._height; + _tmpRect.width = letterDef._width; + _tmpRect.x = letterDef._u; + _tmpRect.y = letterDef._v; + + let py = letterInfo._positionY + _letterOffsetY; + + if (_labelHeight > 0) { + if (py > _tailoredTopY) { + let clipTop = py - _tailoredTopY; + _tmpRect.y += clipTop; + _tmpRect.height -= clipTop; + py = py - clipTop; + } + + if (py - letterDef._height * _bmfontScale < _tailoredBottomY) { + _tmpRect.height = (py < _tailoredBottomY) ? 0 : (py - _tailoredBottomY); + } + } + + let lineIndex = letterInfo._lineIndex; + let px = letterInfo._positionX + letterDef._width / 2 * _bmfontScale + _linesOffsetX[lineIndex]; + + if (_labelWidth > 0) { + if (this._isHorizontalClamped(px, lineIndex)) { + if (_overflow === Overflow.CLAMP) { + _tmpRect.width = 0; + } else if (_overflow === Overflow.SHRINK) { + if (_contentSize.width > letterDef._width) { + ret = false; + break; + } else { + _tmpRect.width = 0; + } + } + } + } + + if (_tmpRect.height > 0 && _tmpRect.width > 0) { + let isRotated = _spriteFrame.isRotated(); + + let originalSize = _spriteFrame._originalSize; + let rect = _spriteFrame._rect; + let offset = _spriteFrame._offset; + let trimmedLeft = offset.x + (originalSize.width - rect.width) / 2; + let trimmedTop = offset.y - (originalSize.height - rect.height) / 2; + + if(!isRotated) { + _tmpRect.x += (rect.x - trimmedLeft); + _tmpRect.y += (rect.y + trimmedTop); + } else { + let originalX = _tmpRect.x; + _tmpRect.x = rect.x + rect.height - _tmpRect.y - _tmpRect.height - trimmedTop; + _tmpRect.y = originalX + rect.y - trimmedLeft; + if (_tmpRect.y < 0) { + _tmpRect.height = _tmpRect.height + trimmedTop; + } + } + + let letterPositionX = letterInfo._positionX + _linesOffsetX[letterInfo._lineIndex]; + this.appendQuad(renderData, texture, _tmpRect, isRotated, letterPositionX - appx, py - appy, _bmfontScale); + } + } + + return ret; + }, + + 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; + + let data = renderData._data; + let texw = texture.width, + texh = texture.height; + + let rectWidth = rect.width, + rectHeight = rect.height; + + let l, b, r, t; + if (!rotated) { + l = (rect.x) / texw; + r = (rect.x + rectWidth) / texw; + b = (rect.y + rectHeight) / texh; + t = (rect.y) / texh; + + 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; + } else { + l = (rect.x) / texw; + r = (rect.x + rectHeight) / texw; + b = (rect.y + rectWidth) / texh; + t = (rect.y) / texh; + + 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].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; + }, + + _computeAlignmentOffset: function() { + _linesOffsetX.length = 0; + + switch (_hAlign) { + case cc.TextAlignment.LEFT: + for (let i = 0; i < _numberOfLines; ++i) { + _linesOffsetX.push(0); + } + break; + case cc.TextAlignment.CENTER: + for (let i = 0, l = _linesWidth.length; i < l; i++) { + _linesOffsetX.push((_contentSize.width - _linesWidth[i]) / 2); + } + break; + case cc.TextAlignment.RIGHT: + for (let i = 0, l = _linesWidth.length; i < l; i++) { + _linesOffsetX.push(_contentSize.width - _linesWidth[i]); + } + break; + default: + break; + } + + switch (_vAlign) { + case cc.VerticalTextAlignment.TOP: + _letterOffsetY = _contentSize.height; + break; + case cc.VerticalTextAlignment.CENTER: + _letterOffsetY = (_contentSize.height + _textDesiredHeight) / 2; + break; + case cc.VerticalTextAlignment.BOTTOM: + _letterOffsetY = _textDesiredHeight; + break; + default: + break; + } + }, + + _setupBMFontOverflowMetrics () { + let newWidth = _contentSize.width, + newHeight = _contentSize.height; + + if (_overflow === Overflow.RESIZE_HEIGHT) { + newHeight = 0; + } + + if (_overflow === Overflow.NONE) { + newWidth = 0; + newHeight = 0; + } + + _labelWidth = newWidth; + _labelHeight = newHeight; + _labelDimensions.width = newWidth; + _labelDimensions.height = newHeight; + _maxLineWidth = newWidth; + } +}; diff --git a/cocos2d/core/renderer/assemblers/label/label-assembler.js b/cocos2d/core/renderer/assemblers/label/label-assembler.js new file mode 100644 index 0000000000..8b26e7c9ea --- /dev/null +++ b/cocos2d/core/renderer/assemblers/label/label-assembler.js @@ -0,0 +1,48 @@ +const Label = require('../../../components/CCLabel'); +const ttfAssembler = require('./ttf-assembler'); +const bmfontAssembler = require('./bmfont-assembler'); + +var labelAssembler = { + updateRenderData (comp) { + let assembler; + if (comp.font instanceof cc.BitmapFont) { + assembler = bmfontAssembler; + } + else { + assembler = ttfAssembler; + } + + let renderData = comp._renderData; + if (!renderData) { + renderData = comp._renderData = assembler.createData(comp); + } + + let size = comp.node._contentSize; + let anchor = comp.node._anchorPoint; + renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); + + assembler.update(comp); + }, + + fillVertexBuffer (comp, index, vbuf, uintbuf) { + if (comp.font instanceof cc.BitmapFont) { + bmfontAssembler.fillVertexBuffer(comp, index, vbuf, uintbuf); + } + else { + ttfAssembler.fillVertexBuffer(comp, index, vbuf, uintbuf); + } + }, + + fillIndexBuffer (comp, offset, vertexId, ibuf) { + if (comp.font instanceof cc.BitmapFont) { + bmfontAssembler.fillIndexBuffer(comp, offset, vertexId, ibuf); + } + else { + ttfAssembler.fillIndexBuffer(comp, offset, vertexId, ibuf); + } + } +} + +Label._assembler = labelAssembler; + +module.exports = labelAssembler; \ No newline at end of file diff --git a/cocos2d/core/renderer/assemblers/label/ttf-assembler.js b/cocos2d/core/renderer/assemblers/label/ttf-assembler.js new file mode 100644 index 0000000000..982758d428 --- /dev/null +++ b/cocos2d/core/renderer/assemblers/label/ttf-assembler.js @@ -0,0 +1,510 @@ +const renderEngine = require('../../render-engine'); +const RenderData = renderEngine.RenderData; + +const Label = require('../../../components/CCLabel'); +const LabelOutline = require('../../../components/CCLabelOutline'); +const Overflow = Label.Overflow; + +let _comp = null; + +let _context = null; +let _canvas = null; +let _texture = null; + +let _fontDesc = ''; +let _string = ''; +let _fontSize = 0; +let _drawFontsize = 0; +let _splitedStrings = []; +let _canvasSize = cc.size(); +let _lineHeight = 0; +let _hAlign = 0; +let _vAlign = 0; +let _color = null; + +let _isBold = false; +let _isItalic = false; + +// outline +let _isOutlined = false; +let _outlineColor = null; +let _outlineWidth = 0; +let _margin = 0; + +// gradient fill color +let _fillColorGradientEnabled = false; +let _gradientStartColor = null; +let _gradientEndColor = null; +let _gradientArgs = null; + +// underline +let _isUnderline = false; + +module.exports = { + createData (comp) { + let renderData = new RenderData(); + + renderData.dataLength = 4; + renderData.vertexCount = 4; + renderData.indiceCount = 6; + + let data = renderData._data; + data[0].u = 0; + data[0].v = 1; + data[1].u = 1; + data[1].v = 1; + data[2].u = 0; + data[2].v = 0; + data[3].u = 1; + data[3].v = 0; + return renderData; + }, + + fillVertexBuffer (comp, index, vbuf, uintbuf) { + let off = index * comp._vertexFormat._bytes / 4; + let node = comp.node; + let renderData = comp._renderData; + let data = renderData._data; + let z = node._position.z; + let color = node._color._val; + + 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; + + let vert; + let length = renderData.dataLength; + for (let i = 0; i < length; i++) { + vert = data[i]; + vbuf[off + 0] = vert.x * a + vert.y * c + tx; + vbuf[off + 1] = vert.x * b + vert.y * d + ty; + vbuf[off + 2] = z; + vbuf[off + 4] = vert.u; + vbuf[off + 5] = vert.v; + uintbuf[off + 3] = color; + off += 6; + } + }, + + fillIndexBuffer (comp, offset, vertexId, ibuf) { + ibuf[offset + 0] = vertexId; + ibuf[offset + 1] = vertexId + 1; + ibuf[offset + 2] = vertexId + 2; + ibuf[offset + 3] = vertexId + 1; + ibuf[offset + 4] = vertexId + 3; + ibuf[offset + 5] = vertexId + 2; + }, + + update (comp) { + if (!comp._renderData.vertDirty) return; + + _comp = comp; + + if (this._updateFontFamly()) { + this._updateProperties(); + this._calculateLabelFont(); + this._calculateSplitedStrings(); + this._updateLabelDimensions(); + this._calculateTextBaseline(); + this._updateTexture(); + + this._updateVerts(); + + _comp._actualFontSize = _fontSize; + _comp.node.setContentSize(_canvasSize); + + _comp._renderData.vertDirty = _comp._renderData.uvDirty = false; + + _context = null; + _canvas = null; + _texture = null; + } + + _comp = null; + }, + + _updateVerts () { + let renderData = _comp._renderData; + + let width = _canvasSize.width, + height = _canvasSize.height, + appx = renderData._pivotX * width, + appy = renderData._pivotY * height; + + let data = renderData._data; + data[0].x = -appx; + data[0].y = -appy; + data[1].x = width - appx; + data[1].y = -appy; + data[2].x = -appx; + data[2].y = height - appy; + data[3].x = width - appx; + data[3].y = height - appy; + }, + + _updateFontFamly () { + if (!_comp.useSystemFont) { + if (!_comp.font) return false; + + let url = _comp.font.rawUrl; + _fontFamily = cc.CustomFontLoader._getFontFamily(url); + let fontDescriptor = cc.CustomFontLoader._fontCache[_fontFamily]; + if (!fontDescriptor || !fontDescriptor.isLoaded()) { + cc.CustomFontLoader.loadTTF(url); + return false; + } + } + else { + _fontFamily = _comp.fontFamily; + } + + return true; + }, + + _updateProperties () { + _context = _comp._context; + _canvas = _comp._canvas; + _texture = _comp._texture; + + _string = _comp.string; + _fontSize = _comp._fontSize; + _drawFontsize = _fontSize; + _overflow = _comp.overflow; + _canvasSize.width = _comp.node.width; + _canvasSize.height = _comp.node.height; + _lineHeight = _comp._lineHeight; + _hAlign = _comp.horizontalAlign; + _vAlign = _comp.verticalAlign; + _color = _comp.node.color; + + if (_overflow === Overflow.NONE) { + _isWrapText = false; + } + else if (_overflow === Overflow.RESIZE_HEIGHT) { + _isWrapText = true; + } + else { + _isWrapText = _comp.enableWrapText; + } + + // outline + let outline = _comp.getComponent(LabelOutline); + if (outline) { + _isOutlined = true; + _margin = _outlineWidth = outline.width; + _outlineColor = outline.color; + } + else { + _isOutlined = false; + } + }, + + _calculateFillTextStartPosition () { + var lineHeight = this._getLineHeight(); + var lineCount = _splitedStrings.length; + var labelX; + var firstLinelabelY; + + if (_hAlign === cc.TextAlignment.RIGHT) { + labelX = _canvasSize.width - _margin; + } + else if (_hAlign === cc.TextAlignment.CENTER) { + labelX = _canvasSize.width / 2; + } + else { + labelX = 0 + _margin; + } + + if (_vAlign === cc.VerticalTextAlignment.TOP) { + firstLinelabelY = 0; + } + else if (_vAlign === cc.VerticalTextAlignment.CENTER) { + firstLinelabelY = _canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2; + } + else { + firstLinelabelY = _canvasSize.height - lineHeight * (lineCount - 1); + } + + return cc.v2(labelX, firstLinelabelY); + }, + + _updateTexture () { + _context.clearRect(0, 0, _canvas.width, _canvas.height); + _context.font = _fontDesc; + + var startPosition = this._calculateFillTextStartPosition(); + var lineHeight = this._getLineHeight(); + //use round for line join to avoid sharp intersect point + _context.lineJoin = 'round'; + _context.fillStyle = 'rgb(' + _color.r + ',' + _color.g + ',' + _color.b + ')'; + var underlineStartPosition; + + //do real rendering + for (var i = 0; i < _splitedStrings.length; ++i) { + if (_isOutlined) { + var strokeColor = _outlineColor || cc.color(255,255,255,255); + _context.globalCompositeOperation = 'source-over'; + _context.strokeStyle = 'rgb(' + strokeColor.r + ',' + strokeColor.g + ',' + strokeColor.b + ')'; + _context.lineWidth = _outlineWidth * 2; + _context.strokeText(_splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); + } + + if (_fillColorGradientEnabled && _gradientArgs) { + var gradientStartColor = _gradientStartColor || cc.color(255, 255, 255, 255); + var gradientEndColor = _gradientEndColor || cc.color(255, 255, 255, 255); + var gradient = _context.createLinearGradient(_gradientArgs.left, _gradientArgs.top, _gradientArgs.right, _gradientArgs.bottom); + gradient.addColorStop(0, cc.colorToHex(gradientStartColor)); + gradient.addColorStop(1, cc.colorToHex(gradientEndColor)); + _context.fillStyle = gradient; + } + _context.fillText(_splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); + + if (_isUnderline) { + underlineStartPosition = this._calculateUnderlineStartPosition(); + _context.save(); + _context.beginPath(); + _context.lineWidth = _fontSize / 8; + _context.strokeStyle = 'rgb(' + _color.r + ',' + _color.g + ',' + _color.b + ')'; + _context.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 1); + _context.lineTo(underlineStartPosition.x + _canvas.width, underlineStartPosition.y + i * lineHeight - 1); + _context.stroke(); + _context.restore(); + } + } + + _texture.handleLoadedTexture(); + }, + + _calculateUnderlineStartPosition () { + var lineHeight = this._getLineHeight(); + var lineCount = _splitedStrings.length; + var labelX; + var firstLinelabelY; + + labelX = 0 + _margin; + + if (_vAlign === cc.VerticalTextAlignment.TOP) { + firstLinelabelY = _fontSize; + } + else if (_vAlign === cc.VerticalTextAlignment.CENTER) { + firstLinelabelY = _canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 + node._fontSize / 2; + } + else { + firstLinelabelY = _canvasSize.height - lineHeight * (lineCount - 1); + } + + return cc.p(labelX, firstLinelabelY); + }, + + _updateLabelDimensions () { + var paragraphedStrings = _string.split('\n'); + var i; + + if (_overflow === Overflow.RESIZE_HEIGHT) { + _canvasSize.height = _splitedStrings.length * this._getLineHeight(); + } + else if (_overflow === Overflow.NONE) { + _splitedStrings = paragraphedStrings; + var canvasSizeX = 0; + var canvasSizeY = 0; + for (i = 0; i < paragraphedStrings.length; ++i) { + var paraLength = _context.measureText(paragraphedStrings[i]).width; + canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength; + } + canvasSizeY = _splitedStrings.length * this._getLineHeight(); + + _canvasSize.width = parseFloat(canvasSizeX.toFixed(2)) + 2 * _margin; + _canvasSize.height = parseFloat(canvasSizeY.toFixed(2)); + if(_isItalic) { + //0.0174532925 = 3.141592653 / 180 + _canvasSize.width += _drawFontsize * Math.tan(12 * 0.0174532925); + } + } + + _canvas.width = _canvasSize.width; + _canvas.height = _canvasSize.height; + }, + + _calculateTextBaseline () { + var node = this._node; + var hAlign; + var vAlign; + + if (_hAlign === cc.TextAlignment.RIGHT) { + hAlign = 'right'; + } + else if (_hAlign === cc.TextAlignment.CENTER) { + hAlign = 'center'; + } + else { + hAlign = 'left'; + } + _context.textAlign = hAlign; + + if (_vAlign === cc.VerticalTextAlignment.TOP) { + vAlign = 'top'; + } + else if (_vAlign === cc.VerticalTextAlignment.CENTER) { + vAlign = 'middle'; + } + else { + vAlign = 'bottom'; + } + _context.textBaseline = vAlign; + }, + + _calculateSplitedStrings () { + var paragraphedStrings = _string.split('\n'); + + var i; + if (_isWrapText) { + _splitedStrings = []; + var canvasWidthNoMargin = _canvasSize.width - 2 * _margin; + for (i = 0; i < paragraphedStrings.length; ++i) { + var allWidth = _context.measureText(paragraphedStrings[i]).width; + var textFragment = cc.TextUtils.fragmentText(paragraphedStrings[i], + allWidth, + canvasWidthNoMargin, + this._measureText(_context)); + _splitedStrings = _splitedStrings.concat(textFragment); + } + } + else { + _splitedStrings = paragraphedStrings; + } + + }, + + _getFontDesc () { + var fontDesc = _fontSize.toString() + 'px '; + fontDesc = fontDesc + _fontFamily; + if (_isBold) { + fontDesc = "bold " + fontDesc; + } + + return fontDesc; + }, + + _getLineHeight () { + var nodeSpacingY = _lineHeight; + if (nodeSpacingY === 0) { + nodeSpacingY = _fontSize; + } else { + nodeSpacingY = nodeSpacingY * _fontSize / _drawFontsize; + } + + var lineHeight = nodeSpacingY | 0; + return lineHeight; + }, + + _calculateParagraphLength (paragraphedStrings, ctx) { + var paragraphLength = []; + + for (var i = 0; i < paragraphedStrings.length; ++i) { + var textMetric = ctx.measureText(paragraphedStrings[i]); + paragraphLength.push(textMetric.width); + } + + return paragraphLength; + }, + + _measureText (ctx) { + return function(string) { + return ctx.measureText(string).width; + }; + }, + + _calculateLabelFont () { + _fontDesc = this._getFontDesc(); + _context.font = _fontDesc; + + if (_overflow === Overflow.SHRINK) { + var paragraphedStrings = _string.split('\n'); + var paragraphLength = this._calculateParagraphLength(paragraphedStrings, _context); + + _splitedStrings = paragraphedStrings; + var i = 0; + var totalHeight = 0; + var maxLength = 0; + + if (_isWrapText) { + var canvasWidthNoMargin = _canvasSize.width - 2 * _margin; + var canvasHeightNoMargin = _canvasSize.height - 2 * _margin; + if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) { + _fontDesc = this._getFontDesc(); + _context.font = _fontDesc; + return; + } + totalHeight = canvasHeightNoMargin + 1; + maxLength = canvasWidthNoMargin + 1; + var actualFontSize = _fontSize + 1; + var textFragment = ""; + var tryDivideByTwo = true; + var startShrinkFontSize = actualFontSize | 0; + + while (totalHeight > canvasHeightNoMargin || maxLength > canvasWidthNoMargin) { + if (tryDivideByTwo) { + actualFontSize = (startShrinkFontSize / 2) | 0; + } else { + actualFontSize = startShrinkFontSize - 1; + startShrinkFontSize = actualFontSize; + } + if(actualFontSize <= 0) { + cc.logID(4003); + break; + } + _fontSize = actualFontSize; + _fontDesc = this._getFontDesc(); + _context.font = _fontDesc; + + _splitedStrings = []; + totalHeight = 0; + for (i = 0; i < paragraphedStrings.length; ++i) { + var j = 0; + var allWidth = _context.measureText(paragraphedStrings[i]).width; + textFragment = cc.TextUtils.fragmentText(paragraphedStrings[i], + allWidth, + canvasWidthNoMargin, + this._measureText(_context)); + while (j < textFragment.length) { + var measureWidth = _context.measureText(textFragment[j]).width; + maxLength = measureWidth; + totalHeight += this._getLineHeight(); + ++j; + } + _splitedStrings = _splitedStrings.concat(textFragment); + } + + if(tryDivideByTwo) { + if (totalHeight > canvasHeightNoMargin) { + startShrinkFontSize = actualFontSize | 0; + } else { + tryDivideByTwo = false; + totalHeight = canvasHeightNoMargin + 1; + } + } + } + } + else { + totalHeight = paragraphedStrings.length * this._getLineHeight(); + + for (i = 0; i < paragraphedStrings.length; ++i) { + if (maxLength < paragraphLength[i]) { + maxLength = paragraphLength[i]; + } + } + var scaleX = (_canvasSize.width - 2 * _margin) / maxLength; + var scaleY = _canvasSize.height / totalHeight; + + _fontSize = (_drawFontsize * Math.min(1, scaleX, scaleY)) | 0; + _fontDesc = this._getFontDesc(); + _context.font = _fontDesc; + } + } + } +};