diff --git a/CCDebugger.js b/CCDebugger.js index 4d266920e6..e59b724c39 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -329,7 +329,6 @@ cc._formatString = function (arg) { /** * Enum for debug modes. * @enum DebugMode - * @readOnly */ cc.DebugMode = cc.Enum({ /** @@ -440,9 +439,15 @@ cc._initDebugSetting = function (mode) { * @param {any} obj - A JavaScript string containing zero or more substitution strings. * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ - cc.warn = function(){ - return console.warn.apply(console, arguments); - }; + if (console.warn.bind) { + // use bind to avoid pollute call stacks + cc.warn = console.warn.bind(console); + } + else { + cc.warn = function() { + return console.warn.apply(console, arguments); + }; + } if(mode === cc.DebugMode.INFO) { /** * Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). diff --git a/cocos2d/actions3d/CCActionGrid3D.js b/cocos2d/actions3d/CCActionGrid3D.js index ca72abc6b1..6a57691dfb 100644 --- a/cocos2d/actions3d/CCActionGrid3D.js +++ b/cocos2d/actions3d/CCActionGrid3D.js @@ -638,7 +638,7 @@ cc.Ripple3D = cc.Grid3DAction.extend(/** @lends cc.Ripple3D# */{ /** * get Amplitude rate - * @return {*} + * @return {Number} */ getAmplitudeRate:function () { return this._amplitudeRate; diff --git a/cocos2d/animation/animation-state.js b/cocos2d/animation/animation-state.js index a4a2b86581..f52ec8f93b 100644 --- a/cocos2d/animation/animation-state.js +++ b/cocos2d/animation/animation-state.js @@ -9,8 +9,13 @@ var AnimationNode = require('./types').AnimationNode; * @class AnimationState * @extends AnimationNode * @constructor + */ + +/** + * @method AnimationState * @param {AnimationClip} clip * @param {String} [name] + * @return {AnimationState} */ function AnimationState (clip, name) { AnimationNode.call(this, null, null, { @@ -28,7 +33,7 @@ var state = AnimationState.prototype; * The clip that is being played by this animation state. * @property clip * @type {AnimationClip} - * @readOnly + * @final */ JS.get(state, 'clip', function () { return this._clip; diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index acdc4632f5..0872824337 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -626,7 +626,8 @@ cc.Audio = cc._Class.extend({ /** * cc.audioEngine is the singleton object, it provide simple audio APIs. - * @namespace + * @class audioEngine + * @static */ cc.audioEngine = { _currMusic: null, @@ -636,12 +637,14 @@ cc.Audio = cc._Class.extend({ /** * Indicates whether any background music can be played or not. + * @method willPlayMusic * @returns {boolean} true if the background music is playing, otherwise false */ willPlayMusic: function(){return false;}, /** * Play music. + * @method playMusic * @param {String} url The path of the music file without filename extension. * @param {Boolean} loop Whether the music loop or not. * @example @@ -666,6 +669,7 @@ cc.Audio = cc._Class.extend({ /** * Stop playing music. + * @method stopMusic * @param {Boolean} [releaseData] If release the music data or not.As default value is false. * @example * //example @@ -682,6 +686,7 @@ cc.Audio = cc._Class.extend({ /** * Pause playing music. + * @method pauseMusic * @example * //example * cc.audioEngine.pauseMusic(); @@ -694,6 +699,7 @@ cc.Audio = cc._Class.extend({ /** * Resume playing music. + * @method resumeMusic * @example * //example * cc.audioEngine.resumeMusic(); @@ -706,6 +712,7 @@ cc.Audio = cc._Class.extend({ /** * Rewind playing music. + * @method rewindMusic * @example * //example * cc.audioEngine.rewindMusic(); @@ -720,6 +727,7 @@ cc.Audio = cc._Class.extend({ /** * The volume of the music max value is 1.0,the min value is 0.0 . + * @method getMusicVolume * @return {Number} * @example * //example @@ -731,6 +739,7 @@ cc.Audio = cc._Class.extend({ /** * Set the volume of music. + * @method setMusicVolume * @param {Number} volume Volume must be in 0.0~1.0 . * @example * //example @@ -751,6 +760,7 @@ cc.Audio = cc._Class.extend({ /** * Whether the music is playing. + * @method isMusicPlaying * @return {Boolean} If is playing return true,or return false. * @example * //example @@ -775,6 +785,7 @@ cc.Audio = cc._Class.extend({ _effectVolume: 1, /** * Play sound effect. + * @method playEffect * @param {String} url The path of the sound effect with filename extension. * @param {Boolean} loop Whether to loop the effect playing, default value is false * @return {Number|null} the audio id @@ -827,6 +838,7 @@ cc.Audio = cc._Class.extend({ /** * Set the volume of sound effects. + * @method setEffectsVolume * @param {Number} volume Volume must be in 0.0~1.0 . * @example * //example @@ -851,6 +863,7 @@ cc.Audio = cc._Class.extend({ /** * The volume of the effects max value is 1.0,the min value is 0.0 . + * @method getEffectsVolume * @return {Number} * @example * //example @@ -862,6 +875,7 @@ cc.Audio = cc._Class.extend({ /** * Pause playing sound effect. + * @method pauseEffect * @param {Number} cc.Audio The return value of function playEffect. * @example * //example @@ -875,6 +889,7 @@ cc.Audio = cc._Class.extend({ /** * Pause all playing sound effect. + * @method pauseAllEffects * @example * //example * cc.audioEngine.pauseAllEffects(); @@ -893,6 +908,7 @@ cc.Audio = cc._Class.extend({ /** * Resume playing sound effect. + * @method resumeEffect * @param {Number} cc.Audio The return value of function playEffect. * @audioID * //example @@ -905,6 +921,7 @@ cc.Audio = cc._Class.extend({ /** * Resume all playing sound effect + * @method resumeAllEffects * @example * //example * cc.audioEngine.resumeAllEffects(); @@ -921,6 +938,7 @@ cc.Audio = cc._Class.extend({ /** * Stop playing sound effect. + * @method stopEffect * @param {Number} cc.Audio The return value of function playEffect. * @example * //example @@ -933,6 +951,7 @@ cc.Audio = cc._Class.extend({ /** * Stop all playing sound effects. + * @method stopAllEffects * @example * //example * cc.audioEngine.stopAllEffects(); @@ -949,6 +968,7 @@ cc.Audio = cc._Class.extend({ /** * Unload the preloaded effect from internal buffer + * @method unloadEffect * @param {String} url * @example * //example @@ -968,6 +988,7 @@ cc.Audio = cc._Class.extend({ /** * End music and effects. + * @method end */ end: function(){ this.stopMusic(); diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 0d5c2d1d9d..d2155d5063 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -215,7 +215,7 @@ var game = /** @lends cc.game# */{ /** * @property director - * @type cc.Director + * @type Director */ cc.director = cc.Director._getInstance(); if (cc.director.setOpenGLView) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index c28cbe50d2..41c75373e9 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -903,6 +903,15 @@ var Node = cc.Class({ EventTarget.prototype.on.call(this, type, callback, target); }, + /** + * Removes the callback previously registered with the same type, callback, target and or useCapture. + * This method is merely an alias to removeEventListener. + * + * @method off + * @param {String} type - A string representing the event type being removed. + * @param {Function} callback - The callback to remove. + * @param {Object} [target] - The target to invoke the callback, if it's not given, only callback without target will be removed + */ off: function (type, callback, target) { EventTarget.prototype.off.call(this, type, callback, target); @@ -914,6 +923,12 @@ var Node = cc.Class({ } }, + /** + * Removes all callbacks previously registered with the same target. + * + * @method targetOff + * @param {Object} target - The target to be searched for all related callbacks + */ targetOff: function (target) { EventTarget.prototype.targetOff.call(this, target); diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 327fd6dc5c..af1dab217f 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -644,6 +644,12 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ return key === timer.getSelector(); } }, + + /** Unschedules a callback for a callback and a given target. + * If you want to unschedule the "update", use `unscheudleUpdate()` + * @param {Function|String} key The callback to be unscheduled + * @param {Object} target The target bound to the callback. + */ unschedule: function(key, target){ //key, target //selector, target @@ -681,6 +687,10 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ } }, + /** + * Unschedules the update callback for a given target + * @param {Object} target The target to be unscheduled. + */ unscheduleUpdate: function(target){ if (target == null) return; @@ -696,6 +706,11 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ } }, + /** + * Unschedules all scheduled callbacks for a given target. + * This also includes the "update" callback. + * @param {Object} target The target to be unscheduled. + */ unscheduleAllForTarget: function(target){ // explicit nullptr handling if (target == null){ @@ -724,10 +739,20 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ this.unscheduleUpdate(target); }, + /** + * Unschedules all scheduled callbacks from all targets including the system callbacks. + * You should NEVER call this method, unless you know what you are doing. + */ unscheduleAll: function(){ this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, + /** + * Unschedules all callbacks from all targets with a minimum priority. + * You should only call this with `PRIORITY_NON_SYSTEM_MIN` or higher. + * @param {Number} minPriority The minimum priority of selector to be unscheduled. Which means, all selectors which + * priority is higher than minPriority will be unscheduled. + */ unscheduleAllWithMinPriority: function(minPriority){ // Custom Selectors var i, element, arr = this._arrayForTimers; @@ -771,6 +796,11 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ } }, + /** Checks whether a callback for a given target is scheduled. + * @param {Function|String} key The callback to check. + * @param {Object} target The target of the callback. + * @return {Boolean} True if the specified callback is invoked, false if not. + */ isScheduled: function(key, target){ //key, target //selector, target diff --git a/cocos2d/core/base-nodes/CCAtlasNode.js b/cocos2d/core/base-nodes/CCAtlasNode.js index f7f47f2253..9fa71339d7 100644 --- a/cocos2d/core/base-nodes/CCAtlasNode.js +++ b/cocos2d/core/base-nodes/CCAtlasNode.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -EventTarget = require("../cocos2d/core/event/event-target"); +var EventTarget = cc.EventTarget; /** *

cc.AtlasNode is a subclass of ccsg.Node, it knows how to render a TextureAtlas object.

diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 794a68f6c2..f8edaef626 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -241,7 +241,7 @@ var Animation = cc.Class({ /** * Resumes an animation named name. If no name is supplied then resumes all paused animations that were started with this Animation. - * @method pause + * @method resume * @param {String} [name] - The animation to resumes, if not supplied then resumes all paused animations. */ resume: function (name) { diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index e3a62f1ac1..80c88ae3f1 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -26,7 +26,7 @@ /** * Audio Source. - * @class AudioScource + * @class AudioSource * @extends Component */ diff --git a/cocos2d/core/components/CCComponentInSG.js b/cocos2d/core/components/CCComponentInSG.js index 98516a32b8..98c69b5330 100644 --- a/cocos2d/core/components/CCComponentInSG.js +++ b/cocos2d/core/components/CCComponentInSG.js @@ -29,14 +29,16 @@ var ComponentInSG = cc.Class({ * @private */ this._sgNode = this._createSgNode(); - // retain immediately - // will be released in SceneGraphHelper.removeSgNode - this._sgNode.retain(); + if (this._sgNode) { + // retain immediately + // will be released in SceneGraphHelper.removeSgNode + this._sgNode.retain(); + } }, onLoad: function () { - var sgNode = this._sgNode; this._initSgNode(); + var sgNode = this._sgNode; this._appendSgNode(sgNode); if ( !this.node._sizeProvider ) { this.node._sizeProvider = sgNode; @@ -78,6 +80,10 @@ var ComponentInSG = cc.Class({ _removeSgNode: SceneGraphHelper.removeSgNode, _appendSgNode: function (sgNode) { + if ( !sgNode ) { + return; + } + var node = this.node; sgNode.setColor(node._color); diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 4273654923..679e281c41 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -21,12 +21,28 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - +/** + * Enum for sprite type + * @enum SpriteType + */ + /** + * @property {Number} SIMPLE + */ +/** + * @property {Number} SLICED + */ +/** + * @property {Number} TILED + */ +/** + * @property {Number} FILLED + */ var SpriteType = cc.Scale9Sprite.RenderingType; var FillType = cc.Scale9Sprite.FillType; /** * Sprite Size can track trimmed size, raw size or none + * @enum SizeMode */ var SizeMode = cc.Enum({ /** diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index e82d40309e..cd2fbf2495 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window['CocosEngine'] = cc.ENGINE_VERSION = 'Cocos Creator v0.7'; +window['CocosEngine'] = cc.ENGINE_VERSION = 'Cocos Creator v0.8.0'; /** *

diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index b91df6bbfb..f4a1d5f162 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -46,7 +46,7 @@ function _copyprop(name, source, target) { /** * This module provides some JavaScript utilities. * - * @module js + * @module cc.js */ var js = { diff --git a/cocos2d/core/platform/utils.js b/cocos2d/core/platform/utils.js index 18e86b7c0b..fb34510757 100644 --- a/cocos2d/core/platform/utils.js +++ b/cocos2d/core/platform/utils.js @@ -32,13 +32,22 @@ module.exports = { ); }, - callInNextTick: function (callback, p1, p2) { - if (callback) { - setTimeout(function () { - callback(p1, p2); - }, 1); + callInNextTick: CC_EDITOR ? + function (callback, p1, p2) { + if (callback) { + process.nextTick(function () { + callback(p1, p2); + }); + } + } + : + function (callback, p1, p2) { + if (callback) { + setTimeout(function () { + callback(p1, p2); + }, 0); + } } - } }; if (CC_DEV) { diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 7196b9b4f5..bdc817a57f 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -29,7 +29,7 @@ EventTarget = require("../cocos2d/core/event/event-target"); -/** +/* *

* A 9-slice sprite for cocos2d UI.
*
diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index f2bf1f13f5..22488525fa 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -203,6 +203,19 @@ if (CC_DEV) { return cc.js.array.copy; }); + + + Object.defineProperty(cc._ComponentInSG.prototype, 'visible', { + get: function () { + cc.warn('The "visible" property of %s is deprecated, use "enabled" instead please.', cc.js.getClassName(this)); + return this.enabled; + }, + set: function (value) { + var printWarning = this.visible; + this.enabled = value; + } + }); + function deprecateEnum (obj, oldPath, newPath, hasTypePrefixBefore) { hasTypePrefixBefore = hasTypePrefixBefore !== false; var enumDef = eval(newPath); @@ -233,14 +246,12 @@ if (CC_DEV) { deprecateEnum(cc.ParticleSystem, 'cc.ParticleSystem.MODE', 'cc.ParticleSystem.EmitterMode'); deprecateEnum(cc.ProgressTimer, 'cc.ProgressTimer.TYPE', 'cc.ProgressTimer.Type'); deprecateEnum(cc.game, 'cc.game.DEBUG_MODE', 'cc.DebugMode'); + deprecateEnum(cc, 'cc', 'cc.Texture2D.WrapMode', false); if (_ccsg.EditBox) { deprecateEnum(cc, 'cc.KEYBOARD_RETURNTYPE', '_ccsg.EditBox.KeyboardReturnType'); deprecateEnum(cc, 'cc.EDITBOX_INPUT_MODE', '_ccsg.EditBox.InputMode'); deprecateEnum(cc, 'cc.EDITBOX_INPUT_FLAG', '_ccsg.EditBox.InputFlag'); } - cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { - deprecateEnum(cc, 'cc', 'cc.Texture2D.WrapMode', false); - }); function markAsRemoved (ownerCtor, removedProps, ownerName) { ownerName = ownerName || js.getClassName(ownerCtor); @@ -254,7 +265,7 @@ if (CC_DEV) { function provideClearError (owner, obj) { var className = cc.js.getClassName(owner); - var Info = 'Sorry,' + className + '.%s is removed, please use %s instead.'; + var Info = 'Sorry, ' + className + '.%s is removed, please use %s instead.'; for (var prop in obj) { function define (prop, getset) { function accessor (newProp) { @@ -529,4 +540,22 @@ if (CC_DEV) { 'setFlippedY', 'isFlippedY' ]); + + // SPINE + + if (typeof sp !== 'undefined') { + deprecateEnum(sp, 'sp.ANIMATION_EVENT_TYPE', 'sp.AnimationEventType'); + js.obsolete(sp, 'SkeletonAnimation', 'Skeleton'); + provideClearError(sp.Skeleton, { + create: 'node.addComponent', + }); + provideClearError(sp.Skeleton.prototype, { + '*etDebugSlotsEnabled': 'debugSlots', + '*etDebugBonesEnabled': 'debugBones', + 'setDebugSolots': 'debugSlots', + 'setDebugBones': 'debugBones', + '*etTimeScale': 'timeScale', + }); + } } + diff --git a/extensions/spine/SGSkeleton.js b/extensions/spine/SGSkeleton.js new file mode 100644 index 0000000000..3d03cb320e --- /dev/null +++ b/extensions/spine/SGSkeleton.js @@ -0,0 +1,331 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2014 Shengxiang Chen (Nero Chan) + Copyright (c) 2015-2016 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. + ****************************************************************************/ + +var spine = sp.spine; + +sp._SGSkeleton = _ccsg.Node.extend({ + _skeleton: null, + _rootBone: null, + _timeScale: 1, + _debugSlots: false, + _debugBones: false, + _premultipliedAlpha: false, + _ownsSkeletonData: null, + _atlas: null, + _blendFunc: null, + + ctor: function(skeletonDataFile, atlasFile, scale) { + _ccsg.Node.prototype.ctor.call(this); + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; + + if(arguments.length === 0) + this.init(); + else + this.initWithArgs(skeletonDataFile, atlasFile, scale); + }, + + _createRenderCmd: function () { + if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + return new sp._SGSkeleton.CanvasRenderCmd(this); + else + return new sp._SGSkeleton.WebGLRenderCmd(this); + }, + + init: function () { + _ccsg.Node.prototype.init.call(this); + //this.setOpacityModifyRGB(true); + this._blendFunc.src = cc.ONE; + this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; + this.scheduleUpdate(); + }, + + /** + * Sets whether open debug slots. + * @param {boolean} enabled true to open, false to close. + */ + setDebugSlotsEnabled: function(enabled) { + this._debugSlots = enabled; + }, + + /** + * Gets whether open debug slots. + * @returns {boolean} true to open, false to close. + */ + getDebugSlotsEnabled: function() { + return this._debugSlots; + }, + + /** + * Sets whether open debug bones. + * @param {boolean} enabled + */ + setDebugBonesEnabled: function(enabled) { + this._debugBones = enabled; + }, + + /** + * Gets whether open debug bones. + * @returns {boolean} true to open, false to close. + */ + getDebugBonesEnabled: function() { + return this._debugBones; + }, + + /** + * Sets the time scale of sp._SGSkeleton. + * @param {Number} scale + */ + setTimeScale:function(scale){ + this._timeScale = scale; + }, + + getTimeScale: function(){ + return this._timeScale; + }, + + /** + * Initializes sp._SGSkeleton with Data. + * @param {spine.SkeletonData|String} skeletonDataFile + * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData + * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. + */ + initWithArgs: function (skeletonDataFile, atlasFile, scale) { + var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, + skeletonData, atlas, ownsSkeletonData; + + if (cc.js.isString(argSkeletonFile)) { + if (cc.js.isString(argAtlasFile)) { + var data = cc.loader.getRes(argAtlasFile); + sp._atlasLoader.setAtlasFile(argAtlasFile); + atlas = new spine.Atlas(data, sp._atlasLoader); + } else { + atlas = atlasFile; + } + scale = scale || 1 / cc.director.getContentScaleFactor(); + + var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); + var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); + skeletonJsonReader.scale = scale; + + var skeletonJson = cc.loader.getRes(argSkeletonFile); + skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); + atlas.dispose(skeletonJsonReader); + ownsSkeletonData = true; + } else { + skeletonData = skeletonDataFile; + ownsSkeletonData = atlasFile; + } + this.setSkeletonData(skeletonData, ownsSkeletonData); + this.init(); + }, + + /** + * Returns the bounding box of sp._SGSkeleton. + * @returns {cc.Rect} + */ + getBoundingBox: function () { + var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN; + var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [], + slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX; + + for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { + var slot = slots[i]; + if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) + continue; + var attachment = slot.attachment; + this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); + minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); + minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); + maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); + maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); + } + var position = this.getPosition(); + return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); + }, + + _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){ + var offset = self.offset, vertexIndex = sp.VERTEX_INDEX; + x += bone.worldX; + y += bone.worldY; + vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; + vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; + vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; + vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; + vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; + vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; + vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; + vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; + }, + + /** + * Computes the world SRT from the local SRT for each bone. + */ + updateWorldTransform: function () { + this._skeleton.updateWorldTransform(); + }, + + /** + * Sets the bones and slots to the setup pose. + */ + setToSetupPose: function () { + this._skeleton.setToSetupPose(); + }, + + /** + * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. + */ + setBonesToSetupPose: function () { + this._skeleton.setBonesToSetupPose(); + }, + + /** + * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. + */ + setSlotsToSetupPose: function () { + this._skeleton.setSlotsToSetupPose(); + }, + + /** + * Finds a bone by name. This does a string comparison for every bone. + * @param {String} boneName + * @returns {spine.Bone} + */ + findBone: function (boneName) { + return this._skeleton.findBone(boneName); + }, + + /** + * Finds a slot by name. This does a string comparison for every slot. + * @param {String} slotName + * @returns {spine.Slot} + */ + findSlot: function (slotName) { + return this._skeleton.findSlot(slotName); + }, + + /** + * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. + * @param {string} skinName + * @returns {spine.Skin} + */ + setSkin: function (skinName) { + return this._skeleton.setSkinByName(skinName); + }, + + /** + * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @param {String} slotName + * @param {String} attachmentName + * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} + */ + getAttachment: function (slotName, attachmentName) { + return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); + }, + + /** + * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @param {String} slotName + * @param {String} attachmentName + */ + setAttachment: function (slotName, attachmentName) { + this._skeleton.setAttachment(slotName, attachmentName); + }, + + /** + * Sets the premultiplied alpha value to sp._SGSkeleton. + * @param {Number} alpha + */ + setOpacityModifyRGB: function (alpha) { + this._premultipliedAlpha = alpha; + }, + + /** + * Returns whether to enable premultiplied alpha. + * @returns {boolean} + */ + isOpacityModifyRGB: function () { + return this._premultipliedAlpha; + }, + + /** + * Sets skeleton data to sp._SGSkeleton. + * @param {spine.SkeletonData} skeletonData + * @param {spine.SkeletonData} ownsSkeletonData + */ + setSkeletonData: function (skeletonData, ownsSkeletonData) { + if(skeletonData.width != null && skeletonData.height != null) + this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); + + this._skeleton = new spine.Skeleton(skeletonData); + this._skeleton.updateWorldTransform(); + this._rootBone = this._skeleton.getRootBone(); + this._ownsSkeletonData = ownsSkeletonData; + + this._renderCmd._createChildFormSkeletonData(); + }, + + /** + * Return the renderer of attachment. + * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment + * @returns {_ccsg.Node} + */ + getTextureAtlas: function (regionAttachment) { + return regionAttachment.rendererObject.page.rendererObject; + }, + + /** + * Returns the blendFunc of sp._SGSkeleton. + * @returns {cc.BlendFunc} + */ + getBlendFunc: function () { + return this._blendFunc; + }, + + /** + * Sets the blendFunc of sp._SGSkeleton. + * @param {cc.BlendFunc|Number} src + * @param {Number} [dst] + */ + 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; + } + }, + + /** + * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". + * @param {Number} dt Delta time since last update + */ + update: function (dt) { + this._skeleton.update(dt); + } +}); diff --git a/extensions/spine/SkeletonAnimation.js b/extensions/spine/SGSkeletonAnimation.js similarity index 80% rename from extensions/spine/SkeletonAnimation.js rename to extensions/spine/SGSkeletonAnimation.js index edfc167f02..05c9388e32 100644 --- a/extensions/spine/SkeletonAnimation.js +++ b/extensions/spine/SGSkeletonAnimation.js @@ -25,11 +25,8 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); - -/** - * @module sp - */ +var spine = sp.spine; +var animEventType = sp.AnimationEventType; sp._atlasPage_createTexture_webGL = function (self, path) { var texture = cc.textureCache.addImage(path); @@ -62,17 +59,6 @@ sp._atlasLoader = { } }; -/** - * The event type of spine skeleton animation. It contains event types: START(0), END(1), COMPLETE(2), EVENT(3). - * @constant - * @type {{START: number, END: number, COMPLETE: number, EVENT: number}} - */ -sp.ANIMATION_EVENT_TYPE = { - START: 0, - END: 1, - COMPLETE: 2, - EVENT: 3 -}; sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener){ this.startListener = startListener || null; @@ -93,15 +79,8 @@ sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) { state.rendererObject.onTrackEntryEvent(trackIndex, type, event, loopCount); }; -/** - * The skeleton animation of spine. It updates animation's state and skeleton's world transform. - * @class - * @extends sp.Skeleton - * @example - * var spineBoy = new sp.SkeletonAnimation('res/skeletons/spineboy.json', 'res/skeletons/spineboy.atlas'); - * this.addChild(spineBoy, 4); - */ -sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ + +sp._SGSkeletonAnimation = sp._SGSkeleton.extend({ _state: null, _target: null, _callback: null, @@ -113,17 +92,17 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ _eventListener: null, /** - * Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. + * Initializes a sp._SGSkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. * @override */ init: function () { - sp.Skeleton.prototype.init.call(this); + sp._SGSkeleton.prototype.init.call(this); this._ownsAnimationStateData = true; this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); }, /** - * Sets animation state data to sp.SkeletonAnimation. + * Sets animation state data to sp._SGSkeletonAnimation. * @param {spine.AnimationStateData} stateData */ setAnimationStateData: function (stateData) { @@ -147,7 +126,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ }, /** - * Sets event listener of sp.SkeletonAnimation. + * Sets event listener of sp._SGSkeletonAnimation. * @param {Object} target * @param {Function} callback */ @@ -275,19 +254,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ return; var listeners = entry.rendererObject; switch (type){ - case sp.ANIMATION_EVENT_TYPE.START: + case animEventType.START: if(listeners.startListener) listeners.startListener(traceIndex); break; - case sp.ANIMATION_EVENT_TYPE.END: + case animEventType.END: if(listeners.endListener) listeners.endListener(traceIndex); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case animEventType.COMPLETE: if(listeners.completeListener) listeners.completeListener(traceIndex, loopCount); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case animEventType.EVENT: if(listeners.eventListener) listeners.eventListener(traceIndex, event); break; @@ -296,19 +275,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ onAnimationStateEvent: function(trackIndex, type, event, loopCount) { switch(type){ - case sp.ANIMATION_EVENT_TYPE.START: + case animEventType.START: if(this._startListener) this._startListener(trackIndex); break; - case sp.ANIMATION_EVENT_TYPE.END: + case animEventType.END: if(this._endListener) this._endListener(trackIndex); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case animEventType.COMPLETE: if(this._completeListener) this._completeListener(trackIndex, loopCount); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case animEventType.EVENT: if(this._eventListener) this._eventListener(trackIndex, event); break; @@ -320,16 +299,16 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ }, _onAnimationStateStart: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0); + this._animationStateCallback(trackIndex, animEventType.START, null, 0); }, _onAnimationStateEnd: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.END, null, 0); + this._animationStateCallback(trackIndex, animEventType.END, null, 0); }, _onAnimationStateComplete: function (trackIndex, count) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, count); + this._animationStateCallback(trackIndex, animEventType.COMPLETE, null, count); }, _onAnimationStateEvent: function (trackIndex, event) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0); + this._animationStateCallback(trackIndex, animEventType.EVENT, event, 0); }, _animationStateCallback: function (trackIndex, type, event, loopCount) { this.onAnimationStateEvent(trackIndex, type, event, loopCount); @@ -338,15 +317,3 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ } } }); - -/** - * Creates a skeleton animation object. - * @deprecated since v3.0, please use new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale) instead. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - * @returns {sp.Skeleton} - */ -sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { - return new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale); -}; diff --git a/extensions/spine/SkeletonCanvasRenderCmd.js b/extensions/spine/SGSkeletonCanvasRenderCmd.js similarity index 96% rename from extensions/spine/SkeletonCanvasRenderCmd.js rename to extensions/spine/SGSkeletonCanvasRenderCmd.js index 5f33707590..c0914c65fa 100644 --- a/extensions/spine/SkeletonCanvasRenderCmd.js +++ b/extensions/spine/SGSkeletonCanvasRenderCmd.js @@ -22,19 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); +var spine = sp.spine; -/** - * @module sp - */ - -sp.Skeleton.CanvasRenderCmd = function(renderableObject){ +sp._SGSkeleton.CanvasRenderCmd = function(renderableObject){ _ccsg.Node.CanvasRenderCmd.call(this, renderableObject); this._needDraw = true; }; -var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); -proto.constructor = sp.Skeleton.CanvasRenderCmd; +var proto = sp._SGSkeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); +proto.constructor = sp._SGSkeleton.CanvasRenderCmd; proto.rendering = function (wrapper, scaleX, scaleY) { var node = this._node, i, n, slot, slotNode; diff --git a/extensions/spine/SkeletonWebGLRenderCmd.js b/extensions/spine/SGSkeletonWebGLRenderCmd.js similarity index 97% rename from extensions/spine/SkeletonWebGLRenderCmd.js rename to extensions/spine/SGSkeletonWebGLRenderCmd.js index 78a9363775..11355a9b92 100644 --- a/extensions/spine/SkeletonWebGLRenderCmd.js +++ b/extensions/spine/SGSkeletonWebGLRenderCmd.js @@ -22,21 +22,18 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); +var spine = sp.spine; -/** - * @module sp - */ -sp.Skeleton.WebGLRenderCmd = function (renderableObject) { +sp._SGSkeleton.WebGLRenderCmd = function (renderableObject) { _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); this._tmpQuad = new cc.V3F_C4B_T2F_Quad(); }; -var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); -proto.constructor = sp.Skeleton.WebGLRenderCmd; +var proto = sp._SGSkeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); +proto.constructor = sp._SGSkeleton.WebGLRenderCmd; proto.rendering = function (ctx) { var node = this._node, tmpQuad = this._tmpQuad; diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 8cadc1f618..149ec6ae15 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -1,8 +1,5 @@ /**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2014 Shengxiang Chen (Nero Chan) - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -25,383 +22,687 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); - /** * @module sp */ -/** - * The vertex index of spine. - * @constant - * @type {{X1: number, Y1: number, X2: number, Y2: number, X3: number, Y3: number, X4: number, Y4: number}} - */ -sp.VERTEX_INDEX = { - X1: 0, - Y1: 1, - X2: 2, - Y2: 3, - X3: 4, - Y3: 5, - X4: 6, - Y4: 7 -}; +var DefaultSkinsEnum = cc.Enum({ 'default': -1 }); +var DefaultAnimsEnum = cc.Enum({ '': 0 }); + +function setEnumAttr (obj, propName, enumDef) { + cc.Class.attr(obj, propName, { + type: 'Enum', + enumList: cc.Enum.getList(enumDef) + }); +} /** - * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. - * @constant - * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}} + * The skeleton of Spine
+ *
+ * (Skeleton has a reference to a SkeletonData and stores the state for skeleton instance, + * which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible.
+ * Multiple skeletons can use the same SkeletonData which includes all animations, skins, and attachments.)
+ * + * @class Skeleton + * @extends cc._ComponentInSG + * @constructor */ -sp.ATTACHMENT_TYPE = { - REGION: 0, - BOUNDING_BOX: 1, - MESH: 2, - SKINNED_MESH:3 -}; -/** - *

- * The skeleton of Spine.
- * Skeleton has a reference to a SkeletonData and stores the state for skeleton instance, - * which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible.
- * Multiple skeletons can use the same SkeletonData (which includes all animations, skins, and attachments).
- *

- * @class - * @extends _ccsg.Node - */ -sp.Skeleton = _ccsg.Node.extend(/** @lends sp.Skeleton# */{ - _skeleton: null, - _rootBone: null, - _timeScale: 1, - _debugSlots: false, - _debugBones: false, - _premultipliedAlpha: false, - _ownsSkeletonData: null, - _atlas: null, - _blendFunc: null, +// 由于 Spine 的 _sgNode 需要参数才能初始化, 所以这里的 _sgNode 不在构造函数中赋值, 每次访问前都要先判断一次是否初始化了 - /** - * The constructor of sp.Skeleton. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - */ - ctor:function(skeletonDataFile, atlasFile, scale){ - _ccsg.Node.prototype.ctor.call(this); - this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; - - if(arguments.length === 0) - this.init(); - else - this.initWithArgs(skeletonDataFile, atlasFile, scale); +sp.Skeleton = cc.Class({ + name: 'sp.Skeleton', + extends: cc._ComponentInSG, + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.others/Spine Skeleton', + //playOnFocus: true }, - _createRenderCmd:function () { - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new sp.Skeleton.CanvasRenderCmd(this); - else - return new sp.Skeleton.WebGLRenderCmd(this); - }, + properties: { - /** - * Initializes a sp.Skeleton. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. - */ - init: function () { - _ccsg.Node.prototype.init.call(this); - //this.setOpacityModifyRGB(true); - this._blendFunc.src = cc.ONE; - this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; - this.scheduleUpdate(); - }, + /** + * The skeleton data contains the skeleton information (bind pose bones, slots, draw order, + * attachments, skins, etc) and animations but does not hold any state. + * Multiple skeletons can share the same skeleton data. + * @property {sp.SkeletonData} skeletonData + */ + skeletonData: { + default: null, + type: sp.SkeletonData, + notify: function () { + this.defaultSkin = ''; + this.defaultAnimation = ''; + this._refresh(); + }, + }, - /** - * Sets whether open debug slots. - * @param {boolean} enable true to open, false to close. - */ - setDebugSolots:function(enable){ - this._debugSlots = enable; - }, + ///** + // * The url of atlas file. + // * @property {string} file + // */ + //atlasFile: { + // default: '', + // url: cc.TextAsset, + // notify: function () { + // this.defaultSkin = ''; + // this.defaultAnimation = ''; + // this._applyAsset(); + // }, + //}, - /** - * Sets whether open debug bones. - * @param {boolean} enable - */ - setDebugBones:function(enable){ - this._debugBones = enable; - }, + // 由于 spine 的 skin 是无法二次替换的,所以只能设置默认的 skin + /** + * The name of default skin. + * @property {string} defaultSkin + */ + defaultSkin: { + default: '', + visible: false + }, - /** - * Sets whether open debug slots. - * @param {boolean} enabled true to open, false to close. - */ - setDebugSlotsEnabled: function(enabled) { - this._debugSlots = enabled; - }, + /** + * The name of default animation. + * @property {string} defaultAnimation + */ + defaultAnimation: { + default: '', + visible: false + }, - /** - * Gets whether open debug slots. - * @returns {boolean} true to open, false to close. - */ - getDebugSlotsEnabled: function() { - return this._debugSlots; - }, + /** + * The name of current playing animation. + * @property {string} animation + */ + animation: { + get: function () { + var entry = this.getCurrent(0); + return (entry && entry.animation.name) || ""; + }, + set: function (value) { + this.defaultAnimation = value; + if (value) { + this.setAnimation(0, value, this.loop); + } + else { + this.clearTrack(0); + this.setToSetupPose(); + } + }, + visible: false + }, - /** - * Sets whether open debug bones. - * @param {boolean} enabled - */ - setDebugBonesEnabled: function(enabled) { - this._debugBones = enabled; - }, + /** + * @property {number} _defaultSkinIndex + */ + _defaultSkinIndex: { + get: function () { + if (this.skeletonData && this.defaultSkin) { + var skinsEnum = this.skeletonData.getSkinsEnum(); + if (skinsEnum) { + var skinIndex = skinsEnum[this.defaultSkin]; + if (skinIndex !== undefined) { + return skinIndex; + } + } + } + return 0; + }, + set: function (value) { + var skinsEnum; + if (this.skeletonData) { + skinsEnum = this.skeletonData.getSkinsEnum(); + } + if ( !skinsEnum ) { + return cc.error('Failed to set _defaultSkinIndex for "%s" because its skeletonData is invalid.', + this.name); + } + var skinName = skinsEnum[value]; + if (skinName !== undefined) { + this.defaultSkin = skinName; + if (CC_EDITOR && !cc.engine.isPlaying) { + this._refresh(); + } + } + else { + cc.error('Failed to set _defaultSkinIndex for "%s" because the index is out of range.', this.name); + } + }, + type: DefaultSkinsEnum, + visible: true, + displayName: "Default Skin" + }, - /** - * Gets whether open debug bones. - * @returns {boolean} true to open, false to close. - */ - getDebugBonesEnabled: function() { - return this._debugBones; - }, + // value of 0 represents no animation + _animationIndex: { + get: function () { + var animationName = (!CC_EDITOR || cc.engine.isPlaying) ? this.animation : this.defaultAnimation; + if (this.skeletonData && animationName) { + var animsEnum = this.skeletonData.getAnimsEnum(); + if (animsEnum) { + var animIndex = animsEnum[animationName]; + if (animIndex !== undefined) { + return animIndex; + } + } + } + return 0; + }, + set: function (value) { + if (value === 0) { + this.animation = ''; + return; + } + var animsEnum; + if (this.skeletonData) { + animsEnum = this.skeletonData.getAnimsEnum(); + } + if ( !animsEnum ) { + return cc.error('Failed to set _animationIndex for "%s" because its skeletonData is invalid.', this.name); + } + var animName = animsEnum[value]; + if (animName !== undefined) { + this.animation = animName; + } + else { + cc.error('Failed to set _animationIndex for "%s" because the index is out of range.', this.name); + } - /** - * Sets the time scale of sp.Skeleton. - * @param {Number} scale - */ - setTimeScale:function(scale){ - this._timeScale = scale; - }, + }, + type: DefaultAnimsEnum, + visible: true, + displayName: 'Animation' + }, - getTimeScale: function(){ - return this._timeScale; - }, + //// for inspector + //_animationList: { + // default: [], + // type: cc.String, + // serializable: false + //}, + // + //// for inspector + //_skinList: { + // default: [], + // type: cc.String, + // serializable: false + //}, - /** - * Initializes sp.Skeleton with Data. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - */ - initWithArgs: function (skeletonDataFile, atlasFile, scale) { - var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, - skeletonData, atlas, ownsSkeletonData; + /** + * @property {boolean} loop + * @default false + */ + loop: false, - if (cc.js.isString(argSkeletonFile)) { - if (cc.js.isString(argAtlasFile)) { - var data = cc.loader.getRes(argAtlasFile); - sp._atlasLoader.setAtlasFile(argAtlasFile); - atlas = new spine.Atlas(data, sp._atlasLoader); - } else { - atlas = atlasFile; + /** + * The time scale of this skeleton. + * @property {number} timeScale + * @default 1 + */ + timeScale: { + default: 1, + notify: function () { + if (this._sgNode) { + this._sgNode.setTimeScale(this.timeScale); + } } - scale = scale || 1 / cc.director.getContentScaleFactor(); + }, - var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); - var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); - skeletonJsonReader.scale = scale; + /** + * Indicates whether open debug slots. + * @property {boolean} debugSlots + * @default false + */ + debugSlots: { + default: false, + notify: function () { + if (this._sgNode) { + this._sgNode.setDebugSlotsEnabled(this.debugSlots); + } + }, + editorOnly: true, + }, - var skeletonJson = cc.loader.getRes(argSkeletonFile); - skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); - atlas.dispose(skeletonJsonReader); - ownsSkeletonData = true; - } else { - skeletonData = skeletonDataFile; - ownsSkeletonData = atlasFile; + /** + * Indicates whether open debug bones. + * @property {boolean} debugBones + * @default false + */ + debugBones: { + default: false, + notify: function () { + if (this._sgNode) { + this._sgNode.setDebugBonesEnabled(this.debugBones); + } + }, + editorOnly: true, } - this.setSkeletonData(skeletonData, ownsSkeletonData); - this.init(); }, - /** - * Returns the bounding box of sp.Skeleton. - * @returns {cc.Rect} - */ - getBoundingBox: function () { - var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN; - var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [], - slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX; + // IMPLEMENT - for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { - var slot = slots[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) - continue; - var attachment = slot.attachment; - this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); - minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); - maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); + onLoad: function () { + this._refresh(); + }, + + //onEnable: function () { + // this._super(); + //}, + + _createSgNode: function () { + if (this.skeletonData/* && self.atlasFile*/) { + var data = this.skeletonData.getRuntimeData(); + if (data) { + return new sp._SGSkeletonAnimation(data, null, this.skeletonData.scale); + } } - var position = this.getPosition(); - return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); + return null; }, - _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){ - var offset = self.offset, vertexIndex = sp.VERTEX_INDEX; - x += bone.worldX; - y += bone.worldY; - vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; - vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; - vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; - vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; - vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; - vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; - vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; - vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; + _initSgNode: function () { + var sgNode = this._sgNode; + sgNode.setTimeScale(this.timeScale); + //if (!CC_EDITOR) { + // function animationCallback (ccObj, trackIndex, type, event, loopCount) { + // var eventType = AnimEvents[type];3 + // var detail = { + // trackIndex: trackIndex + // }; + // if (type === sp.ANIMATION_EVENT_TYPE.COMPLETE) { + // detail.loopCount = loopCount; + // } + // else if (type === sp.ANIMATION_EVENT_TYPE.EVENT) { + // detail.event = event; + // } + // //Fire.log("[animationCallback] eventType: %s, time: '%s'", eventType, Fire.Time.time); + // self.entity.emit(eventType, detail); + // } + // sgNode.setAnimationListener(target, animationCallback); + //} + if (this.defaultSkin) { + try { + sgNode.setSkin(this.defaultSkin); + } + catch (e) { + cc._throw(e); + } + } + this.animation = this.defaultAnimation; + if (CC_EDITOR) { + sgNode.setDebugSlotsEnabled(this.debugSlots); + sgNode.setDebugBonesEnabled(this.debugBones); + } }, - /** - * Computes the world SRT from the local SRT for each bone. - */ - updateWorldTransform: function () { - this._skeleton.updateWorldTransform(); - }, + // RENDERER /** * Sets the bones and slots to the setup pose. + * @method setToSetupPose */ setToSetupPose: function () { - this._skeleton.setToSetupPose(); + if (this._sgNode) { + this._sgNode.setToSetupPose(); + } }, /** * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. + * @method setBonesToSetupPose */ setBonesToSetupPose: function () { - this._skeleton.setBonesToSetupPose(); - }, - - /** - * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. - */ - setSlotsToSetupPose: function () { - this._skeleton.setSlotsToSetupPose(); - }, - - /** - * Finds a bone by name. This does a string comparison for every bone. - * @param {String} boneName - * @returns {spine.Bone} - */ - findBone: function (boneName) { - return this._skeleton.findBone(boneName); - }, - - /** - * Finds a slot by name. This does a string comparison for every slot. - * @param {String} slotName - * @returns {spine.Slot} - */ - findSlot: function (slotName) { - return this._skeleton.findSlot(slotName); - }, - - /** - * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. - * @param {string} skinName - * @returns {spine.Skin} - */ - setSkin: function (skinName) { - return this._skeleton.setSkinByName(skinName); - }, - - /** - * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} - */ - getAttachment: function (slotName, attachmentName) { - return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); - }, - - /** - * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - */ - setAttachment: function (slotName, attachmentName) { - this._skeleton.setAttachment(slotName, attachmentName); - }, - - /** - * Sets the premultiplied alpha value to sp.Skeleton. - * @param {Number} alpha - */ - setOpacityModifyRGB: function (alpha) { - this._premultipliedAlpha = alpha; - }, - - /** - * Returns whether to enable premultiplied alpha. - * @returns {boolean} - */ - isOpacityModifyRGB: function () { - return this._premultipliedAlpha; - }, - - /** - * Sets skeleton data to sp.Skeleton. - * @param {spine.SkeletonData} skeletonData - * @param {spine.SkeletonData} ownsSkeletonData - */ - setSkeletonData: function (skeletonData, ownsSkeletonData) { - if(skeletonData.width != null && skeletonData.height != null) - this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); - - this._skeleton = new spine.Skeleton(skeletonData); - this._skeleton.updateWorldTransform(); - this._rootBone = this._skeleton.getRootBone(); - this._ownsSkeletonData = ownsSkeletonData; - - this._renderCmd._createChildFormSkeletonData(); - }, - - /** - * Return the renderer of attachment. - * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment - * @returns {_ccsg.Node} - */ - getTextureAtlas: function (regionAttachment) { - return regionAttachment.rendererObject.page.rendererObject; - }, - - /** - * Returns the blendFunc of sp.Skeleton. - * @returns {cc.BlendFunc} - */ - getBlendFunc: function () { - return this._blendFunc; - }, - - /** - * Sets the blendFunc of sp.Skeleton. - * @param {cc.BlendFunc|Number} src - * @param {Number} [dst] - */ - 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; + if (this._sgNode) { + this._sgNode.setBonesToSetupPose(); } }, /** - * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". - * @param {Number} dt Delta time since last update + * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. + * @method setSlotsToSetupPose */ - update: function (dt) { - this._skeleton.update(dt); + setSlotsToSetupPose: function () { + if (this._sgNode) { + this._sgNode.setSlotsToSetupPose(); + } + }, + + /** + * Finds a bone by name. This does a string comparison for every bone. + * @method findBone + * @param {string} boneName + * @return {spine.Bone} + */ + findBone: function (boneName) { + if (this._sgNode) { + return this._sgNode.findBone(boneName); + } + return null; + }, + + /** + * Finds a slot by name. This does a string comparison for every slot. + * @method findSlot + * @param {string} slotName + * @return {spine.Slot} + */ + findSlot: function (slotName) { + if (this._sgNode) { + return this._sgNode.findSlot(slotName); + } + return null; + }, + + /** + * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. + * @method setSkin + * @param {string} skinName + * @return {spine.Skin} + */ + setSkin: function (skinName) { + if (this._sgNode) { + return this._sgNode.setSkin(skinName); + } + return null; + }, + + /** + * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @method getAttachment + * @param {string} slotName + * @param {string} attachmentName + * @return {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} + */ + getAttachment: function (slotName, attachmentName) { + if (this._sgNode) { + return this._sgNode.getAttachment(slotName, attachmentName); + } + return null; + }, + + /** + * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @method setAttachment + * @param {string} slotName + * @param {string} attachmentName + */ + setAttachment: function (slotName, attachmentName) { + if (this._sgNode) { + this._sgNode.setAttachment(slotName, attachmentName); + } + }, + + /** + * Sets skeleton data to sp.Skeleton. + * @method setSkeletonData + * @param {spine.SkeletonData} skeletonData + * @param {spine.SkeletonData} ownsSkeletonData + */ + setSkeletonData: function (skeletonData, ownsSkeletonData) { + if (this._sgNode) { + this._sgNode.setSkeletonData(skeletonData, ownsSkeletonData); + } + }, + + ///** + // * Return the renderer of attachment. + // * @method getTextureAtlas + // * @param {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} regionAttachment + // * @return {_ccsg.Node} + // */ + //getTextureAtlas: function (regionAttachment) { + // if (this._sgNode) { + // this._sgNode.getTextureAtlas(regionAttachment); + // } + //}, + + // ANIMATION + + /** + * Sets animation state data. + * @method setAnimationStateData + * @param {spine.AnimationStateData} stateData + */ + setAnimationStateData: function (stateData) { + if (this._sgNode) { + return this._sgNode.setAnimationStateData(stateData); + } + }, + + /** + * Mix applies all keyframe values, interpolated for the specified time and mixed with the current values. + * @method setMix + * @param {string} fromAnimation + * @param {string} toAnimation + * @param {number} duration + */ + setMix: function (fromAnimation, toAnimation, duration) { + if (this._sgNode) { + this._sgNode.setMix(fromAnimation, toAnimation, duration); + } + }, + + /** + * Sets event listener. + * @method setAnimationListener + * @param {object} target + * @param {function} callback + */ + setAnimationListener: function (target, callback) { + if (this._sgNode) { + this._sgNode.setAnimationListener(target, callback); + } + }, + + /** + * Set the current animation. Any queued animations are cleared. + * @method setAnimation + * @param {number} trackIndex + * @param {string} name + * @param {boolean} loop + * @return {spine.TrackEntry} + */ + setAnimation: function (trackIndex, name, loop) { + if (this._sgNode) { + var res = this._sgNode.setAnimation(trackIndex, name, loop); + if (CC_EDITOR && !cc.engine.isPlaying) { + this._sample(); + this.clearTrack(trackIndex); + } + return res; + } + return null; + }, + + _sample: function () { + if (this._sgNode) { + this._sgNode.update(0); + } + }, + + /** + * Adds an animation to be played delay seconds after the current or last queued animation. + * @method addAnimation + * @param {number} trackIndex + * @param {string} name + * @param {boolean} loop + * @param {number} [delay=0] + * @return {spine.TrackEntry} + */ + addAnimation: function (trackIndex, name, loop, delay) { + if (this._sgNode) { + return this._sgNode.addAnimation(trackIndex, name, loop, delay); + } + return null; + }, + + /** + * Returns track entry by trackIndex. + * @method getCurrent + * @param trackIndex + * @return {spine.TrackEntry} + */ + getCurrent: function (trackIndex) { + if (this._sgNode) { + return this._sgNode.getCurrent(trackIndex); + } + return null; + }, + + /** + * Clears all tracks of animation state. + * @method clearTracks + */ + clearTracks: function () { + if (this._sgNode) { + this._sgNode.clearTracks(); + } + }, + + /** + * Clears track of animation state by trackIndex. + * @method clearTrack + * @param {number} trackIndex + */ + clearTrack: function (trackIndex) { + if (this._sgNode) { + this._sgNode.clearTrack(trackIndex); + if (CC_EDITOR && !cc.engine.isPlaying) { + this._sample(); + } + } + }, + + // update animation list for editor + _updateAnimEnum: CC_EDITOR && function () { + var animEnum; + if (this.skeletonData) { + animEnum = this.skeletonData.getAnimsEnum(); + } + // change enum + setEnumAttr(this, '_animationIndex', animEnum || DefaultAnimsEnum); + }, + // update skin list for editor + _updateSkinEnum: CC_EDITOR && function () { + var skinEnum; + if (this.skeletonData) { + skinEnum = this.skeletonData.getSkinsEnum(); + } + // change enum + setEnumAttr(this, '_defaultSkinIndex', skinEnum || DefaultSkinsEnum); + }, + // force refresh inspector + _refreshInspector: CC_EDITOR && function () { + var ga = Editor.Selection.curGlobalActivate(); + var inspecting = (ga && ga.id === this.node.uuid && ga.type === 'node'); + if (inspecting) { + Editor.Selection.unselect('node', this.node.uuid); + ga = Editor.Selection.curGlobalActivate(); + var id = this.node.uuid; + var inspectOther = (ga && ga.type === 'node' && ga.id); + if (inspectOther) { + setTimeout(function () { + Editor.Selection.select('node', id, false); + }, 200); + } + else { + Editor.Selection.select('node', id, false); + } + } + }, + + /** + * Set the start event listener. + * @method setStartListener + * @param {function} listener + */ + setStartListener: function (listener) { + if (this._sgNode) { + this._sgNode.setStartListener(listener); + } + }, + + /** + * Set the end event listener. + * @method setEndListener + * @param {function} listener + */ + setEndListener: function (listener) { + if (this._sgNode) { + this._sgNode.setEndListener(listener); + } + }, + + setCompleteListener: function (listener) { + if (this._sgNode) { + this._sgNode.setCompleteListener(listener); + } + }, + + setEventListener: function (listener) { + if (this._sgNode) { + this._sgNode.setEventListener(listener); + } + }, + + setTrackStartListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackStartListener(entry, listener); + } + }, + + setTrackEndListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackEndListener(entry, listener); + } + }, + + setTrackCompleteListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackCompleteListener(entry, listener); + } + }, + + setTrackEventListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackEventListener(entry, listener); + } + }, + + // + + getState: function () { + if (this._sgNode) { + return this._sgNode.getState(); + } + }, + + _refresh: function () { + var self = this; + + // discard exists sgNode + if (self._sgNode) { + if ( self.node._sizeProvider === self._sgNode ) { + self.node._sizeProvider = null; + } + self._removeSgNode(); + self._sgNode = null; + } + + // recreate sgNode... + var sgNode = self._sgNode = self._createSgNode(); + if (sgNode) { + sgNode.retain(); + self._initSgNode(); + self._appendSgNode(sgNode); + if ( !self.node._sizeProvider ) { + self.node._sizeProvider = sgNode; + } + } + + if (CC_EDITOR) { + // update inspector + self._updateAnimEnum(); + self._updateSkinEnum(); + self._refreshInspector(); + } } }); - -/** - * Creates a skeleton object. - * @deprecated since v3.0, please use new sp.Skeleton(skeletonDataFile, atlasFile, scale) instead. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - * @returns {sp.Skeleton} - */ -sp.Skeleton.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { - return new sp.Skeleton(skeletonDataFile, atlasFile, scale); -}; diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js new file mode 100644 index 0000000000..eb3be0c416 --- /dev/null +++ b/extensions/spine/SkeletonData.js @@ -0,0 +1,269 @@ +/**************************************************************************** + Copyright (c) 2016 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. + ****************************************************************************/ + +/** + * @module sp + */ + +// implements a simple texture loader like sp._atlasLoader +var TextureLoader = cc.Class({ + ctor: function () { + // {SkeletonData} + this.asset = arguments[0]; + }, + getTexture: function (line) { + //var name = cc.path.mainFileName(line); + //var textures = this.asset.textures; + //for (var i = 0; i < textures.length; i++) { + // var tex = textures[i]; + // if (tex.name === name) { + // return tex; + // } + //} + var urls = this.asset.textures; + for (var i = 0; i < urls.length; i++) { + var url = urls[i]; + if (url.endsWith(line)) { + return cc.textureCache.addImage(url); + } + } + return null; + }, + load: function (page, line, spAtlas) { + var texture = this.getTexture(line); + if (texture) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + page.rendererObject = new cc.TextureAtlas(texture, 128); + page.width = texture.getPixelWidth(); + page.height = texture.getPixelHeight(); + } + else { + page._texture = texture; + } + } + else { + cc.error('Failed to load spine atlas "$s"', line); + } + }, + unload: function (obj) { + //page.rendererObject.release(); + } +}); + +/** + * The skeleton data of spine. + * + * @class SkeletonData + * @extends cc.Asset + */ +var SkeletonData = cc.Class({ + name: 'sp.SkeletonData', + extends: cc.Asset, + + ctor: function () { + this.reset(); + }, + + properties: { + + _skeletonJson: null, + + /** + * @see http://en.esotericsoftware.com/spine-json-format + * @property {object} skeletonJson + */ + skeletonJson: { + get: function () { + return this._skeletonJson; + }, + set: function (value) { + this._skeletonJson = value; + this.reset(); + } + }, + + _atlasText: "", + + /** + * @property {string} atlasText + */ + atlasText: { + get: function () { + return this._atlasText; + }, + set: function (value) { + this._atlasText = value; + this.reset(); + } + }, + + /** + * @property {cc.Texture2D} textures + */ + textures: { + default: [], + url: [cc.Texture2D] + }, + + /** + * A scale can be specified on the JSON or binary loader which will scale the bone positions, + * image sizes, and animation translations. + * This can be useful when using different sized images than were used when designing the skeleton + * in Spine. For example, if using images that are half the size than were used in Spine, + * a scale of 0.5 can be used. This is commonly used for games that can run with either low or high + * resolution texture atlases. + * + * @see http://en.esotericsoftware.com/spine-using-runtimes#Scaling + * @property {number} scale + */ + scale: 1 + }, + + // PUBLIC + + createNode: function (callback) { + //var Url = require('fire-url'); + //var node = new cc.Node(Url.basenameNoExt(info.url)); + //var skeleton = node.addComponent(sp.Skeleton); + //skeleton.skeletonFile = info.url; + + var node = new cc.Node(this.name); + var skeleton = node.addComponent(sp.Skeleton); + skeleton.skeletonData = this; + + return callback(null, node); + }, + + reset: function () { + /** + * @property {spine.SkeletonData} _skeletonData + * @private + */ + this._skeletonCache = null; + /** + * @property {spine.Atlas} _atlasCache + * @private + */ + this._atlasCache = null; + if (CC_EDITOR) { + this._skinsEnum = null; + this._animsEnum = null; + } + }, + + /** + * Get the included SkeletonData used in spine runtime. + * @method getRuntimeData + * @param {boolean} [quiet=false] + * @return {spine.SkeletonData} + */ + getRuntimeData: function (quiet) { + if (this._skeletonCache) { + return this._skeletonCache; + } + + + if ( !(this.textures && this.textures.length > 0) ) { + if ( !quiet ) { + cc.error('Please re-import "%s" because its textures is not initialized! (This workflow will be improved in the future.)', this.name); + } + return null; + } + + var atlas = this._getAtlas(quiet); + if (! atlas) { + return null; + } + var attachmentLoader = new sp.spine.AtlasAttachmentLoader(atlas); + var jsonReader = new sp.spine.SkeletonJson(attachmentLoader); + jsonReader.scale = this.scale; + + var json = this.skeletonJson; + this._skeletonCache = jsonReader.readSkeletonData(json); + atlas.dispose(jsonReader); + + return this._skeletonCache; + }, + + // EDITOR + + getSkinsEnum: CC_EDITOR && function () { + if (this._skinsEnum) { + return this._skinsEnum; + } + var sd = this.getRuntimeData(true); + if (sd) { + var skins = sd.skins; + var enumDef = {}; + for (var i = 0; i < skins.length; i++) { + var name = skins[i].name; + enumDef[name] = i; + } + return this._skinsEnum = cc.Enum(enumDef); + } + return null; + }, + + getAnimsEnum: CC_EDITOR && function () { + if (this._animsEnum) { + return this._animsEnum; + } + var sd = this.getRuntimeData(true); + if (sd) { + var enumDef = { '': 0 }; + var anims = sd.animations; + for (var i = 0; i < anims.length; i++) { + var name = anims[i].name; + enumDef[name] = i + 1; + } + return this._animsEnum = cc.Enum(enumDef); + } + return null; + }, + + // PRIVATE + + /** + * @method _getAtlas + * @param {boolean} [quiet=false] + * @return {spine.Atlas} + * @private + */ + _getAtlas: function (quiet) { + if (this._atlasCache) { + return this._atlasCache; + } + + if ( !this.atlasText ) { + if ( !quiet ) { + cc.error('The atlas asset of "%s" is not exists!', this.name); + } + return null; + } + + return this._atlasCache = new sp.spine.Atlas(this.atlasText, new TextureLoader(this)); + } +}); + +sp.SkeletonData = module.exports = SkeletonData; diff --git a/extensions/spine/SpineAsset.js b/extensions/spine/SpineAsset.js deleted file mode 100644 index 9bb126170e..0000000000 --- a/extensions/spine/SpineAsset.js +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** - Copyright (c) 2016 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. - ****************************************************************************/ - -/** - * @module sp - */ - -/** - * The skeleton data of spine. - * @class SpineAsset - * @extends RawAsset - * @constructor - */ -var SpineAsset = cc.Class({ - name: 'sp.SpineAsset', - extends: cc.RawAsset, -}); - -sp.SpineAsset = module.exports = SpineAsset; diff --git a/extensions/spine/editor/spine-asset.html b/extensions/spine/editor/spine-asset.html new file mode 100644 index 0000000000..81cf2b6d84 --- /dev/null +++ b/extensions/spine/editor/spine-asset.html @@ -0,0 +1,44 @@ + + + + + + + + + diff --git a/extensions/spine/editor/spine-asset.png b/extensions/spine/editor/spine-asset.png new file mode 100644 index 0000000000..5ac8644d95 Binary files /dev/null and b/extensions/spine/editor/spine-asset.png differ diff --git a/extensions/spine/editor/spine-meta.js b/extensions/spine/editor/spine-meta.js new file mode 100644 index 0000000000..5478f38c6d --- /dev/null +++ b/extensions/spine/editor/spine-meta.js @@ -0,0 +1,182 @@ +'use strict'; + +/* + * Reference: + * http://en.esotericsoftware.com/spine-json-format + */ + +const Fs = require('fire-fs'); +const Path = require('fire-path'); +const Spine = require('../lib/spine'); + +const ATLAS_EXTS = ['.atlas', '.txt', '']; +const SPINE_ENCODING = { encoding: 'utf-8' }; + +const CustomAssetMeta = Editor.metas['custom-asset']; + +function searchAtlas (skeletonPath, callback) { + skeletonPath = Path.stripExt(skeletonPath); + + function next (index) { + var suffix = ATLAS_EXTS[index]; + var path = skeletonPath + suffix; + Fs.exists(path, exists => { + if (exists) { + return callback(null, path); + } + else if (index + 1 < ATLAS_EXTS.length) { + next(index + 1); + } + else { + callback(new Error(`Can not find ${skeletonPath + ATLAS_EXTS[0]}`)); + } + }); + } + + next(0); +} + +function loadAtlasText (skeletonPath, callback) { + searchAtlas(skeletonPath, (err, path) => { + if (err) { + return callback(err); + } + Fs.readFile(path, SPINE_ENCODING, (err, data) => { + callback(err, { + data: data, + atlasPath: path + }); + }); + }); +} + +// A dummy texture loader to record all textures in atlas +class TextureParser { + constructor (atlasPath) { + this.atlasPath = atlasPath; + // the loaded texture array + this.textures = []; + } + load (page, line) { + var name = Path.basename(line); + var base = Path.dirname(this.atlasPath); + var path = Path.resolve(base, name); + var uuid = Editor.assetdb.fspathToUuid(path); + if (!uuid) { + return; + } + //if (!uuid) { + // cc.error('Can not find texture "%s" for atlas "%s"', line, this.atlasPath); + // return; + //} + //var texture = Editor.serialize.asAsset(uuid); + var url = Editor.assetdb.uuidToUrl(uuid); + this.textures.push(url); + } + unload () {} +} + +class SpineMeta extends CustomAssetMeta { + constructor (assetdb) { + super(assetdb); + this.textures = []; + this.scale = 1; + } + + // HACK - for inspector + get texture () { + //return this.textures[0]; + return Editor.assetdb.uuidToUrl(this.textures[0]); + } + set texture (value) { + this.textures[0] = Editor.assetdb.urlToUuid(value); + //this.textures[0] = value; + } + + static version () { return '1.0.0'; } + static defaultType () { + return 'spine'; + } + + static validate (assetpath) { + // TODO - import as a folder named '***.spine' + var json; + var text = Fs.readFileSync(assetpath, 'utf8'); + var fastTest = text.slice(0, 30); + var maybe = ( fastTest.indexOf('slots') > 0 || + fastTest.indexOf('skins') > 0 || + fastTest.indexOf('events') > 0 || + fastTest.indexOf('animations') > 0 || + fastTest.indexOf('bones') > 0 || + fastTest.indexOf('skeleton') > 0 || + fastTest.indexOf('\"ik\"') > 0 + ); + if (maybe) { + try { + json = JSON.parse(text); + } + catch (e) { + return false; + } + return Array.isArray(json.bones); + } + return false; + } + + import (fspath, cb) { + var self = this; + + Fs.readFile(fspath, SPINE_ENCODING, (err, data) => { + if (err) { + return cb(err); + } + + var json; + try { + json = JSON.parse(data); + } + catch (e) { + return cb(e); + } + + var asset = new sp.SkeletonData(); + asset.name = Path.basenameNoExt(fspath); + asset.skeletonJson = json; + asset.scale = this.scale; + + loadAtlasText(fspath, (err, res) => { + if (err) { + return cb(err); + } + + // parse atlas textures + var textureParser = new TextureParser(res.atlasPath); + try { + new Spine.Atlas(res.data, textureParser); + } + catch (err) { + return cb(new Error(`Failed to load atlas file: "${res.atlasPath}". ${err.stack || err}`)); + } + if (textureParser.textures.length > 0) { + asset.textures = textureParser.textures; + this.textures = textureParser.textures.map(url => Editor.assetdb.urlToUuid(url)); + } + else { + asset.textures = this.textures.map(uuid => Editor.assetdb.uuidToUrl(uuid)); + } + + // + asset.atlasText = res.data; + + // + self._assetdb.saveAssetToLibrary(self.uuid, asset); + + cb(); + }); + }); + } +} + +SpineMeta.prototype.export = null; + +module.exports = SpineMeta; diff --git a/extensions/spine/index.js b/extensions/spine/index.js index 454cf2e0e6..a84678dc64 100644 --- a/extensions/spine/index.js +++ b/extensions/spine/index.js @@ -28,13 +28,79 @@ * @main sp */ +/* + * Reference: + * http://esotericsoftware.com/spine-runtime-terminology + * http://esotericsoftware.com/files/runtime-diagram.png + * http://en.esotericsoftware.com/spine-using-runtimes + */ + sp = {}; -if (!CC_JSB && (!CC_EDITOR || !Editor.isCoreLevel)) { - require('./Skeleton'); - require('./SkeletonCanvasRenderCmd'); - require('./SkeletonWebGLRenderCmd'); - require('./SkeletonAnimation'); -} +// The vertex index of spine. +sp.VERTEX_INDEX = { + X1: 0, + Y1: 1, + X2: 2, + Y2: 3, + X3: 4, + Y3: 5, + X4: 6, + Y4: 7 +}; -require('./SpineAsset'); +// The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. +sp.ATTACHMENT_TYPE = { + REGION: 0, + BOUNDING_BOX: 1, + MESH: 2, + SKINNED_MESH:3 +}; + +/** + * The event type of spine skeleton animation. + * @enum AnimationEventType + */ +sp.AnimationEventType = cc.Enum({ + /** + * @property {Number} START + */ + START: 0, + /** + * @property {Number} END + */ + END: 1, + /** + * @property {Number} COMPLETE + */ + COMPLETE: 2, + /** + * @property {Number} EVENT + */ + EVENT: 3 +}); + +/** + * @module sp + */ + +if (!CC_JSB && (!CC_EDITOR || !Editor.isCoreLevel)) { + + /** + * The official spine runtime. + * See http://en.esotericsoftware.com/spine-using-runtimes + * @property {object} spine + */ + sp.spine = require('./lib/spine'); + + require('./SGSkeleton'); + require('./SGSkeletonCanvasRenderCmd'); + require('./SGSkeletonWebGLRenderCmd'); + require('./SGSkeletonAnimation'); + + require('./SkeletonData'); + require('./Skeleton'); +} +else { + require('./SkeletonData'); +} diff --git a/extensions/spine/spine-exported.js b/extensions/spine/lib/spine.js similarity index 96% rename from extensions/spine/spine-exported.js rename to extensions/spine/lib/spine.js index 55ca291338..f4e875cf1c 100644 --- a/extensions/spine/spine-exported.js +++ b/extensions/spine/lib/spine.js @@ -1,10 +1,10 @@ /****************************************************************************** * Spine Runtimes Software License * Version 2.3 - * + * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. - * + * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal @@ -16,7 +16,7 @@ * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. - * + * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -178,6 +178,7 @@ spine.Slot.prototype = { attachment: null, attachmentVertices: [], setAttachment: function (attachment) { + if (this.attachment == attachment) return; this.attachment = attachment; this._attachmentTime = this.bone.skeleton.time; this.attachmentVertices.length = 0; @@ -195,11 +196,16 @@ spine.Slot.prototype = { this.b = data.b; this.a = data.a; - var slotDatas = this.bone.skeleton.data.slots; - for (var i = 0, n = slotDatas.length; i < n; i++) { - if (slotDatas[i] == data) { - this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); - break; + if (!data.attachmentName) + this.setAttachment(null); + else { + var slotDatas = this.bone.skeleton.data.slots; + for (var i = 0, n = slotDatas.length; i < n; i++) { + if (slotDatas[i] == data) { + this.attachment = null; + this.setAttachment(this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); + break; + } } } } @@ -220,12 +226,12 @@ spine.IkConstraint.prototype = { var target = this.target; var bones = this.bones; switch (bones.length) { - case 1: - spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); - break; - case 2: - spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); - break; + case 1: + spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); + break; + case 2: + spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); + break; } } }; @@ -412,7 +418,7 @@ spine.Curves.prototype = { var i = frameIndex * 19/*BEZIER_SIZE*/; var curves = this.curves; curves[i++] = 2/*BEZIER*/; - + var x = dfx, y = dfy; for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { curves[i] = x; @@ -1018,7 +1024,7 @@ spine.Skeleton = function (skeletonData) { this.slots.push(slot); this.drawOrder.push(slot); } - + this.ikConstraints = []; for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++) this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this)); @@ -1049,28 +1055,28 @@ spine.Skeleton.prototype = { var bones = this.bones; outer: - for (var i = 0, n = bones.length; i < n; i++) { - var bone = bones[i]; - var current = bone; - do { - for (var ii = 0; ii < ikConstraintsCount; ii++) { - var ikConstraint = ikConstraints[ii]; - var parent = ikConstraint.bones[0]; - var child= ikConstraint.bones[ikConstraint.bones.length - 1]; - while (true) { - if (current == child) { - boneCache[ii].push(bone); - boneCache[ii + 1].push(bone); - continue outer; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + var current = bone; + do { + for (var ii = 0; ii < ikConstraintsCount; ii++) { + var ikConstraint = ikConstraints[ii]; + var parent = ikConstraint.bones[0]; + var child= ikConstraint.bones[ikConstraint.bones.length - 1]; + while (true) { + if (current == child) { + boneCache[ii].push(bone); + boneCache[ii + 1].push(bone); + continue outer; + } + if (child == parent) break; + child = child.parent; } - if (child == parent) break; - child = child.parent; } - } - current = current.parent; - } while (current); - nonIkBones[nonIkBones.length] = bone; - } + current = current.parent; + } while (current); + nonIkBones[nonIkBones.length] = bone; + } }, /** Updates the world transform for each bone. */ updateWorldTransform: function () { @@ -1148,11 +1154,11 @@ spine.Skeleton.prototype = { }, setSkinByName: function (skinName) { var skin = this.data.findSkin(skinName); - if (!skin) throw new Error("Skin not found: " + skinName); + if (!skin) throw "Skin not found: " + skinName; this.setSkin(skin); }, - /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}. - * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was + /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}. + * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was * no old skin, each slot's setup mode attachment is attached from the new skin. * @param newSkin May be null. */ setSkin: function (newSkin) { @@ -1195,13 +1201,13 @@ spine.Skeleton.prototype = { var attachment = null; if (attachmentName) { attachment = this.getAttachmentBySlotIndex(i, attachmentName); - if (!attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName); + if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName; } slot.setAttachment(attachment); return; } } - throw new Error("Slot not found: " + slotName); + throw "Slot not found: " + slotName; }, /** @return May be null. */ findIkConstraint: function (ikConstraintName) { @@ -1489,9 +1495,9 @@ spine.AnimationStateData.prototype = { defaultMix: 0, setMixByName: function (fromName, toName, duration) { var from = this.skeletonData.findAnimation(fromName); - if (!from) throw new Error("Animation not found: " + fromName); + if (!from) throw "Animation not found: " + fromName; var to = this.skeletonData.findAnimation(toName); - if (!to) throw new Error("Animation not found: " + toName); + if (!to) throw "Animation not found: " + toName; this.setMix(from, to, duration); }, setMix: function (from, to, duration) { @@ -1599,7 +1605,7 @@ spine.AnimationState.prototype = { clearTracks: function () { for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); - this.tracks.length = 0; + this.tracks.length = 0; }, clearTrack: function (trackIndex) { if (trackIndex >= this.tracks.length) return; @@ -1644,7 +1650,7 @@ spine.AnimationState.prototype = { }, setAnimationByName: function (trackIndex, animationName, loop) { var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); + if (!animation) throw "Animation not found: " + animationName; return this.setAnimation(trackIndex, animation, loop); }, /** Set the current animation. Any queued animations are cleared. */ @@ -1658,7 +1664,7 @@ spine.AnimationState.prototype = { }, addAnimationByName: function (trackIndex, animationName, loop, delay) { var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); + if (!animation) throw "Animation not found: " + animationName; return this.addAnimation(trackIndex, animation, loop, delay); }, /** Adds an animation to be played delay seconds after the current or last queued animation. @@ -1719,7 +1725,7 @@ spine.SkeletonJson.prototype = { var parent = null; if (boneMap["parent"]) { parent = skeletonData.findBone(boneMap["parent"]); - if (!parent) throw new Error("Parent bone not found: " + boneMap["parent"]); + if (!parent) throw "Parent bone not found: " + boneMap["parent"]; } var boneData = new spine.BoneData(boneMap["name"], parent); boneData.length = (boneMap["length"] || 0) * this.scale; @@ -1743,12 +1749,12 @@ spine.SkeletonJson.prototype = { var bones = ikMap["bones"]; for (var ii = 0, nn = bones.length; ii < nn; ii++) { var bone = skeletonData.findBone(bones[ii]); - if (!bone) throw new Error("IK bone not found: " + bones[ii]); + if (!bone) throw "IK bone not found: " + bones[ii]; ikConstraintData.bones.push(bone); } ikConstraintData.target = skeletonData.findBone(ikMap["target"]); - if (!ikConstraintData.target) throw new Error("Target bone not found: " + ikMap["target"]); + if (!ikConstraintData.target) throw "Target bone not found: " + ikMap["target"]; ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1; ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1; @@ -1762,7 +1768,7 @@ spine.SkeletonJson.prototype = { for (var i = 0, n = slots.length; i < n; i++) { var slotMap = slots[i]; var boneData = skeletonData.findBone(slotMap["bone"]); - if (!boneData) throw new Error("Slot bone not found: " + slotMap["bone"]); + if (!boneData) throw "Slot bone not found: " + slotMap["bone"]; var slotData = new spine.SlotData(slotMap["name"], boneData); var color = slotMap["color"]; @@ -1774,7 +1780,7 @@ spine.SkeletonJson.prototype = { } slotData.attachmentName = slotMap["attachment"]; - slotData.blendMode = spine.AttachmentType[slotMap["blend"] || "normal"]; + slotData.blendMode = spine.BlendMode[slotMap["blend"] || "normal"]; skeletonData.slots.push(slotData); } @@ -1825,7 +1831,7 @@ spine.SkeletonJson.prototype = { var type = spine.AttachmentType[map["type"] || "region"]; var path = map["path"] || name; - + var scale = this.scale; if (type == spine.AttachmentType.region) { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); @@ -1852,7 +1858,7 @@ spine.SkeletonJson.prototype = { } else if (type == spine.AttachmentType.mesh) { var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (!mesh) return null; - mesh.path = path; + mesh.path = path; mesh.vertices = this.getFloatArray(map, "vertices", scale); mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = this.getFloatArray(map, "uvs", 1); @@ -1896,7 +1902,7 @@ spine.SkeletonJson.prototype = { mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = uvs; mesh.updateUVs(); - + color = map["color"]; if (color) { mesh.r = this.toColor(color, 0); @@ -1904,7 +1910,7 @@ spine.SkeletonJson.prototype = { mesh.b = this.toColor(color, 2); mesh.a = this.toColor(color, 3); } - + mesh.hullLength = (map["hull"] || 0) * 2; if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); mesh.width = (map["width"] || 0) * scale; @@ -1917,7 +1923,7 @@ spine.SkeletonJson.prototype = { attachment.vertices.push(vertices[i] * scale); return attachment; } - throw new Error("Unknown attachment type: " + type); + throw "Unknown attachment type: " + type; }, readAnimation: function (name, map, skeletonData) { var timelines = []; @@ -1964,7 +1970,7 @@ spine.SkeletonJson.prototype = { duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } else - throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); + throw "Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"; } } @@ -1972,7 +1978,7 @@ spine.SkeletonJson.prototype = { for (var boneName in bones) { if (!bones.hasOwnProperty(boneName)) continue; var boneIndex = skeletonData.findBoneIndex(boneName); - if (boneIndex == -1) throw new Error("Bone not found: " + boneName); + if (boneIndex == -1) throw "Bone not found: " + boneName; var boneMap = bones[boneName]; for (var timelineName in boneMap) { @@ -2030,7 +2036,7 @@ spine.SkeletonJson.prototype = { timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); } else - throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); + throw "Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"; } } @@ -2065,10 +2071,10 @@ spine.SkeletonJson.prototype = { var values = meshMap[meshName]; var timeline = new spine.FfdTimeline(values.length); var attachment = skin.getAttachment(slotIndex, meshName); - if (!attachment) throw new Error("FFD attachment not found: " + meshName); + if (!attachment) throw "FFD attachment not found: " + meshName; timeline.slotIndex = slotIndex; timeline.attachment = attachment; - + var isMesh = attachment.type == spine.AttachmentType.mesh; var vertexCount; if (isMesh) @@ -2106,7 +2112,7 @@ spine.SkeletonJson.prototype = { vertices[ii] += meshVertices[ii]; } } - + timeline.setFrame(frameIndex, valueMap["time"], vertices); this.readCurve(timeline, frameIndex, valueMap); frameIndex++; @@ -2138,7 +2144,7 @@ spine.SkeletonJson.prototype = { for (var ii = 0, nn = offsets.length; ii < nn; ii++) { var offsetMap = offsets[ii]; var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]); - if (slotIndex == -1) throw new Error("Slot not found: " + offsetMap["slot"]); + if (slotIndex == -1) throw "Slot not found: " + offsetMap["slot"]; // Collect unchanged items. while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; @@ -2165,7 +2171,7 @@ spine.SkeletonJson.prototype = { for (var i = 0, n = events.length; i < n; i++) { var eventMap = events[i]; var eventData = skeletonData.findEvent(eventMap["name"]); - if (!eventData) throw new Error("Event not found: " + eventMap["name"]); + if (!eventData) throw "Event not found: " + eventMap["name"]; var event = new spine.Event(eventData); event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue; event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue; @@ -2180,7 +2186,7 @@ spine.SkeletonJson.prototype = { }, readCurve: function (timeline, frameIndex, valueMap) { var curve = valueMap["curve"]; - if (!curve) + if (!curve) timeline.curves.setLinear(frameIndex); else if (curve == "stepped") timeline.curves.setStepped(frameIndex); @@ -2188,7 +2194,7 @@ spine.SkeletonJson.prototype = { timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); }, toColor: function (hexString, colorIndex) { - if (hexString.length != 8) throw new Error("Color hexidecimal length must be 8, recieved: " + hexString); + if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString; return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; }, getFloatArray: function (map, name, scale) { @@ -2408,14 +2414,14 @@ spine.AtlasReader.prototype = { readValue: function () { var line = this.readLine(); var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); + if (colon == -1) throw "Invalid line: " + line; return this.trim(line.substring(colon + 1)); }, /** Returns the number of tuple values read (1, 2 or 4). */ readTuple: function (tuple) { var line = this.readLine(); var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); + if (colon == -1) throw "Invalid line: " + line; var i = 0, lastMatch = colon + 1; for (; i < 3; i++) { var comma = line.indexOf(",", lastMatch); @@ -2434,7 +2440,7 @@ spine.AtlasAttachmentLoader = function (atlas) { spine.AtlasAttachmentLoader.prototype = { newRegionAttachment: function (skin, name, path) { var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")"); + if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")"; var attachment = new spine.RegionAttachment(name); attachment.rendererObject = region; attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate); @@ -2448,7 +2454,7 @@ spine.AtlasAttachmentLoader.prototype = { }, newMeshAttachment: function (skin, name, path) { var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")"); + if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")"; var attachment = new spine.MeshAttachment(name); attachment.rendererObject = region; attachment.regionU = region.u; @@ -2466,7 +2472,7 @@ spine.AtlasAttachmentLoader.prototype = { }, newSkinnedMeshAttachment: function (skin, name, path) { var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"); + if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"; var attachment = new spine.SkinnedMeshAttachment(name); attachment.rendererObject = region; attachment.regionU = region.u; @@ -2635,4 +2641,5 @@ spine.SkeletonBounds.prototype = { } }; +// TODO - delete me module.exports = spine; diff --git a/gulpfile.js b/gulpfile.js index 4a862aaf3b..d1c5ef54ab 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -23,11 +23,11 @@ paths = { '../../cocos2d/core/platform/CCLoader', '../../cocos2d/core/platform/CCLoaders', '../../cocos2d/core/event/event', - '../../extensions/spine/Skeleton', - '../../extensions/spine/SkeletonAnimation', - '../../extensions/spine/SkeletonCanvasRenderCmd', - '../../extensions/spine/SkeletonWebGLRenderCmd', - '../../extensions/spine/spine-exported', + '../../extensions/spine/SGSkeleton', + '../../extensions/spine/SGSkeletonAnimation', + '../../extensions/spine/SGSkeletonCanvasRenderCmd', + '../../extensions/spine/SGSkeletonWebGLRenderCmd', + '../../extensions/spine/lib/spine', ], test: { diff --git a/polyfill/index.js b/polyfill/index.js deleted file mode 100644 index 7cdd8d008f..0000000000 --- a/polyfill/index.js +++ /dev/null @@ -1,2 +0,0 @@ -require('./bind'); -require('./string'); diff --git a/predefine.js b/predefine.js index 67043f93df..6fee5427e2 100644 --- a/predefine.js +++ b/predefine.js @@ -43,9 +43,11 @@ if (CC_DEV) { cc._Test = {}; } -// predefine some modules for cocos +// polyfills +/* require('./polyfill/bind'); */ +require('./polyfill/string'); -require('./polyfill'); +// predefine some modules for cocos require('./cocos2d/core/platform/js'); require('./cocos2d/core/value-types'); require('./cocos2d/core/utils'); diff --git a/test/qunit/lib/polyfill-for-phantom.js b/test/qunit/lib/polyfill-for-phantom.js new file mode 100644 index 0000000000..2612406315 --- /dev/null +++ b/test/qunit/lib/polyfill-for-phantom.js @@ -0,0 +1,64 @@ +if (typeof CustomEvent === 'undefined') { + CustomEvent = function () { + + } +} + +if (typeof Set == 'undefined') { + // very simple polyfill + Set = function () { + this.values = []; + }; + Set.prototype.has = function (value) { + return this.values.indexOf(value) !== -1; + }; + Set.prototype.add = function (value) { + this.values.push(value); + }; +} + +// http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind.html +if (!Function.prototype.bind) { + Function.prototype.bind = function (oThis) { + //return function () {}; + if (typeof this !== 'function') { + // closest thing possible to the ECMAScript 5 + // internal IsCallable function + throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); + } + + var aArgs = Array.prototype.slice.call(arguments, 1), + fToBind = this, + fNOP = function () {}, + fBound = function () { + return fToBind.apply(this instanceof fNOP && oThis + ? this + : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + + // test this.prototype in case of native functions binding: + // - https://gist.github.com/jacomyal/4b7ae101a1cf6b985c60 + if (this.prototype) + fNOP.prototype = this.prototype; + fBound.prototype = new fNOP(); + + return fBound; + }; +} + +var isPhantomJS = window.navigator.userAgent.indexOf('PhantomJS') !== -1; +if (isPhantomJS) { + QUnit.config.notrycatch = true; + window.onerror = function (msg, url, line, column, error) { + if (error) { + console.error(error.stack); + } + else { + console.error(msg + '.\n' + url + ':' + line); + } + }; + // polyfill + var video = document.createElement("video"); + video.constructor.prototype.canPlayType = function () { return ''; }; +} diff --git a/test/qunit/lib/qunit-runner.html b/test/qunit/lib/qunit-runner.html index 0fcdfa3bfc..b05e359afe 100644 --- a/test/qunit/lib/qunit-runner.html +++ b/test/qunit/lib/qunit-runner.html @@ -18,23 +18,7 @@ qunit references: - +
diff --git a/test/qunit/unit/_polyfill-for-phantom.js b/test/qunit/unit/_polyfill-for-phantom.js deleted file mode 100644 index 09ebd1c9e8..0000000000 --- a/test/qunit/unit/_polyfill-for-phantom.js +++ /dev/null @@ -1,18 +0,0 @@ -if (typeof CustomEvent === 'undefined') { - CustomEvent = function () { - - } -} - -if (typeof Set == 'undefined') { - // very simple polyfill - Set = function () { - this.values = []; - }; - Set.prototype.has = function (value) { - return this.values.indexOf(value) !== -1; - }; - Set.prototype.add = function (value) { - this.values.push(value); - }; -} diff --git a/test/visual-tests/src/SpineTest/SpineTest.js b/test/visual-tests/src/SpineTest/SpineTest.js index c8a6353de2..6d9fdb96f2 100644 --- a/test/visual-tests/src/SpineTest/SpineTest.js +++ b/test/visual-tests/src/SpineTest/SpineTest.js @@ -74,7 +74,7 @@ var SpineTestLayer = BaseTestLayer.extend({ } }); -var customSkeletonAnimation = sp.SkeletonAnimation.extend({ +var customSkeletonAnimation = sp._SGSkeletonAnimation.extend({ ctor:function () { this._super.apply(this, arguments); } @@ -100,7 +100,7 @@ var SpineTestLayerNormal = SpineTestLayer.extend({ spineBoy = new customSkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); } else { - spineBoy = new sp.SkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); + spineBoy = new sp._SGSkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); } spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150)); spineBoy.setMix('walk', 'jump', 0.2); @@ -186,16 +186,16 @@ var SpineTestLayerNormal = SpineTestLayer.extend({ var entry = this._spineboy.getCurrent(); var animationName = (entry && entry.animation) ? entry.animation.name : 0; switch(type) { - case sp.ANIMATION_EVENT_TYPE.START: + case sp.AnimationEventType.START: cc.log(trackIndex + " start: " + animationName); break; - case sp.ANIMATION_EVENT_TYPE.END: + case sp.AnimationEventType.END: cc.log(trackIndex + " end:" + animationName); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case sp.AnimationEventType.EVENT: cc.log(trackIndex + " event: " + animationName); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case sp.AnimationEventType.COMPLETE: cc.log(trackIndex + " complete: " + animationName + "," + loopCount); if(this._flipped){ this._flipped = false; @@ -223,7 +223,7 @@ var SpineTestLayerFFD = SpineTestLayer.extend({ ctor: function(){ this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); - var skeletonNode = new sp.SkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); + var skeletonNode = new sp._SGSkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); skeletonNode.setAnimation(0, "walk", true); skeletonNode.setSkin("goblin"); @@ -267,7 +267,7 @@ var SpineTestPerformanceLayer = SpineTestLayer.extend({ event: cc.EventListener.TOUCH_ONE_BY_ONE, onTouchBegan: function(touch, event){ var pos = self.convertToNodeSpace(touch.getLocation()); - var skeletonNode = new sp.SkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); + var skeletonNode = new sp._SGSkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); skeletonNode.setAnimation(0, "walk", true); skeletonNode.setSkin("goblin");