(function outer(modules, cache, entry) { function newRequire(name, jumped) { var module = cache[name]; if (!module) { var moduleData = modules[name]; if (!moduleData) return; var exports = {}; module = cache[name] = { exports: exports }; moduleData[0]((function(x) { return newRequire(moduleData[1][x] || x); }), module, exports); } return module.exports; } for (var i = 0; i < entry.length; i++) newRequire(entry[i]); return newRequire; })({ 1: [ (function(require, module, exports) { module.exports = { 1001: "cocos2d: removeAction: Target not found", 1002: "cc.ActionManager.removeActionByTag(): an invalid tag", 1003: "cc.ActionManager.removeActionByTag(): target must be non-null", 1004: "cc.ActionManager.getActionByTag(): an invalid tag", 1005: "cocos2d : getActionByTag(tag = %s): Action not found", 1006: "[Action step]. override me", 1007: "[Action update]. override me", 1008: "cocos2d: FiniteTimeAction#reverse: Implement me", 1009: "cc.EaseElastic.reverse(): it should be overridden in subclass.", 1010: "cc.IntervalAction: reverse not implemented.", 1011: "cc.ActionInterval.setAmplitudeRate(): it should be overridden in subclass.", 1012: "cc.ActionInterval.getAmplitudeRate(): it should be overridden in subclass.", 1013: "The speed parameter error", 1014: "The repeat parameter error", 1015: "parameters should not be ending with null in Javascript", 1016: "cc.RotateTo.reverse(): it should be overridden in subclass.", 1019: "Failed to construct, Sequence construction needs two or more actions.", 1020: "Failed to construct, Spawn construction needs two or more actions.", 1021: "cc.Speed.initWithAction(): action must be non nil", 1022: "cc.Follow.initWithAction(): followedNode must be non nil", 1023: "cc.ActionEase.initWithAction(): action must be non nil", 1024: "Invalid configuration. It must at least have one control point", 1025: "cc.Sequence.initWithTwoActions(): arguments must all be non nil", 1026: "cc.RepeatForever.initWithAction(): action must be non null", 1027: "cc.Spawn.initWithTwoActions(): arguments must all be non null", 1028: "cc.ReverseTime.initWithAction(): action must be non null", 1029: "cc.ReverseTime.initWithAction(): the action was already passed in.", 1030: "cc.Animate.initWithAnimation(): animation must be non-NULL", 1031: "Illegal parameter get passed in cc.tween: %s.", 1100: "Expected 'data' dict, but not found. Config file: %s", 1101: "Please load the resource first : %s", 1200: "cocos2d: Director: Error in gettimeofday", 1201: "cocos2d: Director: unrecognized projection", 1203: "cocos2d: Director: Error in gettimeofday", 1204: "running scene should not null", 1205: "the scene should not null", 1206: "loadScene: The scene index to load (%s) is out of range.", 1207: "loadScene: Unknown name type to load: '%s'", 1208: "loadScene: Failed to load scene '%s' because '%s' is already being loaded.", 1209: "loadScene: Can not load the scene '%s' because it was not in the build settings before playing.", 1210: "Failed to preload '%s', %s", 1211: "loadScene: The scene index to load (%s) is out of range.", 1212: "loadScene: Unknown name type to load: '%s'", 1213: "loadScene: Failed to load scene '%s' because '%s' is already loading", 1214: "loadScene: Can not load the scene '%s' because it was not in the build settings before playing.", 1215: "Failed to preload '%s', %s", 1216: "Director.runSceneImmediate: scene is not valid", 1300: "element type is wrong!", 1400: "'%s' is deprecated, please use '%s' instead.", 1404: "cc.spriteFrameCache is removed, please use cc.loader to load and cache sprite frames of atlas format.", 1405: "The '%s' has been removed, please use '%s' instead.", 1406: "'%s.%s' is removed", 1408: "'%s' is not support in the '%s', please use '%s' instead.", 1502: "cc.scheduler.scheduleCallbackForTarget(): target should be non-null.", 1503: "cc.Scheduler.pauseTarget():target should be non-null", 1504: "cc.Scheduler.resumeTarget():target should be non-null", 1505: "cc.Scheduler.isTargetPaused():target should be non-null", 1506: "warning: you CANNOT change update priority in scheduled function", 1507: 'CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %s to %s"', 1508: "Argument callback must not be empty", 1509: "Argument target must be non-nullptr", 1510: "cc.Scheduler: Illegal target which doesn't have uuid or instanceId.", 1511: "cc.Scheduler: pause state of the scheduled task doesn't match the element pause state in Scheduler, the given paused state will be ignored.", 1513: "cc.Scheduler: scheduler stopped using `__instanceId` as id since v2.0, you should do scheduler.enableForTarget(target) before all scheduler API usage on target", 1605: "child already added. It can't be added again", 1606: "child must be non-null", 1610: "cocos2d: removeChildByTag(tag = %s): child not found!", 1612: "cc.Node.stopActionBy(): argument tag an invalid tag", 1613: "cc.Node.getActionByTag(): argument tag is an invalid tag", 1617: "child must be non-null", 1618: "cc.Node.runAction(): action must be non-null", 1619: "callback function must be non-null", 1620: "interval must be positive", 1623: "Set '%s' to normal node (not persist root node).", 1624: "Replacing with the same sgNode", 1625: "The replacement sgNode should not contain any child.", 1626: "Should not set alpha via 'color', set 'opacity' please.", 1627: "Not support for asynchronous creating node in SG", 1632: "Node name can not include '/'.", 1633: "Internal error, should not remove unknown node from parent.", 1634: "addChild: The child to add must be instance of cc.Node, not %s.", 1635: "reorderChild: this child is not in children list.", 1636: "Node's zIndex value can't be greater than cc.macro.MAX_ZINDEX, setting to the maximum value", 1637: "Node's zIndex value can't be smaller than cc.macro.MIN_ZINDEX, setting to the minimum value", 1638: "Private node's zIndex can't be set, it will keep cc.macro.MIN_ZINDEX as its value", 1639: "cc.Action is deprecated, please use cc.Tween instead", 1800: "cc._EventListenerKeyboard.checkAvailable(): Invalid EventListenerKeyboard!", 1801: "cc._EventListenerTouchOneByOne.checkAvailable(): Invalid EventListenerTouchOneByOne!", 1802: "cc._EventListenerTouchAllAtOnce.checkAvailable(): Invalid EventListenerTouchAllAtOnce!", 1803: "cc._EventListenerAcceleration.checkAvailable(): _onAccelerationEvent must be non-nil", 1900: "Invalid parameter.", 2e3: "Don't call this method if the event is for touch.", 2200: "Design resolution not valid", 2201: "should set resolutionPolicy", 2300: "The touches is more than MAX_TOUCHES, nUnusedIndex = %s", 2400: "WebGL error %s", 2602: "cc.Sprite.setDisplayFrameWithAnimationName(): Frame not found", 2603: "cc.Sprite.setDisplayFrameWithAnimationName(): Invalid frame index", 2606: "cc.Sprite.initWithSpriteFrame(): spriteFrame should be non-null", 2607: "cc.Sprite.initWithSpriteFrameName(): spriteFrameName should be non-null", 2608: "%s is null, please check.", 2609: "cc.Sprite.initWithFile(): filename should be non-null", 2610: "cc.Sprite.setDisplayFrameWithAnimationName(): animationName must be non-null", 2614: "cc.Sprite.addChild(): child should be non-null", 2616: "cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children", 2617: "cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children", 2618: "cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children", 2619: "cc.SpriteBatchNode.addChild(): cc.Sprite is not using the same texture", 2623: "cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null", 2625: "too many tiles, only 16384 tiles will be show", 2626: "Unrecognized fill type in bar fill", 2627: "Can not generate quad", 2628: "%s does not exist", 2712: "Invalid spriteFrameName", 3005: "cocos2d: '%s' id=%s %s x %s", 3006: "cocos2d: '%s' id= HTMLCanvasElement %s x %s", 3007: "cocos2d: TextureCache dumpDebugInfo: %s textures, HTMLCanvasElement for %s KB (%s MB)", 3103: "cc.Texture.addImage(): path should be non-null", 3112: "cc.Texture.addImage(): path should be non-null", 3113: "NSInternalInconsistencyException", 3116: "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures", 3117: "Mimpap texture only works in POT textures", 3119: "Lazy init texture with image element failed due to image loading failure: %s", 3120: "Loading texture with unsupported type: '%s'. Add '%s' into 'cc.macro.SUPPORT_TEXTURE_FORMATS' please.", 3121: "Can't find a texture format supported by the current platform! Please add a fallback format in the editor.", 3300: "Rect width exceeds maximum margin: %s", 3400: "Rect height exceeds maximum margin: %s", 3401: "Set texture with a url of image is not supported anymore. Please use cc.assetManager.loadRemote to load a texture first.", 3500: "0 priority is forbidden for fixed priority since it's used for scene graph based priority.", 3501: "Invalid listener type!", 3502: "Can't set fixed priority with scene graph based listener.", 3503: "Invalid parameters.", 3504: "listener must be a cc.EventListener object when adding a fixed priority listener", 3505: "The listener has been registered, please don't register it again.", 3506: "Unsupported listener target.", 3507: "Invalid scene graph priority!", 3508: "If program goes here, there should be event in dispatch.", 3509: "_inDispatch should be 1 here.", 3510: "%s's scene graph node not contains in the parent's children", 3511: "event is undefined", 3600: "cc.Class will automatically call super constructor of %s, you should not call it manually.", 3601: "The editor property 'playOnFocus' should be used with 'executeInEditMode' in class '%s'", 3602: "Unknown editor property '%s' in class '%s'.", 3603: "Use 'cc.Float' or 'cc.Integer' instead of 'cc.Number' please.", 3604: "Can only indicate one type attribute for %s.", 3605: "The default value of %s is not instance of %s.", 3606: "No needs to indicate the '%s' attribute for %s, which its default value is type of %s.", 3607: "The default value of %s must be an empty string.", 3608: "The type of %s must be cc.String, not String.", 3609: "The type of %s must be cc.Boolean, not Boolean.", 3610: "The type of %s must be cc.Float or cc.Integer, not Number.", 3611: "Can not indicate the '%s' attribute for %s, which its default value is type of %s.", 3612: "%s Just set the default value to 'new %s()' and it will be handled properly.", 3613: "'No need to use 'serializable: false' or 'editorOnly: true' for the getter of '%s.%s', every getter is actually non-serialized.", 3614: "Should not define constructor for cc.Component %s.", 3615: "Each script can have at most one Component.", 3616: "Should not specify class name %s for Component which defines in project.", 3617: "Can not instantiate CCClass '%s' with arguments.", 3618: "ctor of '%s' can not be another CCClass", 3619: "ctor of '%s' must be function type", 3620: "this._super declared in '%s.%s' but no super method defined", 3621: "Unknown type of %s.%s, maybe you want is '%s'.", 3622: "Unknown type of %s.%s, property should be defined in 'properties' or 'ctor'", 3623: "Can not use 'editor' attribute, '%s' not inherits from Components.", 3624: "'%s' overrided '%s' but '%s' is defined as 'false' so the super method will not be called. You can set '%s' to null to disable this warning.", 3625: "[isChildClassOf] superclass should be function type, not", 3626: "Can't remove '%s' because '%s' depends on it.", 3627: "Should not add renderer component (%s) to a Canvas node.", 3628: "Should not add %s to a node which size is already used by its other component.", 3633: "Properties function of '%s' should return an object!", 3634: "Disallow to use '.' in property name", 3635: "Default array must be empty, set default value of %s.%s to [], and initialize in 'onLoad' or 'ctor' please. (just like 'this.%s = [...];')", 3636: "Do not set default value to non-empty object, unless the object defines its own 'clone' function. Set default value of %s.%s to null or {}, and initialize in 'onLoad' or 'ctor' please. (just like 'this.%s = {foo: bar};')", 3637: "Can not declare %s.%s, it is already defined in the prototype of %s", 3638: "'%s': the getter of '%s' is already defined!", 3639: "Can not apply the specified attribute to the getter of '%s.%s', attribute index: %s", 3640: "'%s': the setter of '%s' is already defined!", 3641: "Can not construct %s because it contains object property.", 3642: "Cannot define %s.%s because static member name can not be '%s'.", 3643: "Can not define a member called 'constructor' in the class '%s', please use 'ctor' instead.", 3644: "Please define 'type' parameter of %s.%s as the actual constructor.", 3645: "Please define 'type' parameter of %s.%s as the constructor of %s.", 3646: "Unknown 'type' parameter of %s.%s\uff1a%s", 3647: "The length of range array must be equal or greater than 2", 3648: "Can not declare %s.%s method, it is already defined in the properties of %s.", 3649: "CCClass %s have conflict between its ctor and __ctor__.", 3651: 'Can not call `_super` or `prototype.ctor` in ES6 Classes "%s", use `super` instead please.', 3652: "Failed to `new %s()` under the hood, %s\nIt is used for getting default values declared in TypeScript in the first place.\nPlease ensure the constructor can be called during the script's initialization.", 3653: 'Please do not specifiy "default" attribute in decorator of "%s" property in "%s" class. \nDefault value must be initialized at their declaration:\n \n// Before:\n@property({\n type: cc.SpriteFrame\n default: null // <--\n})\nmyProp;\n// After:\n@property({\n type: cc.SpriteFrame\n})\nmyProp = null; // <--', 3654: 'Please specifiy a default value for "%s.%s" at its declaration:\n \n// Before:\n@property(...)\nmyProp;\n// After:\n@property(...)\nmyProp = 0;', 3655: 'Can not specifiy "get" or "set" attribute in decorator for "%s" property in "%s" class. \nPlease use:\n \n@property(...)\nget %s () {\n ...\n}\n@property\nset %s (value) {\n ...\n}', 3700: "internal error: _prefab is undefined", 3701: "Failed to load prefab asset for node '%s'", 3800: "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.", 3801: "The node can not be made persist because it's not under root node.", 3802: "The node can not be made persist because it's not in current scene.", 3803: "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.", 3804: "getComponent: Type must be non-nil", 3805: "Can't add component '%s' because %s already contains the same component.", 3806: "Can't add component '%s' to %s because it conflicts with the existing '%s' derived component.", 3807: "addComponent: Failed to get class '%s'", 3808: "addComponent: Should not add component ('%s') when the scripts are still loading.", 3809: "addComponent: The component to add must be a constructor", 3810: "addComponent: The component to add must be child class of cc.Component", 3811: "_addComponentAt: The component to add must be a constructor", 3812: "_addComponentAt: Index out of range", 3813: "removeComponent: Component must be non-nil", 3814: "Argument must be non-nil", 3815: "Component not owned by this entity", 3816: "Node '%s' is already activating", 3817: "Sorry, the component of '%s' which with an index of %s is corrupted! It has been removed.", 3818: "Failed to read or parse project.json", 3819: "Warning: target element is not a DIV or CANVAS", 3820: "The renderer doesn't support the renderMode %s", 3821: "Cannot change hierarchy while activating or deactivating the parent.", 3900: "Invalid clip to add", 3901: "Invalid clip to remove", 3902: "clip is defaultClip, set force to true to force remove clip and animation state", 3903: "animation state is playing, set force to true to force stop and remove clip and animation state", 3904: "motion path of target [%s] in prop [%s] frame [%s] is not valid", 3905: "sprite frames must be an Array.", 3906: "Can't find easing type [%s]", 3907: "animator not added or already removed", 3912: "already-playing", 4003: "Label font size can't be shirnked less than 0!", 4004: "force notify all fonts loaded!", 4011: "Property spriteFrame of Font '%s' is invalid. Using system font instead.", 4012: "The texture of Font '%s' must be already loaded on JSB. Using system font instead.", 4013: "Sorry, lineHeight of system font not supported on JSB.", 4200: "MaskType: IMAGE_STENCIL only support WebGL mode.", 4201: "The alphaThreshold invalid in Canvas Mode.", 4202: "The inverted invalid in Canvas Mode.", 4300: "can not found the %s page.", 4400: "Invalid RichText img tag! The sprite frame name can't be found in the ImageAtlas!", 4600: "Script attached to '%s' is missing or invalid.", 4700: "The dom control is not created!", 4800: "unknown asset type", 4901: "loadRes: should not specify the extname in %s %s", 4902: "No need to release non-cached asset.", 4914: "Resources url '%s' does not exist.", 4915: "Pack indices and data do not match in size", 4916: "Failed to download package for %s", 4921: "Invalid pipe or invalid index provided!", 4922: "The pipe to be inserted is already in the pipeline!", 4923: "Uuid Loader: Parse asset [ %s ] failed : %s", 4924: "JSON Loader: Input item doesn't contain string content", 4925: "Uuid Loader: Deserialize asset [ %s ] failed : %s", 4926: "Audio Downloader: no web audio context.", 4927: "Audio Downloader: audio not supported on this browser!", 4928: "Load %s failed!", 4929: "Load Webp ( %s ) failed", 4930: "Load image ( %s ) failed", 4932: 'Since v1.10, for any atlas ("%s") in the "resources" directory, it is not possible to find the contained SpriteFrames via `loadRes`, `getRes` or `releaseRes`. Load the SpriteAtlas first and then use `spriteAtlas.getSpriteFrame(name)` instead please.', 4933: "Download Font [ %s ] failed, using Arial or system default font instead", 5e3: "object already destroyed", 5001: "object not yet destroyed", 5100: "Not a plist file!", 5200: "Warning: localStorage isn't enabled. Please confirm browser cookie or privacy option", 5201: "browser don't support web audio", 5202: "This feature supports WebGL render mode only.", 5300: "Type of target to deserialize not matched with data: target is %s, data is %s", 5301: "Can not find script '%s'", 5302: "Can not find class '%s'", 5303: "Failed to deserialize %s, missing _deserialize function.", 5304: "Unable to deserialize version %s data.", 5402: "cc.js.addon called on non-object:", 5403: "cc.js.mixin: arguments must be type object:", 5404: "The base class to extend from must be non-nil", 5405: "The class to extend must be non-nil", 5406: "Class should be extended before assigning any prototype members.", 5500: "'notify' can not be used in 'get/set' !", 5501: "'notify' must be used with 'default' !", 5507: "The 'default' attribute of '%s.%s' must be an array", 5508: "Invalid type of %s.%s", 5510: "The 'type' attribute of '%s.%s' can not be 'Number', use cc.Float or cc.Integer instead please.", 5511: "The 'type' attribute of '%s.%s' is undefined when loading script", 5512: "Can not serialize '%s.%s' because the specified type is anonymous, please provide a class name or set the 'serializable' attribute of '%s.%s' to 'false'.", 5513: "The 'default' value of '%s.%s' should not be used with a 'get' function.", 5514: "The 'default' value of '%s.%s' should not be used with a 'set' function.", 5515: "The 'default' value of '%s.%s' can not be an constructor. Set default to null please.", 5516: "Property '%s.%s' must define at least one of 'default', 'get' or 'set'.", 5517: "'%s.%s' hides inherited property '%s.%s'. To make the current property override that implementation, add the `override: true` attribute please.", 5601: "Can not get current scene.", 5602: "Scene is destroyed", 5603: "reference node is destroyed", 5700: "no %s or %s on %s", 5800: "%s.lerp not yet implemented.", 5801: "%s.clone not yet implemented.", 5802: "%s.equals not yet implemented.", 5900: "MotionStreak only support WebGL mode.", 5901: "cc.MotionStreak.getOpacity has not been supported.", 5902: "cc.MotionStreak.setOpacity has not been supported.", 6e3: "Custom should not be false if file is not specified.", 6001: "The new %s must not be NaN", 6017: "Incomplete or corrupt PNG file", 6018: "Invalid filter algorithm: %s", 6019: "Invalid byte order value.", 6020: "You forgot your towel!", 6021: "Unknown Field Tag: %s", 6022: "Too many bits requested", 6023: "No bits requested", 6024: "Cannot recover from missing StripByteCounts", 6025: "Cannot handle sub-byte bits per sample", 6026: "Cannot handle sub-byte bits per pixel", 6027: "Palette image missing color map", 6028: "Unknown Photometric Interpretation: %s", 6029: "Unkown error", 6030: "cc.ParticleSystem: error decoding or ungzipping textureImageData in plist '%s'", 6031: "cc.ParticleSystem: unknown image format with Data in plist %s", 6032: "cc.ParticleSystem.initWithDictionary() : error loading the texture in plist '%s'", 6400: "asset.url is not usable in core process", 6402: "AssetLibrary has already been initialized!", 6500: "Widget target must be one of the parent nodes of it", 6600: "collider not added or already removed", 6601: "Can't find testFunc for (%s, $s).", 6700: "Can't init canvas '%s' because it conflicts with the existing '%s', the scene should only have one active canvas at the same time.", 6800: "Callback of event must be non-nil", 6801: "The message must be provided", 6900: "The thing you want to instantiate must be an object", 6901: "The thing you want to instantiate is nil", 6902: "The thing you want to instantiate is destroyed", 6903: "The instantiate method for given asset do not implemented", 6904: "Can not instantiate array", 6905: "Can not instantiate DOM element", 7100: "%s already defined in Enum.", 7101: "Sorry, 'cc.Enum' not available on this platform, please report this error here: https://github.com/cocos-creator/engine/issues/new", 7200: "Method 'initWithTMXFile' is no effect now, please set property 'tmxAsset' instead.", 7201: "Method 'initWithXML' is no effect now, please set property 'tmxAsset' instead.", 7202: "Add component TiledLayer into node failed.", 7203: "Property 'mapLoaded' is unused now. Please write the logic to the callback 'start'.", 7210: "TMX Hexa zOrder not supported", 7211: "TMX invalid value", 7215: "cocos2d: Warning: TMX Layer %s has no tiles", 7216: "cocos2d: TMXFormat: Unsupported TMX version: %s", 7217: "cocos2d: TMXFomat: Unsupported orientation: %s", 7218: "cc.TMXMapInfo.parseXMLFile(): unsupported compression method", 7219: "cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported", 7221: "cc.TMXMapInfo.parseXMLFile(): Texture '%s' not found.", 7222: "Parse %s failed.", 7236: "cc.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released", 7237: "cc.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released", 7238: "cc.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released", 7239: "cc.TMXLayer.setTileGID(): invalid gid: %s", 7240: "cc.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released", 7241: "cc.TiledMap.initWithXML(): Map not found. Please check the filename.", 7401: "Failed to set _defaultArmatureIndex for '%s' because the index is out of range.", 7402: "Failed to set _animationIndex for '%s' because the index is out of range.", 7501: "Failed to set _defaultSkinIndex for '%s' because the index is out of range.", 7502: "Failed to set _animationIndex for '%s' because its skeletonData is invalid.", 7503: "Failed to set _animationIndex for '%s' because the index is out of range.", 7504: "Can not render dynamic created SkeletonData", 7506: "Failed to load spine atlas '$s'", 7507: "Please re-import '%s' because its textures is not initialized! (This workflow will be improved in the future.)", 7508: "The atlas asset of '%s' is not exists!", 7509: "Spine: Animation not found: %s", 7510: "Spine: Animation not found: %s", 7600: "The context of RenderTexture is invalid.", 7601: "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;", 7602: "Could not attach texture to the framebuffer", 7603: "clearDepth isn't supported on Cocos2d-Html5", 7604: "saveToFile isn't supported on Cocos2d-Html5", 7605: "newCCImage isn't supported on Cocos2d-Html5", 7700: "On the web is always keep the aspect ratio", 7701: "Can't know status", 7702: "Video player's duration is not ready to get now!", 7800: "Web does not support loading", 7801: "Web does not support query history", 7802: "Web does not support query history", 7803: "The current browser does not support the GoBack", 7804: "The current browser does not support the GoForward", 7805: "Web does not support zoom", 7900: "cc.math.Matrix3.assign(): current matrix equals matIn", 7901: "cc.math.mat4Assign(): pOut equals pIn", 7902: "cc.mat.Matrix4.assignFrom(): mat4 equals current matrix", 7903: "cc.math.Matrix4 equal: pMat1 and pMat2 are same object.", 7904: "cc.math.Matrix4.extractPlane: Invalid plane index", 7905: "cc.math.mat4Assign(): pOut equals pIn", 7906: "cc.mat.Matrix4.assignFrom(): mat4 equals current matrix", 7907: "cc.math.Matrix4 equals: pMat1 and pMat2 are same object.", 7908: "Invalid matrix mode specified", 7909: "current quaternion is an invalid value", 8e3: "Can't handle this field type or size", 8001: "No bytes requested", 8002: "Too many bytes requested", 8003: "Missing StripByteCounts!", 8103: "cc.GLProgram.link(): Cannot link invalid program", 8104: "cocos2d: ERROR: Failed to link program: %s", 8105: "cocos2d: cc.shaderCache._loadDefaultShader, error shader type", 8106: "Please load the resource firset : %s", 8107: "cc.GLProgram.getUniformLocationForName(): uniform name should be non-null", 8108: "cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized", 8109: "modelView matrix is undefined.", 8200: "Please set node's active instead of rigidbody's enabled.", 8300: "Should only one camera exists, please check your project.", 8301: "Camera does not support Canvas Mode.", 8400: "Wrong type arguments, 'filePath' must be a String.", 8401: "Since 1.10, `%s` accept %s instance directly, not a URL string. Please directly reference the %s object in your script, or load %s by loader first. Don't use %s's URL anymore.", 9e3: "Stencil manager does not support level bigger than %d in this device.", 9001: "Stencil manager is already empty, cannot pop any mask.", 9100: "LabelAtlas '%s' cannot be loaded, raw texture does not exist.", 9101: "LabelAtlas '%s' cannot be loaded, fnt data does not exist.", 9102: "Program not support highp precision, will change to mediump.", 9103: "%s : Failed to set property [%s], property not found.", 9104: "%s : Failed to define [%s], define not found.", 9105: "%s : Failed to set property [%s], property length not correct.", 9106: "%s : Set property [%s] warning : should transform object to ArrayBuffer.", 9107: "%s : illegal property: [%s], myabe defined an unused property;", 9200: "cc.view.enableAntiAlias is deprecated, please use cc.Texture2D.setFilters instead", "0100": "%s not yet implemented." }; }), {} ], 2: [ (function(require, module, exports) { "use strict"; require("../core/platform/CCClass"); var misc = require("../core/utils/misc"); cc.Action = cc.Class({ name: "cc.Action", ctor: function ctor() { this.originalTarget = null; this.target = null; this.tag = cc.Action.TAG_INVALID; }, clone: function clone() { var action = new cc.Action(); action.originalTarget = null; action.target = null; action.tag = this.tag; return action; }, isDone: function isDone() { return true; }, startWithTarget: function startWithTarget(target) { this.originalTarget = target; this.target = target; }, stop: function stop() { this.target = null; }, step: function step(dt) { cc.logID(1006); }, update: function update(dt) { cc.logID(1007); }, getTarget: function getTarget() { return this.target; }, setTarget: function setTarget(target) { this.target = target; }, getOriginalTarget: function getOriginalTarget() { return this.originalTarget; }, setOriginalTarget: function setOriginalTarget(originalTarget) { this.originalTarget = originalTarget; }, getTag: function getTag() { return this.tag; }, setTag: function setTag(tag) { this.tag = tag; }, retain: function retain() {}, release: function release() {} }); cc.Action.TAG_INVALID = -1; cc.FiniteTimeAction = cc.Class({ name: "cc.FiniteTimeAction", extends: cc.Action, ctor: function ctor() { this._duration = 0; }, getDuration: function getDuration() { return this._duration * (this._timesForRepeat || 1); }, setDuration: function setDuration(duration) { this._duration = duration; }, reverse: function reverse() { cc.logID(1008); return null; }, clone: function clone() { return new cc.FiniteTimeAction(); } }); cc.Speed = cc.Class({ name: "cc.Speed", extends: cc.Action, ctor: function ctor(action, speed) { this._speed = 0; this._innerAction = null; action && this.initWithAction(action, speed); }, getSpeed: function getSpeed() { return this._speed; }, setSpeed: function setSpeed(speed) { this._speed = speed; }, initWithAction: function initWithAction(action, speed) { if (!action) { cc.errorID(1021); return false; } this._innerAction = action; this._speed = speed; return true; }, clone: function clone() { var action = new cc.Speed(); action.initWithAction(this._innerAction.clone(), this._speed); return action; }, startWithTarget: function startWithTarget(target) { cc.Action.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, stop: function stop() { this._innerAction.stop(); cc.Action.prototype.stop.call(this); }, step: function step(dt) { this._innerAction.step(dt * this._speed); }, isDone: function isDone() { return this._innerAction.isDone(); }, reverse: function reverse() { return new cc.Speed(this._innerAction.reverse(), this._speed); }, setInnerAction: function setInnerAction(action) { this._innerAction !== action && (this._innerAction = action); }, getInnerAction: function getInnerAction() { return this._innerAction; } }); cc.speed = function(action, speed) { return new cc.Speed(action, speed); }; cc.Follow = cc.Class({ name: "cc.Follow", extends: cc.Action, ctor: function ctor(followedNode, rect) { this._followedNode = null; this._boundarySet = false; this._boundaryFullyCovered = false; this._halfScreenSize = null; this._fullScreenSize = null; this.leftBoundary = 0; this.rightBoundary = 0; this.topBoundary = 0; this.bottomBoundary = 0; this._worldRect = cc.rect(0, 0, 0, 0); followedNode && (rect ? this.initWithTarget(followedNode, rect) : this.initWithTarget(followedNode)); }, clone: function clone() { var action = new cc.Follow(); var locRect = this._worldRect; var rect = new cc.Rect(locRect.x, locRect.y, locRect.width, locRect.height); action.initWithTarget(this._followedNode, rect); return action; }, isBoundarySet: function isBoundarySet() { return this._boundarySet; }, setBoundarySet: function setBoundarySet(value) { this._boundarySet = value; }, setBoudarySet: function setBoudarySet(value) { this.setBoundarySet(value); }, initWithTarget: function initWithTarget(followedNode, rect) { if (!followedNode) { cc.errorID(1022); return false; } var _this = this; rect = rect || cc.rect(0, 0, 0, 0); _this._followedNode = followedNode; _this._worldRect = rect; _this._boundarySet = !(0 === rect.width && 0 === rect.height); _this._boundaryFullyCovered = false; var winSize = cc.winSize; _this._fullScreenSize = cc.v2(winSize.width, winSize.height); _this._halfScreenSize = _this._fullScreenSize.mul(.5); if (_this._boundarySet) { _this.leftBoundary = -(rect.x + rect.width - _this._fullScreenSize.x); _this.rightBoundary = -rect.x; _this.topBoundary = -rect.y; _this.bottomBoundary = -(rect.y + rect.height - _this._fullScreenSize.y); _this.rightBoundary < _this.leftBoundary && (_this.rightBoundary = _this.leftBoundary = (_this.leftBoundary + _this.rightBoundary) / 2); _this.topBoundary < _this.bottomBoundary && (_this.topBoundary = _this.bottomBoundary = (_this.topBoundary + _this.bottomBoundary) / 2); _this.topBoundary === _this.bottomBoundary && _this.leftBoundary === _this.rightBoundary && (_this._boundaryFullyCovered = true); } return true; }, step: function step(dt) { var targetWorldPos = this.target.convertToWorldSpaceAR(cc.Vec2.ZERO); var followedWorldPos = this._followedNode.convertToWorldSpaceAR(cc.Vec2.ZERO); var delta = targetWorldPos.sub(followedWorldPos); var tempPos = this.target.parent.convertToNodeSpaceAR(delta.add(this._halfScreenSize)); if (this._boundarySet) { if (this._boundaryFullyCovered) return; this.target.setPosition(misc.clampf(tempPos.x, this.leftBoundary, this.rightBoundary), misc.clampf(tempPos.y, this.bottomBoundary, this.topBoundary)); } else this.target.setPosition(tempPos.x, tempPos.y); }, isDone: function isDone() { return !this._followedNode.activeInHierarchy; }, stop: function stop() { this.target = null; cc.Action.prototype.stop.call(this); } }); cc.follow = function(followedNode, rect) { return new cc.Follow(followedNode, rect); }; }), { "../core/platform/CCClass": 129, "../core/utils/misc": 217 } ], 3: [ (function(require, module, exports) { "use strict"; function cardinalSplineAt(p0, p1, p2, p3, tension, t) { var t2 = t * t; var t3 = t2 * t; var s = (1 - tension) / 2; var b1 = s * (2 * t2 - t3 - t); var b2 = s * (-t3 + t2) + (2 * t3 - 3 * t2 + 1); var b3 = s * (t3 - 2 * t2 + t) + (-2 * t3 + 3 * t2); var b4 = s * (t3 - t2); var x = p0.x * b1 + p1.x * b2 + p2.x * b3 + p3.x * b4; var y = p0.y * b1 + p1.y * b2 + p2.y * b3 + p3.y * b4; return cc.v2(x, y); } function getControlPointAt(controlPoints, pos) { var p = Math.min(controlPoints.length - 1, Math.max(pos, 0)); return controlPoints[p]; } function reverseControlPoints(controlPoints) { var newArray = []; for (var i = controlPoints.length - 1; i >= 0; i--) newArray.push(cc.v2(controlPoints[i].x, controlPoints[i].y)); return newArray; } function cloneControlPoints(controlPoints) { var newArray = []; for (var i = 0; i < controlPoints.length; i++) newArray.push(cc.v2(controlPoints[i].x, controlPoints[i].y)); return newArray; } cc.CardinalSplineTo = cc.Class({ name: "cc.CardinalSplineTo", extends: cc.ActionInterval, ctor: function ctor(duration, points, tension) { this._points = []; this._deltaT = 0; this._tension = 0; this._previousPosition = null; this._accumulatedDiff = null; void 0 !== tension && cc.CardinalSplineTo.prototype.initWithDuration.call(this, duration, points, tension); }, initWithDuration: function initWithDuration(duration, points, tension) { if (!points || 0 === points.length) { cc.errorID(1024); return false; } if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this.setPoints(points); this._tension = tension; return true; } return false; }, clone: function clone() { var action = new cc.CardinalSplineTo(); action.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._deltaT = 1 / (this._points.length - 1); this._previousPosition = cc.v2(this.target.x, this.target.y); this._accumulatedDiff = cc.v2(0, 0); }, update: function update(dt) { dt = this._computeEaseTime(dt); var p, lt; var ps = this._points; if (1 === dt) { p = ps.length - 1; lt = 1; } else { var locDT = this._deltaT; p = 0 | dt / locDT; lt = (dt - locDT * p) / locDT; } var newPos = cardinalSplineAt(getControlPointAt(ps, p - 1), getControlPointAt(ps, p - 0), getControlPointAt(ps, p + 1), getControlPointAt(ps, p + 2), this._tension, lt); if (cc.macro.ENABLE_STACKABLE_ACTIONS) { var tempX, tempY; tempX = this.target.x - this._previousPosition.x; tempY = this.target.y - this._previousPosition.y; if (0 !== tempX || 0 !== tempY) { var locAccDiff = this._accumulatedDiff; tempX = locAccDiff.x + tempX; tempY = locAccDiff.y + tempY; locAccDiff.x = tempX; locAccDiff.y = tempY; newPos.x += tempX; newPos.y += tempY; } } this.updatePosition(newPos); }, reverse: function reverse() { var reversePoints = reverseControlPoints(this._points); return cc.cardinalSplineTo(this._duration, reversePoints, this._tension); }, updatePosition: function updatePosition(newPos) { this.target.setPosition(newPos); this._previousPosition = newPos; }, getPoints: function getPoints() { return this._points; }, setPoints: function setPoints(points) { this._points = points; } }); cc.cardinalSplineTo = function(duration, points, tension) { return new cc.CardinalSplineTo(duration, points, tension); }; cc.CardinalSplineBy = cc.Class({ name: "cc.CardinalSplineBy", extends: cc.CardinalSplineTo, ctor: function ctor(duration, points, tension) { this._startPosition = cc.v2(0, 0); void 0 !== tension && this.initWithDuration(duration, points, tension); }, startWithTarget: function startWithTarget(target) { cc.CardinalSplineTo.prototype.startWithTarget.call(this, target); this._startPosition.x = target.x; this._startPosition.y = target.y; }, reverse: function reverse() { var copyConfig = this._points.slice(); var current; var p = copyConfig[0]; for (var i = 1; i < copyConfig.length; ++i) { current = copyConfig[i]; copyConfig[i] = current.sub(p); p = current; } var reverseArray = reverseControlPoints(copyConfig); p = reverseArray[reverseArray.length - 1]; reverseArray.pop(); p.x = -p.x; p.y = -p.y; reverseArray.unshift(p); for (var i = 1; i < reverseArray.length; ++i) { current = reverseArray[i]; current.x = -current.x; current.y = -current.y; current.x += p.x; current.y += p.y; reverseArray[i] = current; p = current; } return cc.cardinalSplineBy(this._duration, reverseArray, this._tension); }, updatePosition: function updatePosition(newPos) { var pos = this._startPosition; var posX = newPos.x + pos.x; var posY = newPos.y + pos.y; this._previousPosition.x = posX; this._previousPosition.y = posY; this.target.setPosition(posX, posY); }, clone: function clone() { var a = new cc.CardinalSplineBy(); a.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension); return a; } }); cc.cardinalSplineBy = function(duration, points, tension) { return new cc.CardinalSplineBy(duration, points, tension); }; cc.CatmullRomTo = cc.Class({ name: "cc.CatmullRomTo", extends: cc.CardinalSplineTo, ctor: function ctor(dt, points) { points && this.initWithDuration(dt, points); }, initWithDuration: function initWithDuration(dt, points) { return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, .5); }, clone: function clone() { var action = new cc.CatmullRomTo(); action.initWithDuration(this._duration, cloneControlPoints(this._points)); return action; } }); cc.catmullRomTo = function(dt, points) { return new cc.CatmullRomTo(dt, points); }; cc.CatmullRomBy = cc.Class({ name: "cc.CatmullRomBy", extends: cc.CardinalSplineBy, ctor: function ctor(dt, points) { points && this.initWithDuration(dt, points); }, initWithDuration: function initWithDuration(dt, points) { return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, .5); }, clone: function clone() { var action = new cc.CatmullRomBy(); action.initWithDuration(this._duration, cloneControlPoints(this._points)); return action; } }); cc.catmullRomBy = function(dt, points) { return new cc.CatmullRomBy(dt, points); }; }), {} ], 4: [ (function(require, module, exports) { "use strict"; cc.easeIn = function(rate) { return { _rate: rate, easing: function easing(dt) { return Math.pow(dt, this._rate); }, reverse: function reverse() { return cc.easeIn(1 / this._rate); } }; }; cc.easeOut = function(rate) { return { _rate: rate, easing: function easing(dt) { return Math.pow(dt, 1 / this._rate); }, reverse: function reverse() { return cc.easeOut(1 / this._rate); } }; }; cc.easeInOut = function(rate) { return { _rate: rate, easing: function easing(dt) { dt *= 2; return dt < 1 ? .5 * Math.pow(dt, this._rate) : 1 - .5 * Math.pow(2 - dt, this._rate); }, reverse: function reverse() { return cc.easeInOut(this._rate); } }; }; var _easeExponentialInObj = { easing: function easing(dt) { return 0 === dt ? 0 : Math.pow(2, 10 * (dt - 1)); }, reverse: function reverse() { return _easeExponentialOutObj; } }; cc.easeExponentialIn = function() { return _easeExponentialInObj; }; var _easeExponentialOutObj = { easing: function easing(dt) { return 1 === dt ? 1 : 1 - Math.pow(2, -10 * dt); }, reverse: function reverse() { return _easeExponentialInObj; } }; cc.easeExponentialOut = function() { return _easeExponentialOutObj; }; var _easeExponentialInOutObj = { easing: function easing(dt) { if (1 !== dt && 0 !== dt) { dt *= 2; return dt < 1 ? .5 * Math.pow(2, 10 * (dt - 1)) : .5 * (2 - Math.pow(2, -10 * (dt - 1))); } return dt; }, reverse: function reverse() { return _easeExponentialInOutObj; } }; cc.easeExponentialInOut = function() { return _easeExponentialInOutObj; }; var _easeSineInObj = { easing: function easing(dt) { return 0 === dt || 1 === dt ? dt : -1 * Math.cos(dt * Math.PI / 2) + 1; }, reverse: function reverse() { return _easeSineOutObj; } }; cc.easeSineIn = function() { return _easeSineInObj; }; var _easeSineOutObj = { easing: function easing(dt) { return 0 === dt || 1 === dt ? dt : Math.sin(dt * Math.PI / 2); }, reverse: function reverse() { return _easeSineInObj; } }; cc.easeSineOut = function() { return _easeSineOutObj; }; var _easeSineInOutObj = { easing: function easing(dt) { return 0 === dt || 1 === dt ? dt : -.5 * (Math.cos(Math.PI * dt) - 1); }, reverse: function reverse() { return _easeSineInOutObj; } }; cc.easeSineInOut = function() { return _easeSineInOutObj; }; var _easeElasticInObj = { easing: function easing(dt) { if (0 === dt || 1 === dt) return dt; dt -= 1; return -Math.pow(2, 10 * dt) * Math.sin((dt - .075) * Math.PI * 2 / .3); }, reverse: function reverse() { return _easeElasticOutObj; } }; cc.easeElasticIn = function(period) { if (period && .3 !== period) return { _period: period, easing: function easing(dt) { if (0 === dt || 1 === dt) return dt; dt -= 1; return -Math.pow(2, 10 * dt) * Math.sin((dt - this._period / 4) * Math.PI * 2 / this._period); }, reverse: function reverse() { return cc.easeElasticOut(this._period); } }; return _easeElasticInObj; }; var _easeElasticOutObj = { easing: function easing(dt) { return 0 === dt || 1 === dt ? dt : Math.pow(2, -10 * dt) * Math.sin((dt - .075) * Math.PI * 2 / .3) + 1; }, reverse: function reverse() { return _easeElasticInObj; } }; cc.easeElasticOut = function(period) { if (period && .3 !== period) return { _period: period, easing: function easing(dt) { return 0 === dt || 1 === dt ? dt : Math.pow(2, -10 * dt) * Math.sin((dt - this._period / 4) * Math.PI * 2 / this._period) + 1; }, reverse: function reverse() { return cc.easeElasticIn(this._period); } }; return _easeElasticOutObj; }; cc.easeElasticInOut = function(period) { period = period || .3; return { _period: period, easing: function easing(dt) { var newT = 0; var locPeriod = this._period; if (0 === dt || 1 === dt) newT = dt; else { dt *= 2; locPeriod || (locPeriod = this._period = .3 * 1.5); var s = locPeriod / 4; dt -= 1; newT = dt < 0 ? -.5 * Math.pow(2, 10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) : Math.pow(2, -10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) * .5 + 1; } return newT; }, reverse: function reverse() { return cc.easeElasticInOut(this._period); } }; }; function _bounceTime(time1) { if (time1 < 1 / 2.75) return 7.5625 * time1 * time1; if (time1 < 2 / 2.75) { time1 -= 1.5 / 2.75; return 7.5625 * time1 * time1 + .75; } if (time1 < 2.5 / 2.75) { time1 -= 2.25 / 2.75; return 7.5625 * time1 * time1 + .9375; } time1 -= 2.625 / 2.75; return 7.5625 * time1 * time1 + .984375; } var _easeBounceInObj = { easing: function easing(dt) { return 1 - _bounceTime(1 - dt); }, reverse: function reverse() { return _easeBounceOutObj; } }; cc.easeBounceIn = function() { return _easeBounceInObj; }; var _easeBounceOutObj = { easing: function easing(dt) { return _bounceTime(dt); }, reverse: function reverse() { return _easeBounceInObj; } }; cc.easeBounceOut = function() { return _easeBounceOutObj; }; var _easeBounceInOutObj = { easing: function easing(time1) { var newT; if (time1 < .5) { time1 *= 2; newT = .5 * (1 - _bounceTime(1 - time1)); } else newT = .5 * _bounceTime(2 * time1 - 1) + .5; return newT; }, reverse: function reverse() { return _easeBounceInOutObj; } }; cc.easeBounceInOut = function() { return _easeBounceInOutObj; }; var _easeBackInObj = { easing: function easing(time1) { var overshoot = 1.70158; return 0 === time1 || 1 === time1 ? time1 : time1 * time1 * ((overshoot + 1) * time1 - overshoot); }, reverse: function reverse() { return _easeBackOutObj; } }; cc.easeBackIn = function() { return _easeBackInObj; }; var _easeBackOutObj = { easing: function easing(time1) { if (0 === time1) return 0; var overshoot = 1.70158; time1 -= 1; return time1 * time1 * ((overshoot + 1) * time1 + overshoot) + 1; }, reverse: function reverse() { return _easeBackInObj; } }; cc.easeBackOut = function() { return _easeBackOutObj; }; var _easeBackInOutObj = { easing: function easing(time1) { var overshoot = 2.5949095; time1 *= 2; if (time1 < 1) return time1 * time1 * ((overshoot + 1) * time1 - overshoot) / 2; time1 -= 2; return time1 * time1 * ((overshoot + 1) * time1 + overshoot) / 2 + 1; }, reverse: function reverse() { return _easeBackInOutObj; } }; cc.easeBackInOut = function() { return _easeBackInOutObj; }; cc.easeBezierAction = function(a, b, c, d) { return { easing: function easing(t) { return Math.pow(1 - t, 3) * a + 3 * t * Math.pow(1 - t, 2) * b + 3 * Math.pow(t, 2) * (1 - t) * c + Math.pow(t, 3) * d; }, reverse: function reverse() { return cc.easeBezierAction(d, c, b, a); } }; }; var _easeQuadraticActionIn = { easing: function easing(time) { return Math.pow(time, 2); }, reverse: function reverse() { return _easeQuadraticActionIn; } }; cc.easeQuadraticActionIn = function() { return _easeQuadraticActionIn; }; var _easeQuadraticActionOut = { easing: function easing(time) { return -time * (time - 2); }, reverse: function reverse() { return _easeQuadraticActionOut; } }; cc.easeQuadraticActionOut = function() { return _easeQuadraticActionOut; }; var _easeQuadraticActionInOut = { easing: function easing(time) { var resultTime = time; time *= 2; if (time < 1) resultTime = time * time * .5; else { --time; resultTime = -.5 * (time * (time - 2) - 1); } return resultTime; }, reverse: function reverse() { return _easeQuadraticActionInOut; } }; cc.easeQuadraticActionInOut = function() { return _easeQuadraticActionInOut; }; var _easeQuarticActionIn = { easing: function easing(time) { return time * time * time * time; }, reverse: function reverse() { return _easeQuarticActionIn; } }; cc.easeQuarticActionIn = function() { return _easeQuarticActionIn; }; var _easeQuarticActionOut = { easing: function easing(time) { time -= 1; return -(time * time * time * time - 1); }, reverse: function reverse() { return _easeQuarticActionOut; } }; cc.easeQuarticActionOut = function() { return _easeQuarticActionOut; }; var _easeQuarticActionInOut = { easing: function easing(time) { time *= 2; if (time < 1) return .5 * time * time * time * time; time -= 2; return -.5 * (time * time * time * time - 2); }, reverse: function reverse() { return _easeQuarticActionInOut; } }; cc.easeQuarticActionInOut = function() { return _easeQuarticActionInOut; }; var _easeQuinticActionIn = { easing: function easing(time) { return time * time * time * time * time; }, reverse: function reverse() { return _easeQuinticActionIn; } }; cc.easeQuinticActionIn = function() { return _easeQuinticActionIn; }; var _easeQuinticActionOut = { easing: function easing(time) { time -= 1; return time * time * time * time * time + 1; }, reverse: function reverse() { return _easeQuinticActionOut; } }; cc.easeQuinticActionOut = function() { return _easeQuinticActionOut; }; var _easeQuinticActionInOut = { easing: function easing(time) { time *= 2; if (time < 1) return .5 * time * time * time * time * time; time -= 2; return .5 * (time * time * time * time * time + 2); }, reverse: function reverse() { return _easeQuinticActionInOut; } }; cc.easeQuinticActionInOut = function() { return _easeQuinticActionInOut; }; var _easeCircleActionIn = { easing: function easing(time) { return -1 * (Math.sqrt(1 - time * time) - 1); }, reverse: function reverse() { return _easeCircleActionIn; } }; cc.easeCircleActionIn = function() { return _easeCircleActionIn; }; var _easeCircleActionOut = { easing: function easing(time) { time -= 1; return Math.sqrt(1 - time * time); }, reverse: function reverse() { return _easeCircleActionOut; } }; cc.easeCircleActionOut = function() { return _easeCircleActionOut; }; var _easeCircleActionInOut = { easing: function easing(time) { time *= 2; if (time < 1) return -.5 * (Math.sqrt(1 - time * time) - 1); time -= 2; return .5 * (Math.sqrt(1 - time * time) + 1); }, reverse: function reverse() { return _easeCircleActionInOut; } }; cc.easeCircleActionInOut = function() { return _easeCircleActionInOut; }; var _easeCubicActionIn = { easing: function easing(time) { return time * time * time; }, reverse: function reverse() { return _easeCubicActionIn; } }; cc.easeCubicActionIn = function() { return _easeCubicActionIn; }; var _easeCubicActionOut = { easing: function easing(time) { time -= 1; return time * time * time + 1; }, reverse: function reverse() { return _easeCubicActionOut; } }; cc.easeCubicActionOut = function() { return _easeCubicActionOut; }; var _easeCubicActionInOut = { easing: function easing(time) { time *= 2; if (time < 1) return .5 * time * time * time; time -= 2; return .5 * (time * time * time + 2); }, reverse: function reverse() { return _easeCubicActionInOut; } }; cc.easeCubicActionInOut = function() { return _easeCubicActionInOut; }; }), {} ], 5: [ (function(require, module, exports) { "use strict"; cc.ActionInstant = cc.Class({ name: "cc.ActionInstant", extends: cc.FiniteTimeAction, isDone: function isDone() { return true; }, step: function step(dt) { this.update(1); }, update: function update(dt) {}, reverse: function reverse() { return this.clone(); }, clone: function clone() { return new cc.ActionInstant(); } }); cc.Show = cc.Class({ name: "cc.Show", extends: cc.ActionInstant, update: function update(dt) { var _renderComps = this.target.getComponentsInChildren(cc.RenderComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = true; } }, reverse: function reverse() { return new cc.Hide(); }, clone: function clone() { return new cc.Show(); } }); cc.show = function() { return new cc.Show(); }; cc.Hide = cc.Class({ name: "cc.Hide", extends: cc.ActionInstant, update: function update(dt) { var _renderComps = this.target.getComponentsInChildren(cc.RenderComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = false; } }, reverse: function reverse() { return new cc.Show(); }, clone: function clone() { return new cc.Hide(); } }); cc.hide = function() { return new cc.Hide(); }; cc.ToggleVisibility = cc.Class({ name: "cc.ToggleVisibility", extends: cc.ActionInstant, update: function update(dt) { var _renderComps = this.target.getComponentsInChildren(cc.RenderComponent); for (var i = 0; i < _renderComps.length; ++i) { var render = _renderComps[i]; render.enabled = !render.enabled; } }, reverse: function reverse() { return new cc.ToggleVisibility(); }, clone: function clone() { return new cc.ToggleVisibility(); } }); cc.toggleVisibility = function() { return new cc.ToggleVisibility(); }; cc.RemoveSelf = cc.Class({ name: "cc.RemoveSelf", extends: cc.ActionInstant, ctor: function ctor(isNeedCleanUp) { this._isNeedCleanUp = true; void 0 !== isNeedCleanUp && this.init(isNeedCleanUp); }, update: function update(dt) { this.target.removeFromParent(this._isNeedCleanUp); }, init: function init(isNeedCleanUp) { this._isNeedCleanUp = isNeedCleanUp; return true; }, reverse: function reverse() { return new cc.RemoveSelf(this._isNeedCleanUp); }, clone: function clone() { return new cc.RemoveSelf(this._isNeedCleanUp); } }); cc.removeSelf = function(isNeedCleanUp) { return new cc.RemoveSelf(isNeedCleanUp); }; cc.DestroySelf = cc.Class({ name: "cc.DestroySelf", extends: cc.ActionInstant, update: function update() { this.target.destroy(); }, reverse: function reverse() { return new cc.DestroySelf(); }, clone: function clone() { return new cc.DestroySelf(); } }); cc.destroySelf = function() { return new cc.DestroySelf(); }; cc.FlipX = cc.Class({ name: "cc.FlipX", extends: cc.ActionInstant, ctor: function ctor(flip) { this._flippedX = false; void 0 !== flip && this.initWithFlipX(flip); }, initWithFlipX: function initWithFlipX(flip) { this._flippedX = flip; return true; }, update: function update(dt) { this.target.scaleX = Math.abs(this.target.scaleX) * (this._flippedX ? -1 : 1); }, reverse: function reverse() { return new cc.FlipX(!this._flippedX); }, clone: function clone() { var action = new cc.FlipX(); action.initWithFlipX(this._flippedX); return action; } }); cc.flipX = function(flip) { return new cc.FlipX(flip); }; cc.FlipY = cc.Class({ name: "cc.FlipY", extends: cc.ActionInstant, ctor: function ctor(flip) { this._flippedY = false; void 0 !== flip && this.initWithFlipY(flip); }, initWithFlipY: function initWithFlipY(flip) { this._flippedY = flip; return true; }, update: function update(dt) { this.target.scaleY = Math.abs(this.target.scaleY) * (this._flippedY ? -1 : 1); }, reverse: function reverse() { return new cc.FlipY(!this._flippedY); }, clone: function clone() { var action = new cc.FlipY(); action.initWithFlipY(this._flippedY); return action; } }); cc.flipY = function(flip) { return new cc.FlipY(flip); }; cc.Place = cc.Class({ name: "cc.Place", extends: cc.ActionInstant, ctor: function ctor(pos, y) { this._x = 0; this._y = 0; if (void 0 !== pos) { if (void 0 !== pos.x) { y = pos.y; pos = pos.x; } this.initWithPosition(pos, y); } }, initWithPosition: function initWithPosition(x, y) { this._x = x; this._y = y; return true; }, update: function update(dt) { this.target.setPosition(this._x, this._y); }, clone: function clone() { var action = new cc.Place(); action.initWithPosition(this._x, this._y); return action; } }); cc.place = function(pos, y) { return new cc.Place(pos, y); }; cc.CallFunc = cc.Class({ name: "cc.CallFunc", extends: cc.ActionInstant, ctor: function ctor(selector, selectorTarget, data) { this._selectorTarget = null; this._function = null; this._data = null; this.initWithFunction(selector, selectorTarget, data); }, initWithFunction: function initWithFunction(selector, selectorTarget, data) { selector && (this._function = selector); selectorTarget && (this._selectorTarget = selectorTarget); void 0 !== data && (this._data = data); return true; }, execute: function execute() { this._function && this._function.call(this._selectorTarget, this.target, this._data); }, update: function update(dt) { this.execute(); }, getTargetCallback: function getTargetCallback() { return this._selectorTarget; }, setTargetCallback: function setTargetCallback(sel) { if (sel !== this._selectorTarget) { this._selectorTarget && (this._selectorTarget = null); this._selectorTarget = sel; } }, clone: function clone() { var action = new cc.CallFunc(); action.initWithFunction(this._function, this._selectorTarget, this._data); return action; } }); cc.callFunc = function(selector, selectorTarget, data) { return new cc.CallFunc(selector, selectorTarget, data); }; }), {} ], 6: [ (function(require, module, exports) { "use strict"; cc.ActionInterval = cc.Class({ name: "cc.ActionInterval", extends: cc.FiniteTimeAction, ctor: function ctor(d) { this.MAX_VALUE = 2; this._elapsed = 0; this._firstTick = false; this._easeList = null; this._speed = 1; this._timesForRepeat = 1; this._repeatForever = false; this._repeatMethod = false; this._speedMethod = false; void 0 !== d && cc.ActionInterval.prototype.initWithDuration.call(this, d); }, getElapsed: function getElapsed() { return this._elapsed; }, initWithDuration: function initWithDuration(d) { this._duration = 0 === d ? cc.macro.FLT_EPSILON : d; this._elapsed = 0; this._firstTick = true; return true; }, isDone: function isDone() { return this._elapsed >= this._duration; }, _cloneDecoration: function _cloneDecoration(action) { action._repeatForever = this._repeatForever; action._speed = this._speed; action._timesForRepeat = this._timesForRepeat; action._easeList = this._easeList; action._speedMethod = this._speedMethod; action._repeatMethod = this._repeatMethod; }, _reverseEaseList: function _reverseEaseList(action) { if (this._easeList) { action._easeList = []; for (var i = 0; i < this._easeList.length; i++) action._easeList.push(this._easeList[i].reverse()); } }, clone: function clone() { var action = new cc.ActionInterval(this._duration); this._cloneDecoration(action); return action; }, easing: function easing(easeObj) { this._easeList ? this._easeList.length = 0 : this._easeList = []; for (var i = 0; i < arguments.length; i++) this._easeList.push(arguments[i]); return this; }, _computeEaseTime: function _computeEaseTime(dt) { var locList = this._easeList; if (!locList || 0 === locList.length) return dt; for (var i = 0, n = locList.length; i < n; i++) dt = locList[i].easing(dt); return dt; }, step: function step(dt) { if (this._firstTick) { this._firstTick = false; this._elapsed = 0; } else this._elapsed += dt; var t = this._elapsed / (this._duration > 1.192092896e-7 ? this._duration : 1.192092896e-7); t = 1 > t ? t : 1; this.update(t > 0 ? t : 0); if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) { this._repeatForever || this._timesForRepeat--; this.startWithTarget(this.target); this.step(this._elapsed - this._duration); } }, startWithTarget: function startWithTarget(target) { cc.Action.prototype.startWithTarget.call(this, target); this._elapsed = 0; this._firstTick = true; }, reverse: function reverse() { cc.logID(1010); return null; }, setAmplitudeRate: function setAmplitudeRate(amp) { cc.logID(1011); }, getAmplitudeRate: function getAmplitudeRate() { cc.logID(1012); return 0; }, speed: function speed(_speed) { if (_speed <= 0) { cc.logID(1013); return this; } this._speedMethod = true; this._speed *= _speed; return this; }, getSpeed: function getSpeed() { return this._speed; }, setSpeed: function setSpeed(speed) { this._speed = speed; return this; }, repeat: function repeat(times) { times = Math.round(times); if (isNaN(times) || times < 1) { cc.logID(1014); return this; } this._repeatMethod = true; this._timesForRepeat *= times; return this; }, repeatForever: function repeatForever() { this._repeatMethod = true; this._timesForRepeat = this.MAX_VALUE; this._repeatForever = true; return this; } }); cc.actionInterval = function(d) { return new cc.ActionInterval(d); }; cc.Sequence = cc.Class({ name: "cc.Sequence", extends: cc.ActionInterval, ctor: function ctor(tempArray) { this._actions = []; this._split = null; this._last = 0; this._reversed = false; var paramArray = tempArray instanceof Array ? tempArray : arguments; if (1 === paramArray.length) { cc.errorID(1019); return; } var last = paramArray.length - 1; last >= 0 && null == paramArray[last] && cc.logID(1015); if (last >= 0) { var prev = paramArray[0], action1; for (var i = 1; i < last; i++) if (paramArray[i]) { action1 = prev; prev = cc.Sequence._actionOneTwo(action1, paramArray[i]); } this.initWithTwoActions(prev, paramArray[last]); } }, initWithTwoActions: function initWithTwoActions(actionOne, actionTwo) { if (!actionOne || !actionTwo) { cc.errorID(1025); return false; } var durationOne = actionOne._duration, durationTwo = actionTwo._duration; durationOne *= actionOne._repeatMethod ? actionOne._timesForRepeat : 1; durationTwo *= actionTwo._repeatMethod ? actionTwo._timesForRepeat : 1; var d = durationOne + durationTwo; this.initWithDuration(d); this._actions[0] = actionOne; this._actions[1] = actionTwo; return true; }, clone: function clone() { var action = new cc.Sequence(); this._cloneDecoration(action); action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone()); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._split = this._actions[0]._duration / this._duration; this._split *= this._actions[0]._repeatMethod ? this._actions[0]._timesForRepeat : 1; this._last = -1; }, stop: function stop() { -1 !== this._last && this._actions[this._last].stop(); cc.Action.prototype.stop.call(this); }, update: function update(dt) { var new_t, found = 0; var locSplit = this._split, locActions = this._actions, locLast = this._last, actionFound; dt = this._computeEaseTime(dt); if (dt < locSplit) { new_t = 0 !== locSplit ? dt / locSplit : 1; if (0 === found && 1 === locLast && this._reversed) { locActions[1].update(0); locActions[1].stop(); } } else { found = 1; new_t = 1 === locSplit ? 1 : (dt - locSplit) / (1 - locSplit); if (-1 === locLast) { locActions[0].startWithTarget(this.target); locActions[0].update(1); locActions[0].stop(); } if (0 === locLast) { locActions[0].update(1); locActions[0].stop(); } } actionFound = locActions[found]; if (locLast === found && actionFound.isDone()) return; locLast !== found && actionFound.startWithTarget(this.target); new_t *= actionFound._timesForRepeat; actionFound.update(new_t > 1 ? new_t % 1 : new_t); this._last = found; }, reverse: function reverse() { var action = cc.Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse()); this._cloneDecoration(action); this._reverseEaseList(action); action._reversed = true; return action; } }); cc.sequence = function(tempArray) { var paramArray = tempArray instanceof Array ? tempArray : arguments; if (1 === paramArray.length) { cc.errorID(1019); return null; } var last = paramArray.length - 1; last >= 0 && null == paramArray[last] && cc.logID(1015); var result = null; if (last >= 0) { result = paramArray[0]; for (var i = 1; i <= last; i++) paramArray[i] && (result = cc.Sequence._actionOneTwo(result, paramArray[i])); } return result; }; cc.Sequence._actionOneTwo = function(actionOne, actionTwo) { var sequence = new cc.Sequence(); sequence.initWithTwoActions(actionOne, actionTwo); return sequence; }; cc.Repeat = cc.Class({ name: "cc.Repeat", extends: cc.ActionInterval, ctor: function ctor(action, times) { this._times = 0; this._total = 0; this._nextDt = 0; this._actionInstant = false; this._innerAction = null; void 0 !== times && this.initWithAction(action, times); }, initWithAction: function initWithAction(action, times) { var duration = action._duration * times; if (this.initWithDuration(duration)) { this._times = times; this._innerAction = action; if (action instanceof cc.ActionInstant) { this._actionInstant = true; this._times -= 1; } this._total = 0; return true; } return false; }, clone: function clone() { var action = new cc.Repeat(); this._cloneDecoration(action); action.initWithAction(this._innerAction.clone(), this._times); return action; }, startWithTarget: function startWithTarget(target) { this._total = 0; this._nextDt = this._innerAction._duration / this._duration; cc.ActionInterval.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, stop: function stop() { this._innerAction.stop(); cc.Action.prototype.stop.call(this); }, update: function update(dt) { dt = this._computeEaseTime(dt); var locInnerAction = this._innerAction; var locDuration = this._duration; var locTimes = this._times; var locNextDt = this._nextDt; if (dt >= locNextDt) { while (dt > locNextDt && this._total < locTimes) { locInnerAction.update(1); this._total++; locInnerAction.stop(); locInnerAction.startWithTarget(this.target); locNextDt += locInnerAction._duration / locDuration; this._nextDt = locNextDt > 1 ? 1 : locNextDt; } if (dt >= 1 && this._total < locTimes) { locInnerAction.update(1); this._total++; } this._actionInstant || (this._total === locTimes ? locInnerAction.stop() : locInnerAction.update(dt - (locNextDt - locInnerAction._duration / locDuration))); } else locInnerAction.update(dt * locTimes % 1); }, isDone: function isDone() { return this._total === this._times; }, reverse: function reverse() { var action = new cc.Repeat(this._innerAction.reverse(), this._times); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, setInnerAction: function setInnerAction(action) { this._innerAction !== action && (this._innerAction = action); }, getInnerAction: function getInnerAction() { return this._innerAction; } }); cc.repeat = function(action, times) { return new cc.Repeat(action, times); }; cc.repeatForever = function(action) { return new cc.RepeatForever(action); }; cc.RepeatForever = cc.Class({ name: "cc.RepeatForever", extends: cc.ActionInterval, ctor: function ctor(action) { this._innerAction = null; action && this.initWithAction(action); }, initWithAction: function initWithAction(action) { if (!action) { cc.errorID(1026); return false; } this._innerAction = action; return true; }, clone: function clone() { var action = new cc.RepeatForever(); this._cloneDecoration(action); action.initWithAction(this._innerAction.clone()); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, step: function step(dt) { var locInnerAction = this._innerAction; locInnerAction.step(dt); if (locInnerAction.isDone()) { locInnerAction.startWithTarget(this.target); locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration); } }, isDone: function isDone() { return false; }, reverse: function reverse() { var action = new cc.RepeatForever(this._innerAction.reverse()); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, setInnerAction: function setInnerAction(action) { this._innerAction !== action && (this._innerAction = action); }, getInnerAction: function getInnerAction() { return this._innerAction; } }); cc.repeatForever = function(action) { return new cc.RepeatForever(action); }; cc.Spawn = cc.Class({ name: "cc.Spawn", extends: cc.ActionInterval, ctor: function ctor(tempArray) { this._one = null; this._two = null; var paramArray = tempArray instanceof Array ? tempArray : arguments; if (1 === paramArray.length) { cc.errorID(1020); return; } var last = paramArray.length - 1; last >= 0 && null == paramArray[last] && cc.logID(1015); if (last >= 0) { var prev = paramArray[0], action1; for (var i = 1; i < last; i++) if (paramArray[i]) { action1 = prev; prev = cc.Spawn._actionOneTwo(action1, paramArray[i]); } this.initWithTwoActions(prev, paramArray[last]); } }, initWithTwoActions: function initWithTwoActions(action1, action2) { if (!action1 || !action2) { cc.errorID(1027); return false; } var ret = false; var d1 = action1._duration; var d2 = action2._duration; if (this.initWithDuration(Math.max(d1, d2))) { this._one = action1; this._two = action2; d1 > d2 ? this._two = cc.Sequence._actionOneTwo(action2, cc.delayTime(d1 - d2)) : d1 < d2 && (this._one = cc.Sequence._actionOneTwo(action1, cc.delayTime(d2 - d1))); ret = true; } return ret; }, clone: function clone() { var action = new cc.Spawn(); this._cloneDecoration(action); action.initWithTwoActions(this._one.clone(), this._two.clone()); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._one.startWithTarget(target); this._two.startWithTarget(target); }, stop: function stop() { this._one.stop(); this._two.stop(); cc.Action.prototype.stop.call(this); }, update: function update(dt) { dt = this._computeEaseTime(dt); this._one && this._one.update(dt); this._two && this._two.update(dt); }, reverse: function reverse() { var action = cc.Spawn._actionOneTwo(this._one.reverse(), this._two.reverse()); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.spawn = function(tempArray) { var paramArray = tempArray instanceof Array ? tempArray : arguments; if (1 === paramArray.length) { cc.errorID(1020); return null; } paramArray.length > 0 && null == paramArray[paramArray.length - 1] && cc.logID(1015); var prev = paramArray[0]; for (var i = 1; i < paramArray.length; i++) null != paramArray[i] && (prev = cc.Spawn._actionOneTwo(prev, paramArray[i])); return prev; }; cc.Spawn._actionOneTwo = function(action1, action2) { var pSpawn = new cc.Spawn(); pSpawn.initWithTwoActions(action1, action2); return pSpawn; }; cc.RotateTo = cc.Class({ name: "cc.RotateTo", extends: cc.ActionInterval, statics: { _reverse: false }, ctor: function ctor(duration, dstAngle) { this._startAngle = 0; this._dstAngle = 0; this._angle = 0; void 0 !== dstAngle && this.initWithDuration(duration, dstAngle); }, initWithDuration: function initWithDuration(duration, dstAngle) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._dstAngle = dstAngle; return true; } return false; }, clone: function clone() { var action = new cc.RotateTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._dstAngle); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var startAngle = target.angle % 360; var angle = cc.RotateTo._reverse ? this._dstAngle - startAngle : this._dstAngle + startAngle; angle > 180 && (angle -= 360); angle < -180 && (angle += 360); this._startAngle = startAngle; this._angle = cc.RotateTo._reverse ? angle : -angle; }, reverse: function reverse() { cc.logID(1016); }, update: function update(dt) { dt = this._computeEaseTime(dt); this.target && (this.target.angle = this._startAngle + this._angle * dt); } }); cc.rotateTo = function(duration, dstAngle) { return new cc.RotateTo(duration, dstAngle); }; cc.RotateBy = cc.Class({ name: "cc.RotateBy", extends: cc.ActionInterval, statics: { _reverse: false }, ctor: function ctor(duration, deltaAngle) { deltaAngle *= cc.RotateBy._reverse ? 1 : -1; this._deltaAngle = 0; this._startAngle = 0; void 0 !== deltaAngle && this.initWithDuration(duration, deltaAngle); }, initWithDuration: function initWithDuration(duration, deltaAngle) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._deltaAngle = deltaAngle; return true; } return false; }, clone: function clone() { var action = new cc.RotateBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._deltaAngle); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._startAngle = target.angle; }, update: function update(dt) { dt = this._computeEaseTime(dt); this.target && (this.target.angle = this._startAngle + this._deltaAngle * dt); }, reverse: function reverse() { var action = new cc.RotateBy(); action.initWithDuration(this._duration, -this._deltaAngle); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.rotateBy = function(duration, deltaAngle) { return new cc.RotateBy(duration, deltaAngle); }; cc.MoveBy = cc.Class({ name: "cc.MoveBy", extends: cc.ActionInterval, ctor: function ctor(duration, deltaPos, deltaY) { this._positionDelta = cc.v2(0, 0); this._startPosition = cc.v2(0, 0); this._previousPosition = cc.v2(0, 0); void 0 !== deltaPos && cc.MoveBy.prototype.initWithDuration.call(this, duration, deltaPos, deltaY); }, initWithDuration: function initWithDuration(duration, position, y) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { if (void 0 !== position.x) { y = position.y; position = position.x; } this._positionDelta.x = position; this._positionDelta.y = y; return true; } return false; }, clone: function clone() { var action = new cc.MoveBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._positionDelta); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var locPosX = target.x; var locPosY = target.y; this._previousPosition.x = locPosX; this._previousPosition.y = locPosY; this._startPosition.x = locPosX; this._startPosition.y = locPosY; }, update: function update(dt) { dt = this._computeEaseTime(dt); if (this.target) { var x = this._positionDelta.x * dt; var y = this._positionDelta.y * dt; var locStartPosition = this._startPosition; if (cc.macro.ENABLE_STACKABLE_ACTIONS) { var targetX = this.target.x; var targetY = this.target.y; var locPreviousPosition = this._previousPosition; locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x; locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; x += locStartPosition.x; y += locStartPosition.y; locPreviousPosition.x = x; locPreviousPosition.y = y; this.target.setPosition(x, y); } else this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } }, reverse: function reverse() { var action = new cc.MoveBy(this._duration, cc.v2(-this._positionDelta.x, -this._positionDelta.y)); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.moveBy = function(duration, deltaPos, deltaY) { return new cc.MoveBy(duration, deltaPos, deltaY); }; cc.MoveTo = cc.Class({ name: "cc.MoveTo", extends: cc.MoveBy, ctor: function ctor(duration, position, y) { this._endPosition = cc.v2(0, 0); void 0 !== position && this.initWithDuration(duration, position, y); }, initWithDuration: function initWithDuration(duration, position, y) { if (cc.MoveBy.prototype.initWithDuration.call(this, duration, position, y)) { if (void 0 !== position.x) { y = position.y; position = position.x; } this._endPosition.x = position; this._endPosition.y = y; return true; } return false; }, clone: function clone() { var action = new cc.MoveTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endPosition); return action; }, startWithTarget: function startWithTarget(target) { cc.MoveBy.prototype.startWithTarget.call(this, target); this._positionDelta.x = this._endPosition.x - target.x; this._positionDelta.y = this._endPosition.y - target.y; } }); cc.moveTo = function(duration, position, y) { return new cc.MoveTo(duration, position, y); }; cc.SkewTo = cc.Class({ name: "cc.SkewTo", extends: cc.ActionInterval, ctor: function ctor(t, sx, sy) { this._skewX = 0; this._skewY = 0; this._startSkewX = 0; this._startSkewY = 0; this._endSkewX = 0; this._endSkewY = 0; this._deltaX = 0; this._deltaY = 0; void 0 !== sy && cc.SkewTo.prototype.initWithDuration.call(this, t, sx, sy); }, initWithDuration: function initWithDuration(t, sx, sy) { var ret = false; if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._endSkewX = sx; this._endSkewY = sy; ret = true; } return ret; }, clone: function clone() { var action = new cc.SkewTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endSkewX, this._endSkewY); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._startSkewX = target.skewX % 180; this._deltaX = this._endSkewX - this._startSkewX; this._deltaX > 180 && (this._deltaX -= 360); this._deltaX < -180 && (this._deltaX += 360); this._startSkewY = target.skewY % 360; this._deltaY = this._endSkewY - this._startSkewY; this._deltaY > 180 && (this._deltaY -= 360); this._deltaY < -180 && (this._deltaY += 360); }, update: function update(dt) { dt = this._computeEaseTime(dt); this.target.skewX = this._startSkewX + this._deltaX * dt; this.target.skewY = this._startSkewY + this._deltaY * dt; } }); cc.skewTo = function(t, sx, sy) { return new cc.SkewTo(t, sx, sy); }; cc.SkewBy = cc.Class({ name: "cc.SkewBy", extends: cc.SkewTo, ctor: function ctor(t, sx, sy) { void 0 !== sy && this.initWithDuration(t, sx, sy); }, initWithDuration: function initWithDuration(t, deltaSkewX, deltaSkewY) { var ret = false; if (cc.SkewTo.prototype.initWithDuration.call(this, t, deltaSkewX, deltaSkewY)) { this._skewX = deltaSkewX; this._skewY = deltaSkewY; ret = true; } return ret; }, clone: function clone() { var action = new cc.SkewBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._skewX, this._skewY); return action; }, startWithTarget: function startWithTarget(target) { cc.SkewTo.prototype.startWithTarget.call(this, target); this._deltaX = this._skewX; this._deltaY = this._skewY; this._endSkewX = this._startSkewX + this._deltaX; this._endSkewY = this._startSkewY + this._deltaY; }, reverse: function reverse() { var action = new cc.SkewBy(this._duration, -this._skewX, -this._skewY); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.skewBy = function(t, sx, sy) { return new cc.SkewBy(t, sx, sy); }; cc.JumpBy = cc.Class({ name: "cc.JumpBy", extends: cc.ActionInterval, ctor: function ctor(duration, position, y, height, jumps) { this._startPosition = cc.v2(0, 0); this._previousPosition = cc.v2(0, 0); this._delta = cc.v2(0, 0); this._height = 0; this._jumps = 0; void 0 !== height && cc.JumpBy.prototype.initWithDuration.call(this, duration, position, y, height, jumps); }, initWithDuration: function initWithDuration(duration, position, y, height, jumps) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { if (void 0 === jumps) { jumps = height; height = y; y = position.y; position = position.x; } this._delta.x = position; this._delta.y = y; this._height = height; this._jumps = jumps; return true; } return false; }, clone: function clone() { var action = new cc.JumpBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._delta, this._height, this._jumps); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var locPosX = target.x; var locPosY = target.y; this._previousPosition.x = locPosX; this._previousPosition.y = locPosY; this._startPosition.x = locPosX; this._startPosition.y = locPosY; }, update: function update(dt) { dt = this._computeEaseTime(dt); if (this.target) { var frac = dt * this._jumps % 1; var y = 4 * this._height * frac * (1 - frac); y += this._delta.y * dt; var x = this._delta.x * dt; var locStartPosition = this._startPosition; if (cc.macro.ENABLE_STACKABLE_ACTIONS) { var targetX = this.target.x; var targetY = this.target.y; var locPreviousPosition = this._previousPosition; locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x; locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; x += locStartPosition.x; y += locStartPosition.y; locPreviousPosition.x = x; locPreviousPosition.y = y; this.target.setPosition(x, y); } else this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } }, reverse: function reverse() { var action = new cc.JumpBy(this._duration, cc.v2(-this._delta.x, -this._delta.y), this._height, this._jumps); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.jumpBy = function(duration, position, y, height, jumps) { return new cc.JumpBy(duration, position, y, height, jumps); }; cc.JumpTo = cc.Class({ name: "cc.JumpTo", extends: cc.JumpBy, ctor: function ctor(duration, position, y, height, jumps) { this._endPosition = cc.v2(0, 0); void 0 !== height && this.initWithDuration(duration, position, y, height, jumps); }, initWithDuration: function initWithDuration(duration, position, y, height, jumps) { if (cc.JumpBy.prototype.initWithDuration.call(this, duration, position, y, height, jumps)) { if (void 0 === jumps) { y = position.y; position = position.x; } this._endPosition.x = position; this._endPosition.y = y; return true; } return false; }, startWithTarget: function startWithTarget(target) { cc.JumpBy.prototype.startWithTarget.call(this, target); this._delta.x = this._endPosition.x - this._startPosition.x; this._delta.y = this._endPosition.y - this._startPosition.y; }, clone: function clone() { var action = new cc.JumpTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endPosition, this._height, this._jumps); return action; } }); cc.jumpTo = function(duration, position, y, height, jumps) { return new cc.JumpTo(duration, position, y, height, jumps); }; function bezierAt(a, b, c, d, t) { return Math.pow(1 - t, 3) * a + 3 * t * Math.pow(1 - t, 2) * b + 3 * Math.pow(t, 2) * (1 - t) * c + Math.pow(t, 3) * d; } cc.BezierBy = cc.Class({ name: "cc.BezierBy", extends: cc.ActionInterval, ctor: function ctor(t, c) { this._config = []; this._startPosition = cc.v2(0, 0); this._previousPosition = cc.v2(0, 0); c && cc.BezierBy.prototype.initWithDuration.call(this, t, c); }, initWithDuration: function initWithDuration(t, c) { if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._config = c; return true; } return false; }, clone: function clone() { var action = new cc.BezierBy(); this._cloneDecoration(action); var newConfigs = []; for (var i = 0; i < this._config.length; i++) { var selConf = this._config[i]; newConfigs.push(cc.v2(selConf.x, selConf.y)); } action.initWithDuration(this._duration, newConfigs); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var locPosX = target.x; var locPosY = target.y; this._previousPosition.x = locPosX; this._previousPosition.y = locPosY; this._startPosition.x = locPosX; this._startPosition.y = locPosY; }, update: function update(dt) { dt = this._computeEaseTime(dt); if (this.target) { var locConfig = this._config; var xa = 0; var xb = locConfig[0].x; var xc = locConfig[1].x; var xd = locConfig[2].x; var ya = 0; var yb = locConfig[0].y; var yc = locConfig[1].y; var yd = locConfig[2].y; var x = bezierAt(xa, xb, xc, xd, dt); var y = bezierAt(ya, yb, yc, yd, dt); var locStartPosition = this._startPosition; if (cc.macro.ENABLE_STACKABLE_ACTIONS) { var targetX = this.target.x; var targetY = this.target.y; var locPreviousPosition = this._previousPosition; locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x; locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; x += locStartPosition.x; y += locStartPosition.y; locPreviousPosition.x = x; locPreviousPosition.y = y; this.target.setPosition(x, y); } else this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } }, reverse: function reverse() { var locConfig = this._config; var x0 = locConfig[0].x, y0 = locConfig[0].y; var x1 = locConfig[1].x, y1 = locConfig[1].y; var x2 = locConfig[2].x, y2 = locConfig[2].y; var r = [ cc.v2(x1 - x2, y1 - y2), cc.v2(x0 - x2, y0 - y2), cc.v2(-x2, -y2) ]; var action = new cc.BezierBy(this._duration, r); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.bezierBy = function(t, c) { return new cc.BezierBy(t, c); }; cc.BezierTo = cc.Class({ name: "cc.BezierTo", extends: cc.BezierBy, ctor: function ctor(t, c) { this._toConfig = []; c && this.initWithDuration(t, c); }, initWithDuration: function initWithDuration(t, c) { if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._toConfig = c; return true; } return false; }, clone: function clone() { var action = new cc.BezierTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toConfig); return action; }, startWithTarget: function startWithTarget(target) { cc.BezierBy.prototype.startWithTarget.call(this, target); var locStartPos = this._startPosition; var locToConfig = this._toConfig; var locConfig = this._config; locConfig[0] = locToConfig[0].sub(locStartPos); locConfig[1] = locToConfig[1].sub(locStartPos); locConfig[2] = locToConfig[2].sub(locStartPos); } }); cc.bezierTo = function(t, c) { return new cc.BezierTo(t, c); }; cc.ScaleTo = cc.Class({ name: "cc.ScaleTo", extends: cc.ActionInterval, ctor: function ctor(duration, sx, sy) { this._scaleX = 1; this._scaleY = 1; this._startScaleX = 1; this._startScaleY = 1; this._endScaleX = 0; this._endScaleY = 0; this._deltaX = 0; this._deltaY = 0; void 0 !== sx && cc.ScaleTo.prototype.initWithDuration.call(this, duration, sx, sy); }, initWithDuration: function initWithDuration(duration, sx, sy) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._endScaleX = sx; this._endScaleY = null != sy ? sy : sx; return true; } return false; }, clone: function clone() { var action = new cc.ScaleTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endScaleX, this._endScaleY); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._startScaleX = target.scaleX; this._startScaleY = target.scaleY; this._deltaX = this._endScaleX - this._startScaleX; this._deltaY = this._endScaleY - this._startScaleY; }, update: function update(dt) { dt = this._computeEaseTime(dt); if (this.target) { this.target.scaleX = this._startScaleX + this._deltaX * dt; this.target.scaleY = this._startScaleY + this._deltaY * dt; } } }); cc.scaleTo = function(duration, sx, sy) { return new cc.ScaleTo(duration, sx, sy); }; cc.ScaleBy = cc.Class({ name: "cc.ScaleBy", extends: cc.ScaleTo, startWithTarget: function startWithTarget(target) { cc.ScaleTo.prototype.startWithTarget.call(this, target); this._deltaX = this._startScaleX * this._endScaleX - this._startScaleX; this._deltaY = this._startScaleY * this._endScaleY - this._startScaleY; }, reverse: function reverse() { var action = new cc.ScaleBy(this._duration, 1 / this._endScaleX, 1 / this._endScaleY); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function clone() { var action = new cc.ScaleBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endScaleX, this._endScaleY); return action; } }); cc.scaleBy = function(duration, sx, sy) { return new cc.ScaleBy(duration, sx, sy); }; cc.Blink = cc.Class({ name: "cc.Blink", extends: cc.ActionInterval, ctor: function ctor(duration, blinks) { this._times = 0; this._originalState = false; void 0 !== blinks && this.initWithDuration(duration, blinks); }, initWithDuration: function initWithDuration(duration, blinks) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._times = blinks; return true; } return false; }, clone: function clone() { var action = new cc.Blink(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._times); return action; }, update: function update(dt) { dt = this._computeEaseTime(dt); if (this.target && !this.isDone()) { var slice = 1 / this._times; var m = dt % slice; this.target.opacity = m > slice / 2 ? 255 : 0; } }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._originalState = target.opacity; }, stop: function stop() { this.target.opacity = this._originalState; cc.ActionInterval.prototype.stop.call(this); }, reverse: function reverse() { var action = new cc.Blink(this._duration, this._times); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.blink = function(duration, blinks) { return new cc.Blink(duration, blinks); }; cc.FadeTo = cc.Class({ name: "cc.FadeTo", extends: cc.ActionInterval, ctor: function ctor(duration, opacity) { this._toOpacity = 0; this._fromOpacity = 0; void 0 !== opacity && cc.FadeTo.prototype.initWithDuration.call(this, duration, opacity); }, initWithDuration: function initWithDuration(duration, opacity) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._toOpacity = opacity; return true; } return false; }, clone: function clone() { var action = new cc.FadeTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); return action; }, update: function update(time) { time = this._computeEaseTime(time); var fromOpacity = void 0 !== this._fromOpacity ? this._fromOpacity : 255; this.target.opacity = fromOpacity + (this._toOpacity - fromOpacity) * time; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._fromOpacity = target.opacity; } }); cc.fadeTo = function(duration, opacity) { return new cc.FadeTo(duration, opacity); }; cc.FadeIn = cc.Class({ name: "cc.FadeIn", extends: cc.FadeTo, ctor: function ctor(duration) { null == duration && (duration = 0); this._reverseAction = null; this.initWithDuration(duration, 255); }, reverse: function reverse() { var action = new cc.FadeOut(); action.initWithDuration(this._duration, 0); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function clone() { var action = new cc.FadeIn(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); return action; }, startWithTarget: function startWithTarget(target) { this._reverseAction && (this._toOpacity = this._reverseAction._fromOpacity); cc.FadeTo.prototype.startWithTarget.call(this, target); } }); cc.fadeIn = function(duration) { return new cc.FadeIn(duration); }; cc.FadeOut = cc.Class({ name: "cc.FadeOut", extends: cc.FadeTo, ctor: function ctor(duration) { null == duration && (duration = 0); this._reverseAction = null; this.initWithDuration(duration, 0); }, reverse: function reverse() { var action = new cc.FadeIn(); action._reverseAction = this; action.initWithDuration(this._duration, 255); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function clone() { var action = new cc.FadeOut(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); return action; } }); cc.fadeOut = function(d) { return new cc.FadeOut(d); }; cc.TintTo = cc.Class({ name: "cc.TintTo", extends: cc.ActionInterval, ctor: function ctor(duration, red, green, blue) { this._to = cc.color(0, 0, 0); this._from = cc.color(0, 0, 0); if (red instanceof cc.Color) { blue = red.b; green = red.g; red = red.r; } void 0 !== blue && this.initWithDuration(duration, red, green, blue); }, initWithDuration: function initWithDuration(duration, red, green, blue) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._to = cc.color(red, green, blue); return true; } return false; }, clone: function clone() { var action = new cc.TintTo(); this._cloneDecoration(action); var locTo = this._to; action.initWithDuration(this._duration, locTo.r, locTo.g, locTo.b); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._from = this.target.color; }, update: function update(dt) { dt = this._computeEaseTime(dt); var locFrom = this._from, locTo = this._to; locFrom && (this.target.color = cc.color(locFrom.r + (locTo.r - locFrom.r) * dt, locFrom.g + (locTo.g - locFrom.g) * dt, locFrom.b + (locTo.b - locFrom.b) * dt)); } }); cc.tintTo = function(duration, red, green, blue) { return new cc.TintTo(duration, red, green, blue); }; cc.TintBy = cc.Class({ name: "cc.TintBy", extends: cc.ActionInterval, ctor: function ctor(duration, deltaRed, deltaGreen, deltaBlue) { this._deltaR = 0; this._deltaG = 0; this._deltaB = 0; this._fromR = 0; this._fromG = 0; this._fromB = 0; void 0 !== deltaBlue && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue); }, initWithDuration: function initWithDuration(duration, deltaRed, deltaGreen, deltaBlue) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._deltaR = deltaRed; this._deltaG = deltaGreen; this._deltaB = deltaBlue; return true; } return false; }, clone: function clone() { var action = new cc.TintBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var color = target.color; this._fromR = color.r; this._fromG = color.g; this._fromB = color.b; }, update: function update(dt) { dt = this._computeEaseTime(dt); this.target.color = cc.color(this._fromR + this._deltaR * dt, this._fromG + this._deltaG * dt, this._fromB + this._deltaB * dt); }, reverse: function reverse() { var action = new cc.TintBy(this._duration, -this._deltaR, -this._deltaG, -this._deltaB); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.tintBy = function(duration, deltaRed, deltaGreen, deltaBlue) { return new cc.TintBy(duration, deltaRed, deltaGreen, deltaBlue); }; cc.DelayTime = cc.Class({ name: "cc.DelayTime", extends: cc.ActionInterval, update: function update(dt) {}, reverse: function reverse() { var action = new cc.DelayTime(this._duration); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function clone() { var action = new cc.DelayTime(); this._cloneDecoration(action); action.initWithDuration(this._duration); return action; } }); cc.delayTime = function(d) { return new cc.DelayTime(d); }; cc.ReverseTime = cc.Class({ name: "cc.ReverseTime", extends: cc.ActionInterval, ctor: function ctor(action) { this._other = null; action && this.initWithAction(action); }, initWithAction: function initWithAction(action) { if (!action) { cc.errorID(1028); return false; } if (action === this._other) { cc.errorID(1029); return false; } if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) { this._other = action; return true; } return false; }, clone: function clone() { var action = new cc.ReverseTime(); this._cloneDecoration(action); action.initWithAction(this._other.clone()); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._other.startWithTarget(target); }, update: function update(dt) { dt = this._computeEaseTime(dt); this._other && this._other.update(1 - dt); }, reverse: function reverse() { return this._other.clone(); }, stop: function stop() { this._other.stop(); cc.Action.prototype.stop.call(this); } }); cc.reverseTime = function(action) { return new cc.ReverseTime(action); }; cc.TargetedAction = cc.Class({ name: "cc.TargetedAction", extends: cc.ActionInterval, ctor: function ctor(target, action) { this._action = null; this._forcedTarget = null; action && this.initWithTarget(target, action); }, initWithTarget: function initWithTarget(target, action) { if (this.initWithDuration(action._duration)) { this._forcedTarget = target; this._action = action; return true; } return false; }, clone: function clone() { var action = new cc.TargetedAction(); this._cloneDecoration(action); action.initWithTarget(this._forcedTarget, this._action.clone()); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._action.startWithTarget(this._forcedTarget); }, stop: function stop() { this._action.stop(); }, update: function update(dt) { dt = this._computeEaseTime(dt); this._action.update(dt); }, getForcedTarget: function getForcedTarget() { return this._forcedTarget; }, setForcedTarget: function setForcedTarget(forcedTarget) { this._forcedTarget !== forcedTarget && (this._forcedTarget = forcedTarget); } }); cc.targetedAction = function(target, action) { return new cc.TargetedAction(target, action); }; }), {} ], 7: [ (function(require, module, exports) { "use strict"; require("../core/platform/CCClass"); var js = require("../core/platform/js"); var HashElement = function HashElement() { this.actions = []; this.target = null; this.actionIndex = 0; this.currentAction = null; this.paused = false; this.lock = false; }; cc.ActionManager = function() { this._hashTargets = js.createMap(true); this._arrayTargets = []; this._currentTarget = null; cc.director._scheduler && cc.director._scheduler.enableForTarget(this); }; cc.ActionManager.prototype = { constructor: cc.ActionManager, _elementPool: [], _searchElementByTarget: function _searchElementByTarget(arr, target) { for (var k = 0; k < arr.length; k++) if (target === arr[k].target) return arr[k]; return null; }, _getElement: function _getElement(target, paused) { var element = this._elementPool.pop(); element || (element = new HashElement()); element.target = target; element.paused = !!paused; return element; }, _putElement: function _putElement(element) { element.actions.length = 0; element.actionIndex = 0; element.currentAction = null; element.paused = false; element.target = null; element.lock = false; this._elementPool.push(element); }, addAction: function addAction(action, target, paused) { if (!action || !target) { cc.errorID(1e3); return; } var element = this._hashTargets[target._id]; if (element) element.actions || (element.actions = []); else { element = this._getElement(target, paused); this._hashTargets[target._id] = element; this._arrayTargets.push(element); } element.actions.push(action); action.startWithTarget(target); }, removeAllActions: function removeAllActions() { var locTargets = this._arrayTargets; for (var i = 0; i < locTargets.length; i++) { var element = locTargets[i]; element && this._putElement(element); } this._arrayTargets.length = 0; this._hashTargets = js.createMap(true); }, removeAllActionsFromTarget: function removeAllActionsFromTarget(target, forceDelete) { if (null == target) return; var element = this._hashTargets[target._id]; if (element) { element.actions.length = 0; this._deleteHashElement(element); } }, removeAction: function removeAction(action) { if (!action) return; var target = action.getOriginalTarget(); var element = this._hashTargets[target._id]; if (!element) return; for (var i = 0; i < element.actions.length; i++) if (element.actions[i] === action) { element.actions.splice(i, 1); element.actionIndex >= i && element.actionIndex--; break; } }, _removeActionByTag: function _removeActionByTag(tag, element, target) { for (var i = 0, l = element.actions.length; i < l; ++i) { var action = element.actions[i]; if (action && action.getTag() === tag) { if (target && action.getOriginalTarget() !== target) continue; this._removeActionAtIndex(i, element); break; } } }, _removeAllActionsByTag: function _removeAllActionsByTag(tag, element, target) { for (var i = element.actions.length - 1; i >= 0; --i) { var action = element.actions[i]; if (action && action.getTag() === tag) { if (target && action.getOriginalTarget() !== target) continue; this._removeActionAtIndex(i, element); } } }, removeActionByTag: function removeActionByTag(tag, target) { tag === cc.Action.TAG_INVALID && cc.logID(1002); var hashTargets = this._hashTargets; if (target) { var element = hashTargets[target._id]; element && this._removeActionByTag(tag, element, target); } else for (var name in hashTargets) { var _element = hashTargets[name]; this._removeActionByTag(tag, _element); } }, removeAllActionsByTag: function removeAllActionsByTag(tag, target) { tag === cc.Action.TAG_INVALID && cc.logID(1002); var hashTargets = this._hashTargets; if (target) { var element = hashTargets[target._id]; element && this._removeAllActionsByTag(tag, element, target); } else for (var name in hashTargets) { var _element2 = hashTargets[name]; this._removeAllActionsByTag(tag, _element2); } }, getActionByTag: function getActionByTag(tag, target) { tag === cc.Action.TAG_INVALID && cc.logID(1004); var element = this._hashTargets[target._id]; if (element) { if (null != element.actions) for (var i = 0; i < element.actions.length; ++i) { var action = element.actions[i]; if (action && action.getTag() === tag) return action; } cc.logID(1005, tag); } return null; }, getNumberOfRunningActionsInTarget: function getNumberOfRunningActionsInTarget(target) { var element = this._hashTargets[target._id]; if (element) return element.actions ? element.actions.length : 0; return 0; }, pauseTarget: function pauseTarget(target) { var element = this._hashTargets[target._id]; element && (element.paused = true); }, resumeTarget: function resumeTarget(target) { var element = this._hashTargets[target._id]; element && (element.paused = false); }, pauseAllRunningActions: function pauseAllRunningActions() { var idsWithActions = []; var locTargets = this._arrayTargets; for (var i = 0; i < locTargets.length; i++) { var element = locTargets[i]; if (element && !element.paused) { element.paused = true; idsWithActions.push(element.target); } } return idsWithActions; }, resumeTargets: function resumeTargets(targetsToResume) { if (!targetsToResume) return; for (var i = 0; i < targetsToResume.length; i++) targetsToResume[i] && this.resumeTarget(targetsToResume[i]); }, pauseTargets: function pauseTargets(targetsToPause) { if (!targetsToPause) return; for (var i = 0; i < targetsToPause.length; i++) targetsToPause[i] && this.pauseTarget(targetsToPause[i]); }, purgeSharedManager: function purgeSharedManager() { cc.director.getScheduler().unscheduleUpdate(this); }, _removeActionAtIndex: function _removeActionAtIndex(index, element) { var action = element.actions[index]; element.actions.splice(index, 1); element.actionIndex >= index && element.actionIndex--; 0 === element.actions.length && this._deleteHashElement(element); }, _deleteHashElement: function _deleteHashElement(element) { var ret = false; if (element && !element.lock && this._hashTargets[element.target._id]) { delete this._hashTargets[element.target._id]; var targets = this._arrayTargets; for (var i = 0, l = targets.length; i < l; i++) if (targets[i] === element) { targets.splice(i, 1); break; } this._putElement(element); ret = true; } return ret; }, update: function update(dt) { var locTargets = this._arrayTargets, locCurrTarget; for (var elt = 0; elt < locTargets.length; elt++) { this._currentTarget = locTargets[elt]; locCurrTarget = this._currentTarget; if (!locCurrTarget.paused && locCurrTarget.actions) { locCurrTarget.lock = true; for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; locCurrTarget.actionIndex++) { locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex]; if (!locCurrTarget.currentAction) continue; locCurrTarget.currentAction.step(dt * (locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1)); if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) { locCurrTarget.currentAction.stop(); var action = locCurrTarget.currentAction; locCurrTarget.currentAction = null; this.removeAction(action); } locCurrTarget.currentAction = null; } locCurrTarget.lock = false; } 0 === locCurrTarget.actions.length && this._deleteHashElement(locCurrTarget) && elt--; } } }; false; }), { "../core/platform/CCClass": 129, "../core/platform/js": 150 } ], 8: [ (function(require, module, exports) { "use strict"; require("./CCActionManager"); require("./CCAction"); require("./CCActionInterval"); require("./CCActionInstant"); require("./CCActionEase"); require("./CCActionCatmullRom"); require("./tween"); }), { "./CCAction": 2, "./CCActionCatmullRom": 3, "./CCActionEase": 4, "./CCActionInstant": 5, "./CCActionInterval": 6, "./CCActionManager": 7, "./tween": 9 } ], 9: [ (function(require, module, exports) { "use strict"; var _bezier = require("../animation/bezier"); var _tweenID = 0; var TweenAction = cc.Class({ name: "cc.TweenAction", extends: cc.ActionInterval, ctor: function ctor(duration, props, opts) { this._opts = opts = opts || Object.create(null); this._props = Object.create(null); opts.progress = opts.progress || this.progress; if (opts.easing && "string" === typeof opts.easing) { var easingName = opts.easing; opts.easing = cc.easing[easingName]; !opts.easing && cc.warnID(1031, easingName); } var relative = this._opts.relative; for (var name in props) { var value = props[name]; var easing = void 0, progress = void 0; if (void 0 !== value.value && (value.easing || value.progress)) { if ("string" === typeof value.easing) { easing = cc.easing[value.easing]; !easing && cc.warnID(1031, value.easing); } else easing = value.easing; progress = value.progress; value = value.value; } var isNumber = "number" === typeof value; if (!isNumber && (!value.lerp || relative && !value.add && !value.mul || !value.clone)) { cc.warn("Can not animate " + name + " property, because it do not have [lerp, (add|mul), clone] function."); continue; } var prop = Object.create(null); prop.value = value; prop.easing = easing; prop.progress = progress; this._props[name] = prop; } this._originProps = props; this.initWithDuration(duration); }, clone: function clone() { var action = new TweenAction(this._duration, this._originProps, this._opts); this._cloneDecoration(action); return action; }, startWithTarget: function startWithTarget(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var relative = !!this._opts.relative; var props = this._props; for (var name in props) { var value = target[name]; var prop = props[name]; if ("number" === typeof value) { prop.start = value; prop.current = value; prop.end = relative ? value + prop.value : prop.value; } else { prop.start = value.clone(); prop.current = value.clone(); prop.end = relative ? (value.add || value.mul).call(value, prop.value) : prop.value; } } }, update: function update(t) { var opts = this._opts; var easingTime = t; opts.easing && (easingTime = opts.easing(t)); var target = this.target; if (!target) return; var props = this._props; var progress = opts.progress; for (var name in props) { var prop = props[name]; var time = prop.easing ? prop.easing(t) : easingTime; var current = prop.current = (prop.progress || progress)(prop.start, prop.end, prop.current, time); target[name] = current; } var onUpdate = opts.onUpdate; onUpdate && onUpdate(target, t); }, progress: function progress(start, end, current, t) { "number" === typeof start ? current = start + (end - start) * t : start.lerp(end, t, current); return current; } }); var SetAction = cc.Class({ name: "cc.SetAction", extends: cc.ActionInstant, ctor: function ctor(props) { this._props = {}; void 0 !== props && this.init(props); }, init: function init(props) { for (var name in props) this._props[name] = props[name]; return true; }, update: function update() { var props = this._props; var target = this.target; for (var name in props) target[name] = props[name]; }, clone: function clone() { var action = new SetAction(); action.init(this._props); return action; } }); function Tween(target) { this._actions = []; this._finalAction = null; this._target = target; this._tag = cc.Action.TAG_INVALID; } Tween.stopAll = function() { cc.director.getActionManager().removeAllActions(); }; Tween.stopAllByTag = function(tag) { cc.director.getActionManager().removeAllActionsByTag(tag); }; Tween.stopAllByTarget = function(target) { cc.director.getActionManager().removeAllActionsFromTarget(target); }; Tween.prototype.then = function(other) { other instanceof cc.Action ? this._actions.push(other.clone()) : this._actions.push(other._union()); return this; }; Tween.prototype.target = function(target) { this._target = target; return this; }; Tween.prototype.start = function() { var target = this._target; if (!target) { cc.warn("Please set target to tween first"); return this; } if (target instanceof cc.Object && !target.isValid) return; this._finalAction && cc.director.getActionManager().removeAction(this._finalAction); this._finalAction = this._union(); void 0 === target._id && (target._id = ++_tweenID); this._finalAction.setTag(this._tag); cc.director.getActionManager().addAction(this._finalAction, target, false); return this; }; Tween.prototype.stop = function() { this._finalAction && cc.director.getActionManager().removeAction(this._finalAction); return this; }; Tween.prototype.tag = function(tag) { this._tag = tag; return this; }; Tween.prototype.clone = function(target) { var action = this._union(); return cc.tween(target).then(action.clone()); }; Tween.prototype.union = function() { var action = this._union(); this._actions.length = 0; this._actions.push(action); return this; }; Tween.prototype._union = function() { var actions = this._actions; actions = 1 === actions.length ? actions[0] : cc.sequence(actions); return actions; }; Object.assign(Tween.prototype, { bezierTo: function bezierTo(duration, c1, c2, to, opts) { var c0x = c1.x, c0y = c1.y, c1x = c2.x, c1y = c2.y; opts = opts || Object.create(null); opts.progress = function(start, end, current, t) { current.x = (0, _bezier.bezier)(start.x, c0x, c1x, end.x, t); current.y = (0, _bezier.bezier)(start.y, c0y, c1y, end.y, t); return current; }; return this.to(duration, { position: to }, opts); }, bezierBy: function bezierBy(duration, c1, c2, to, opts) { var c0x = c1.x, c0y = c1.y, c1x = c2.x, c1y = c2.y; opts = opts || Object.create(null); opts.progress = function(start, end, current, t) { var sx = start.x, sy = start.y; current.x = (0, _bezier.bezier)(sx, c0x + sx, c1x + sx, end.x, t); current.y = (0, _bezier.bezier)(sy, c0y + sy, c1y + sy, end.y, t); return current; }; return this.by(duration, { position: to }, opts); }, flipX: function flipX() { var _this = this; return this.call((function() { _this._target.scaleX *= -1; }), this); }, flipY: function flipY() { var _this2 = this; return this.call((function() { _this2._target.scaleY *= -1; }), this); }, blink: function blink(duration, times, opts) { var slice = 1 / times; opts = opts || Object.create(null); opts.progress = function(start, end, current, t) { if (t >= 1) return start; var m = t % slice; return m > slice / 2 ? 255 : 0; }; return this.to(duration, { opacity: 1 }, opts); } }); var tmp_args = []; function wrapAction(action) { return function() { tmp_args.length = 0; for (var l = arguments.length, i = 0; i < l; i++) { var arg = tmp_args[i] = arguments[i]; arg instanceof Tween && (tmp_args[i] = arg._union()); } return action.apply(this, tmp_args); }; } var actions = { to: function to(duration, props, opts) { opts = opts || Object.create(null); opts.relative = false; return new TweenAction(duration, props, opts); }, by: function by(duration, props, opts) { opts = opts || Object.create(null); opts.relative = true; return new TweenAction(duration, props, opts); }, set: function set(props) { return new SetAction(props); }, delay: cc.delayTime, call: cc.callFunc, hide: cc.hide, show: cc.show, removeSelf: cc.removeSelf, sequence: wrapAction(cc.sequence), parallel: wrapAction(cc.spawn) }; var previousAsInputActions = { repeat: cc.repeat, repeatForever: cc.repeatForever, reverseTime: cc.reverseTime }; var keys = Object.keys(actions); var _loop = function _loop(i) { var key = keys[i]; Tween.prototype[key] = function() { var action = actions[key].apply(this, arguments); this._actions.push(action); return this; }; }; for (var i = 0; i < keys.length; i++) _loop(i); keys = Object.keys(previousAsInputActions); var _loop2 = function _loop2(_i) { var key = keys[_i]; Tween.prototype[key] = function() { var actions = this._actions; var action = arguments[arguments.length - 1]; var length = arguments.length - 1; if (action instanceof cc.Tween) action = action._union(); else if (!(action instanceof cc.Action)) { action = actions[actions.length - 1]; actions.length -= 1; length += 1; } var args = [ action ]; for (var _i2 = 0; _i2 < length; _i2++) args.push(arguments[_i2]); action = previousAsInputActions[key].apply(this, args); actions.push(action); return this; }; }; for (var _i = 0; _i < keys.length; _i++) _loop2(_i); cc.tween = function(target) { return new Tween(target); }; cc.Tween = Tween; }), { "../animation/bezier": 15 } ], 10: [ (function(require, module, exports) { "use strict"; var js = cc.js; var Playable = require("./playable"); var _require = require("./animation-curves"), EventAnimCurve = _require.EventAnimCurve, EventInfo = _require.EventInfo; var WrapModeMask = require("./types").WrapModeMask; var binarySearch = require("../core/utils/binary-search").binarySearchEpsilon; function AnimationAnimator(target, animation) { Playable.call(this); this.target = target; this.animation = animation; this._anims = new js.array.MutableForwardIterator([]); } js.extend(AnimationAnimator, Playable); var p = AnimationAnimator.prototype; p.playState = function(state, startTime) { if (!state.clip) return; state.curveLoaded || initClipData(this.target, state); state.animator = this; state.play(); "number" === typeof startTime && state.setTime(startTime); this.play(); }; p.stopStatesExcept = function(state) { var iterator = this._anims; var array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { var anim = array[iterator.i]; if (anim === state) continue; this.stopState(anim); } }; p.addAnimation = function(anim) { var index = this._anims.array.indexOf(anim); -1 === index && this._anims.push(anim); anim._setEventTarget(this.animation); }; p.removeAnimation = function(anim) { var index = this._anims.array.indexOf(anim); if (index >= 0) { this._anims.fastRemoveAt(index); 0 === this._anims.array.length && this.stop(); } else cc.errorID(3907); anim.animator = null; }; p.sample = function() { var iterator = this._anims; var array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { var anim = array[iterator.i]; anim.sample(); } }; p.stopState = function(state) { state && state.stop(); }; p.pauseState = function(state) { state && state.pause(); }; p.resumeState = function(state) { state && state.resume(); this.isPaused && this.resume(); }; p.setStateTime = function(state, time) { if (void 0 !== time) { if (state) { state.setTime(time); state.sample(); } } else { time = state; var array = this._anims.array; for (var i = 0; i < array.length; ++i) { var anim = array[i]; anim.setTime(time); anim.sample(); } } }; p.onStop = function() { var iterator = this._anims; var array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { var anim = array[iterator.i]; anim.stop(); } }; p.onPause = function() { var array = this._anims.array; for (var i = 0; i < array.length; ++i) { var anim = array[i]; anim.pause(); anim.animator = null; } }; p.onResume = function() { var array = this._anims.array; for (var i = 0; i < array.length; ++i) { var anim = array[i]; anim.animator = this; anim.resume(); } }; p._reloadClip = function(state) { initClipData(this.target, state); }; function createBatchedProperty(propPath, firstDotIndex, mainValue, animValue) { mainValue = mainValue.clone(); var nextValue = mainValue; var leftIndex = firstDotIndex + 1; var rightIndex = propPath.indexOf(".", leftIndex); while (-1 !== rightIndex) { var nextName = propPath.slice(leftIndex, rightIndex); nextValue = nextValue[nextName]; leftIndex = rightIndex + 1; rightIndex = propPath.indexOf(".", leftIndex); } var lastPropName = propPath.slice(leftIndex); nextValue[lastPropName] = animValue; return mainValue; } false; function initClipData(root, state) { var clip = state.clip; state.duration = clip.duration; state.speed = clip.speed; state.wrapMode = clip.wrapMode; state.frameRate = clip.sample; (state.wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop ? state.repeatCount = Infinity : state.repeatCount = 1; var curves = state.curves = clip.createCurves(state, root); var events = clip.events; if (true, events) { var curve; for (var i = 0, l = events.length; i < l; i++) { if (!curve) { curve = new EventAnimCurve(); curve.target = root; curves.push(curve); } var eventData = events[i]; var ratio = eventData.frame / state.duration; var eventInfo = void 0; var index = binarySearch(curve.ratios, ratio); if (index >= 0) eventInfo = curve.events[index]; else { eventInfo = new EventInfo(); curve.ratios.push(ratio); curve.events.push(eventInfo); } eventInfo.add(eventData.func, eventData.params); } } } false; module.exports = AnimationAnimator; }), { "../core/utils/binary-search": 210, "./animation-curves": 12, "./playable": 19, "./types": 20 } ], 11: [ (function(require, module, exports) { "use strict"; var WrapMode = require("./types").WrapMode; var _require = require("./animation-curves"), DynamicAnimCurve = _require.DynamicAnimCurve, quickFindIndex = _require.quickFindIndex; var sampleMotionPaths = require("./motion-path-helper").sampleMotionPaths; var binarySearch = require("../core/utils/binary-search").binarySearchEpsilon; var AnimationClip = cc.Class({ name: "cc.AnimationClip", extends: cc.Asset, properties: { _duration: { default: 0, type: cc.Float }, duration: { get: function get() { return this._duration; } }, sample: { default: 60 }, speed: { default: 1 }, wrapMode: { default: WrapMode.Normal }, curveData: { default: {}, visible: false }, events: { default: [], visible: false } }, statics: { createWithSpriteFrames: function createWithSpriteFrames(spriteFrames, sample) { if (!Array.isArray(spriteFrames)) { cc.errorID(3905); return null; } var clip = new AnimationClip(); clip.sample = sample || clip.sample; clip._duration = spriteFrames.length / clip.sample; var frames = []; var step = 1 / clip.sample; for (var i = 0, l = spriteFrames.length; i < l; i++) frames[i] = { frame: i * step, value: spriteFrames[i] }; clip.curveData = { comps: { "cc.Sprite": { spriteFrame: frames } } }; return clip; } }, onLoad: function onLoad() { this._duration = Number.parseFloat(this.duration); this.speed = Number.parseFloat(this.speed); this.wrapMode = Number.parseInt(this.wrapMode); this.frameRate = Number.parseFloat(this.sample); }, createPropCurve: function createPropCurve(target, propPath, keyframes) { var motionPaths = []; var isMotionPathProp = target instanceof cc.Node && "position" === propPath; var curve = new DynamicAnimCurve(); curve.target = target; curve.prop = propPath; for (var i = 0, l = keyframes.length; i < l; i++) { var keyframe = keyframes[i]; var ratio = keyframe.frame / this.duration; curve.ratios.push(ratio); isMotionPathProp && motionPaths.push(keyframe.motionPath); var curveValue = keyframe.value; curve.values.push(curveValue); var curveTypes = keyframe.curve; if (curveTypes) { if ("string" === typeof curveTypes) { curve.types.push(curveTypes); continue; } if (Array.isArray(curveTypes)) { curveTypes[0] === curveTypes[1] && curveTypes[2] === curveTypes[3] ? curve.types.push(DynamicAnimCurve.Linear) : curve.types.push(DynamicAnimCurve.Bezier(curveTypes)); continue; } } curve.types.push(DynamicAnimCurve.Linear); } isMotionPathProp && sampleMotionPaths(motionPaths, curve, this.duration, this.sample, target); var ratios = curve.ratios; var currRatioDif, lastRatioDif; var canOptimize = true; var EPSILON = 1e-6; for (var _i = 1, _l = ratios.length; _i < _l; _i++) { currRatioDif = ratios[_i] - ratios[_i - 1]; if (1 === _i) lastRatioDif = currRatioDif; else if (Math.abs(currRatioDif - lastRatioDif) > EPSILON) { canOptimize = false; break; } } curve._findFrameIndex = canOptimize ? quickFindIndex : binarySearch; var firstValue = curve.values[0]; void 0 === firstValue || null === firstValue || curve._lerp || ("number" === typeof firstValue ? curve._lerp = DynamicAnimCurve.prototype._lerpNumber : firstValue instanceof cc.Quat ? curve._lerp = DynamicAnimCurve.prototype._lerpQuat : firstValue instanceof cc.Vec2 ? curve._lerp = DynamicAnimCurve.prototype._lerpVector2 : firstValue instanceof cc.Vec3 ? curve._lerp = DynamicAnimCurve.prototype._lerpVector3 : firstValue.lerp && (curve._lerp = DynamicAnimCurve.prototype._lerpObject)); return curve; }, createTargetCurves: function createTargetCurves(target, curveData, curves) { var propsData = curveData.props; var compsData = curveData.comps; if (propsData) for (var propPath in propsData) { var data = propsData[propPath]; var curve = this.createPropCurve(target, propPath, data); curves.push(curve); } if (compsData) for (var compName in compsData) { var comp = target.getComponent(compName); if (!comp) continue; var compData = compsData[compName]; for (var _propPath in compData) { var _data = compData[_propPath]; var _curve = this.createPropCurve(comp, _propPath, _data); curves.push(_curve); } } }, createCurves: function createCurves(state, root) { var curveData = this.curveData; var childrenCurveDatas = curveData.paths; var curves = []; this.createTargetCurves(root, curveData, curves); for (var namePath in childrenCurveDatas) { var target = cc.find(namePath, root); if (!target) continue; var childCurveDatas = childrenCurveDatas[namePath]; this.createTargetCurves(target, childCurveDatas, curves); } return curves; } }); cc.AnimationClip = module.exports = AnimationClip; }), { "../core/utils/binary-search": 210, "./animation-curves": 12, "./motion-path-helper": 18, "./types": 20 } ], 12: [ (function(require, module, exports) { "use strict"; var bezierByTime = require("./bezier").bezierByTime; var binarySearch = require("../core/utils/binary-search").binarySearchEpsilon; var WrapModeMask = require("./types").WrapModeMask; var WrappedInfo = require("./types").WrappedInfo; function computeRatioByType(ratio, type) { if ("string" === typeof type) { var func = cc.easing[type]; func ? ratio = func(ratio) : cc.errorID(3906, type); } else Array.isArray(type) && (ratio = bezierByTime(type, ratio)); return ratio; } var AnimCurve = cc.Class({ name: "cc.AnimCurve", sample: function sample(time, ratio, state) {}, onTimeChangedManually: void 0 }); function quickFindIndex(ratios, ratio) { var length = ratios.length - 1; if (0 === length) return 0; var start = ratios[0]; if (ratio < start) return 0; var end = ratios[length]; if (ratio > end) return ~ratios.length; ratio = (ratio - start) / (end - start); var eachLength = 1 / length; var index = ratio / eachLength; var floorIndex = 0 | index; var EPSILON = 1e-6; if (index - floorIndex < EPSILON) return floorIndex; if (floorIndex + 1 - index < EPSILON) return floorIndex + 1; return ~(floorIndex + 1); } var DynamicAnimCurve = cc.Class({ name: "cc.DynamicAnimCurve", extends: AnimCurve, ctor: function ctor() { this._cachedIndex = 0; }, properties: { target: null, prop: "", values: [], ratios: [], types: [] }, _findFrameIndex: binarySearch, _lerp: void 0, _lerpNumber: function _lerpNumber(from, to, t) { return from + (to - from) * t; }, _lerpObject: function _lerpObject(from, to, t) { return from.lerp(to, t); }, _lerpQuat: (function() { var out = cc.quat(); return function(from, to, t) { return from.lerp(to, t, out); }; })(), _lerpVector2: (function() { var out = cc.v2(); return function(from, to, t) { return from.lerp(to, t, out); }; })(), _lerpVector3: (function() { var out = cc.v3(); return function(from, to, t) { return from.lerp(to, t, out); }; })(), sample: function sample(time, ratio, state) { var values = this.values; var ratios = this.ratios; var frameCount = ratios.length; if (0 === frameCount) return; var shoudRefind = true; var cachedIndex = this._cachedIndex; if (cachedIndex < 0) { cachedIndex = ~cachedIndex; if (cachedIndex > 0 && cachedIndex < ratios.length) { var _fromRatio = ratios[cachedIndex - 1]; var _toRatio = ratios[cachedIndex]; ratio > _fromRatio && ratio < _toRatio && (shoudRefind = false); } } shoudRefind && (this._cachedIndex = this._findFrameIndex(ratios, ratio)); var value; var index = this._cachedIndex; if (index < 0) { index = ~index; if (index <= 0) value = values[0]; else if (index >= frameCount) value = values[frameCount - 1]; else { var fromVal = values[index - 1]; if (this._lerp) { var fromRatio = ratios[index - 1]; var toRatio = ratios[index]; var type = this.types[index - 1]; var ratioBetweenFrames = (ratio - fromRatio) / (toRatio - fromRatio); type && (ratioBetweenFrames = computeRatioByType(ratioBetweenFrames, type)); var toVal = values[index]; value = this._lerp(fromVal, toVal, ratioBetweenFrames); } else value = fromVal; } } else value = values[index]; this.target[this.prop] = value; } }); DynamicAnimCurve.Linear = null; DynamicAnimCurve.Bezier = function(controlPoints) { return controlPoints; }; var EventInfo = function EventInfo() { this.events = []; }; EventInfo.prototype.add = function(func, params) { this.events.push({ func: func || "", params: params || [] }); }; var EventAnimCurve = cc.Class({ name: "cc.EventAnimCurve", extends: AnimCurve, properties: { target: null, ratios: [], events: [], _wrappedInfo: { default: function _default() { return new WrappedInfo(); } }, _lastWrappedInfo: null, _ignoreIndex: NaN }, _wrapIterations: function _wrapIterations(iterations) { iterations - (0 | iterations) === 0 && (iterations -= 1); return 0 | iterations; }, sample: function sample(time, ratio, state) { var length = this.ratios.length; var currentWrappedInfo = state.getWrappedInfo(state.time, this._wrappedInfo); var direction = currentWrappedInfo.direction; var currentIndex = binarySearch(this.ratios, currentWrappedInfo.ratio); if (currentIndex < 0) { currentIndex = ~currentIndex - 1; direction < 0 && (currentIndex += 1); } this._ignoreIndex !== currentIndex && (this._ignoreIndex = NaN); currentWrappedInfo.frameIndex = currentIndex; if (!this._lastWrappedInfo) { this._fireEvent(currentIndex); this._lastWrappedInfo = new WrappedInfo(currentWrappedInfo); return; } var wrapMode = state.wrapMode; var currentIterations = this._wrapIterations(currentWrappedInfo.iterations); var lastWrappedInfo = this._lastWrappedInfo; var lastIterations = this._wrapIterations(lastWrappedInfo.iterations); var lastIndex = lastWrappedInfo.frameIndex; var lastDirection = lastWrappedInfo.direction; var interationsChanged = -1 !== lastIterations && currentIterations !== lastIterations; if (lastIndex === currentIndex && interationsChanged && 1 === length) this._fireEvent(0); else if (lastIndex !== currentIndex || interationsChanged) { direction = lastDirection; do { if (lastIndex !== currentIndex) { if (-1 === direction && 0 === lastIndex && currentIndex > 0) { (wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong ? direction *= -1 : lastIndex = length; lastIterations++; } else if (1 === direction && lastIndex === length - 1 && currentIndex < length - 1) { (wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong ? direction *= -1 : lastIndex = -1; lastIterations++; } if (lastIndex === currentIndex) break; if (lastIterations > currentIterations) break; } lastIndex += direction; cc.director.getAnimationManager().pushDelayEvent(this, "_fireEvent", [ lastIndex ]); } while (lastIndex !== currentIndex && lastIndex > -1 && lastIndex < length); } this._lastWrappedInfo.set(currentWrappedInfo); }, _fireEvent: function _fireEvent(index) { if (index < 0 || index >= this.events.length || this._ignoreIndex === index) return; var eventInfo = this.events[index]; var events = eventInfo.events; if (!this.target.isValid) return; var components = this.target._components; for (var i = 0; i < events.length; i++) { var event = events[i]; var funcName = event.func; for (var j = 0; j < components.length; j++) { var component = components[j]; var func = component[funcName]; func && func.apply(component, event.params); } } }, onTimeChangedManually: function onTimeChangedManually(time, state) { this._lastWrappedInfo = null; this._ignoreIndex = NaN; var info = state.getWrappedInfo(time, this._wrappedInfo); var direction = info.direction; var frameIndex = binarySearch(this.ratios, info.ratio); if (frameIndex < 0) { frameIndex = ~frameIndex - 1; direction < 0 && (frameIndex += 1); this._ignoreIndex = frameIndex; } } }); false; module.exports = { AnimCurve: AnimCurve, DynamicAnimCurve: DynamicAnimCurve, EventAnimCurve: EventAnimCurve, EventInfo: EventInfo, computeRatioByType: computeRatioByType, quickFindIndex: quickFindIndex }; }), { "../core/utils/binary-search": 210, "./bezier": 15, "./types": 20 } ], 13: [ (function(require, module, exports) { "use strict"; var js = cc.js; var AnimationManager = cc.Class({ ctor: function ctor() { this._anims = new js.array.MutableForwardIterator([]); this._delayEvents = []; cc.director._scheduler && cc.director._scheduler.enableForTarget(this); }, update: function update(dt) { var iterator = this._anims; var array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { var anim = array[iterator.i]; anim._isPlaying && !anim._isPaused && anim.update(dt); } var events = this._delayEvents; for (var i = 0; i < events.length; i++) { var event = events[i]; event.target[event.func].apply(event.target, event.args); } events.length = 0; }, destruct: function destruct() {}, addAnimation: function addAnimation(anim) { var index = this._anims.array.indexOf(anim); -1 === index && this._anims.push(anim); }, removeAnimation: function removeAnimation(anim) { var index = this._anims.array.indexOf(anim); index >= 0 ? this._anims.fastRemoveAt(index) : cc.errorID(3907); }, pushDelayEvent: function pushDelayEvent(target, func, args) { this._delayEvents.push({ target: target, func: func, args: args }); } }); cc.AnimationManager = module.exports = AnimationManager; }), {} ], 14: [ (function(require, module, exports) { "use strict"; var js = cc.js; var Playable = require("./playable"); var Types = require("./types"); var WrappedInfo = Types.WrappedInfo; var WrapMode = Types.WrapMode; var WrapModeMask = Types.WrapModeMask; function AnimationState(clip, name) { Playable.call(this); this._currentFramePlayed = false; this._delay = 0; this._delayTime = 0; this._wrappedInfo = new WrappedInfo(); this._lastWrappedInfo = null; this._process = process; this._clip = clip; this._name = name || clip && clip.name; this.animator = null; this.curves = []; this.delay = 0; this.repeatCount = 1; this.duration = 1; this.speed = 1; this.wrapMode = WrapMode.Normal; this.time = 0; this._target = null; this._lastframeEventOn = false; this.emit = function() { var args = new Array(arguments.length); for (var i = 0, l = args.length; i < l; i++) args[i] = arguments[i]; cc.director.getAnimationManager().pushDelayEvent(this, "_emit", args); }; } js.extend(AnimationState, Playable); var proto = AnimationState.prototype; proto._emit = function(type, state) { this._target && this._target.isValid && this._target.emit(type, type, state); }; proto.on = function(type, callback, target) { if (this._target && this._target.isValid) { "lastframe" === type && (this._lastframeEventOn = true); return this._target.on(type, callback, target); } return null; }; proto.once = function(type, callback, target) { if (this._target && this._target.isValid) { "lastframe" === type && (this._lastframeEventOn = true); var self = this; return this._target.once(type, (function(event) { callback.call(target, event); self._lastframeEventOn = false; })); } return null; }; proto.off = function(type, callback, target) { if (this._target && this._target.isValid) { "lastframe" === type && (this._target.hasEventListener(type) || (this._lastframeEventOn = false)); this._target.off(type, callback, target); } }; proto._setEventTarget = function(target) { this._target = target; }; proto.onPlay = function() { this.setTime(0); this._delayTime = this._delay; cc.director.getAnimationManager().addAnimation(this); this.animator && this.animator.addAnimation(this); this.emit("play", this); }; proto.onStop = function() { this.isPaused || cc.director.getAnimationManager().removeAnimation(this); this.animator && this.animator.removeAnimation(this); this.emit("stop", this); }; proto.onResume = function() { cc.director.getAnimationManager().addAnimation(this); this.emit("resume", this); }; proto.onPause = function() { cc.director.getAnimationManager().removeAnimation(this); this.emit("pause", this); }; proto.setTime = function(time) { this._currentFramePlayed = false; this.time = time || 0; var curves = this.curves; for (var i = 0, l = curves.length; i < l; i++) { var curve = curves[i]; curve.onTimeChangedManually && curve.onTimeChangedManually(time, this); } }; function process() { var info = this.sample(); if (this._lastframeEventOn) { var lastInfo; lastInfo = this._lastWrappedInfo ? this._lastWrappedInfo : this._lastWrappedInfo = new WrappedInfo(info); this.repeatCount > 1 && (0 | info.iterations) > (0 | lastInfo.iterations) && this.emit("lastframe", this); lastInfo.set(info); } if (info.stopped) { this.stop(); this.emit("finished", this); } } function simpleProcess() { var time = this.time; var duration = this.duration; if (time > duration) { time %= duration; 0 === time && (time = duration); } else if (time < 0) { time %= duration; 0 !== time && (time += duration); } var ratio = time / duration; var curves = this.curves; for (var i = 0, len = curves.length; i < len; i++) { var curve = curves[i]; curve.sample(time, ratio, this); } if (this._lastframeEventOn) { void 0 === this._lastIterations && (this._lastIterations = ratio); (this.time > 0 && this._lastIterations > ratio || this.time < 0 && this._lastIterations < ratio) && this.emit("lastframe", this); this._lastIterations = ratio; } } proto.update = function(delta) { if (this._delayTime > 0) { this._delayTime -= delta; if (this._delayTime > 0) return; } this._currentFramePlayed ? this.time += delta * this.speed : this._currentFramePlayed = true; this._process(); }; proto._needRevers = function(currentIterations) { var wrapMode = this.wrapMode; var needRevers = false; if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) { var isEnd = currentIterations - (0 | currentIterations) === 0; isEnd && currentIterations > 0 && (currentIterations -= 1); var isOddIteration = 1 & currentIterations; isOddIteration && (needRevers = !needRevers); } (wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse && (needRevers = !needRevers); return needRevers; }; proto.getWrappedInfo = function(time, info) { info = info || new WrappedInfo(); var stopped = false; var duration = this.duration; var repeatCount = this.repeatCount; var currentIterations = time > 0 ? time / duration : -time / duration; if (currentIterations >= repeatCount) { currentIterations = repeatCount; stopped = true; var tempRatio = repeatCount - (0 | repeatCount); 0 === tempRatio && (tempRatio = 1); time = tempRatio * duration * (time > 0 ? 1 : -1); } if (time > duration) { var tempTime = time % duration; time = 0 === tempTime ? duration : tempTime; } else if (time < 0) { time %= duration; 0 !== time && (time += duration); } var needRevers = false; var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap; shouldWrap && (needRevers = this._needRevers(currentIterations)); var direction = needRevers ? -1 : 1; this.speed < 0 && (direction *= -1); shouldWrap && needRevers && (time = duration - time); info.ratio = time / duration; info.time = time; info.direction = direction; info.stopped = stopped; info.iterations = currentIterations; return info; }; proto.sample = function() { var info = this.getWrappedInfo(this.time, this._wrappedInfo); var curves = this.curves; for (var i = 0, len = curves.length; i < len; i++) { var curve = curves[i]; curve.sample(info.time, info.ratio, this); } return info; }; js.get(proto, "clip", (function() { return this._clip; })); js.get(proto, "name", (function() { return this._name; })); js.obsolete(proto, "AnimationState.length", "duration"); js.getset(proto, "curveLoaded", (function() { return this.curves.length > 0; }), (function() { this.curves.length = 0; })); js.getset(proto, "wrapMode", (function() { return this._wrapMode; }), (function(value) { this._wrapMode = value; false; this.time = 0; value & WrapModeMask.Loop ? this.repeatCount = Infinity : this.repeatCount = 1; })); js.getset(proto, "repeatCount", (function() { return this._repeatCount; }), (function(value) { this._repeatCount = value; var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap; var reverse = (this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse; this._process = Infinity !== value || shouldWrap || reverse ? process : simpleProcess; })); js.getset(proto, "delay", (function() { return this._delay; }), (function(value) { this._delayTime = this._delay = value; })); cc.AnimationState = module.exports = AnimationState; }), { "./playable": 19, "./types": 20 } ], 15: [ (function(require, module, exports) { "use strict"; function bezier(C1, C2, C3, C4, t) { var t1 = 1 - t; return t1 * (t1 * (C1 + (3 * C2 - C1) * t) + 3 * C3 * t * t) + C4 * t * t * t; } var cos = Math.cos, acos = Math.acos, max = Math.max, pi = Math.PI, tau = 2 * pi, sqrt = Math.sqrt; function crt(v) { return v < 0 ? -Math.pow(-v, 1 / 3) : Math.pow(v, 1 / 3); } function cardano(curve, x) { var pa = x - 0; var pb = x - curve[0]; var pc = x - curve[2]; var pd = x - 1; var pa3 = 3 * pa; var pb3 = 3 * pb; var pc3 = 3 * pc; var d = -pa + pb3 - pc3 + pd, rd = 1 / d, r3 = 1 / 3, a = (pa3 - 6 * pb + pc3) * rd, a3 = a * r3, b = (-pa3 + pb3) * rd, c = pa * rd, p = (3 * b - a * a) * r3, p3 = p * r3, q = (2 * a * a * a - 9 * a * b + 27 * c) / 27, q2 = q / 2, discriminant = q2 * q2 + p3 * p3 * p3, u1, v1, x1, x2, x3; if (discriminant < 0) { var mp3 = -p * r3, mp33 = mp3 * mp3 * mp3, r = sqrt(mp33), t = -q / (2 * r), cosphi = t < -1 ? -1 : t > 1 ? 1 : t, phi = acos(cosphi), crtr = crt(r), t1 = 2 * crtr; x1 = t1 * cos(phi * r3) - a3; x2 = t1 * cos((phi + tau) * r3) - a3; x3 = t1 * cos((phi + 2 * tau) * r3) - a3; return 0 <= x1 && x1 <= 1 ? 0 <= x2 && x2 <= 1 ? 0 <= x3 && x3 <= 1 ? max(x1, x2, x3) : max(x1, x2) : 0 <= x3 && x3 <= 1 ? max(x1, x3) : x1 : 0 <= x2 && x2 <= 1 ? 0 <= x3 && x3 <= 1 ? max(x2, x3) : x2 : x3; } if (0 === discriminant) { u1 = q2 < 0 ? crt(-q2) : -crt(q2); x1 = 2 * u1 - a3; x2 = -u1 - a3; return 0 <= x1 && x1 <= 1 ? 0 <= x2 && x2 <= 1 ? max(x1, x2) : x1 : x2; } var sd = sqrt(discriminant); u1 = crt(-q2 + sd); v1 = crt(q2 + sd); x1 = u1 - v1 - a3; return x1; } function bezierByTime(controlPoints, x) { var percent = cardano(controlPoints, x); var p1y = controlPoints[1]; var p2y = controlPoints[3]; return ((1 - percent) * (p1y + (p2y - p1y) * percent) * 3 + percent * percent) * percent; } false; module.exports = { bezier: bezier, bezierByTime: bezierByTime }; }), {} ], 16: [ (function(require, module, exports) { "use strict"; var easing = { constant: function constant() { return 0; }, linear: function linear(k) { return k; }, quadIn: function quadIn(k) { return k * k; }, quadOut: function quadOut(k) { return k * (2 - k); }, quadInOut: function quadInOut(k) { if ((k *= 2) < 1) return .5 * k * k; return -.5 * (--k * (k - 2) - 1); }, cubicIn: function cubicIn(k) { return k * k * k; }, cubicOut: function cubicOut(k) { return --k * k * k + 1; }, cubicInOut: function cubicInOut(k) { if ((k *= 2) < 1) return .5 * k * k * k; return .5 * ((k -= 2) * k * k + 2); }, quartIn: function quartIn(k) { return k * k * k * k; }, quartOut: function quartOut(k) { return 1 - --k * k * k * k; }, quartInOut: function quartInOut(k) { if ((k *= 2) < 1) return .5 * k * k * k * k; return -.5 * ((k -= 2) * k * k * k - 2); }, quintIn: function quintIn(k) { return k * k * k * k * k; }, quintOut: function quintOut(k) { return --k * k * k * k * k + 1; }, quintInOut: function quintInOut(k) { if ((k *= 2) < 1) return .5 * k * k * k * k * k; return .5 * ((k -= 2) * k * k * k * k + 2); }, sineIn: function sineIn(k) { return 1 - Math.cos(k * Math.PI / 2); }, sineOut: function sineOut(k) { return Math.sin(k * Math.PI / 2); }, sineInOut: function sineInOut(k) { return .5 * (1 - Math.cos(Math.PI * k)); }, expoIn: function expoIn(k) { return 0 === k ? 0 : Math.pow(1024, k - 1); }, expoOut: function expoOut(k) { return 1 === k ? 1 : 1 - Math.pow(2, -10 * k); }, expoInOut: function expoInOut(k) { if (0 === k) return 0; if (1 === k) return 1; if ((k *= 2) < 1) return .5 * Math.pow(1024, k - 1); return .5 * (2 - Math.pow(2, -10 * (k - 1))); }, circIn: function circIn(k) { return 1 - Math.sqrt(1 - k * k); }, circOut: function circOut(k) { return Math.sqrt(1 - --k * k); }, circInOut: function circInOut(k) { if ((k *= 2) < 1) return -.5 * (Math.sqrt(1 - k * k) - 1); return .5 * (Math.sqrt(1 - (k -= 2) * k) + 1); }, elasticIn: function elasticIn(k) { var s, a = .1, p = .4; if (0 === k) return 0; if (1 === k) return 1; if (!a || a < 1) { a = 1; s = p / 4; } else s = p * Math.asin(1 / a) / (2 * Math.PI); return -a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p); }, elasticOut: function elasticOut(k) { var s, a = .1, p = .4; if (0 === k) return 0; if (1 === k) return 1; if (!a || a < 1) { a = 1; s = p / 4; } else s = p * Math.asin(1 / a) / (2 * Math.PI); return a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1; }, elasticInOut: function elasticInOut(k) { var s, a = .1, p = .4; if (0 === k) return 0; if (1 === k) return 1; if (!a || a < 1) { a = 1; s = p / 4; } else s = p * Math.asin(1 / a) / (2 * Math.PI); if ((k *= 2) < 1) return a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * -.5; return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * .5 + 1; }, backIn: function backIn(k) { var s = 1.70158; return k * k * ((s + 1) * k - s); }, backOut: function backOut(k) { var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; }, backInOut: function backInOut(k) { var s = 2.5949095; if ((k *= 2) < 1) return k * k * ((s + 1) * k - s) * .5; return .5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); }, bounceIn: function bounceIn(k) { return 1 - easing.bounceOut(1 - k); }, bounceOut: function bounceOut(k) { return k < 1 / 2.75 ? 7.5625 * k * k : k < 2 / 2.75 ? 7.5625 * (k -= 1.5 / 2.75) * k + .75 : k < 2.5 / 2.75 ? 7.5625 * (k -= 2.25 / 2.75) * k + .9375 : 7.5625 * (k -= 2.625 / 2.75) * k + .984375; }, bounceInOut: function bounceInOut(k) { if (k < .5) return .5 * easing.bounceIn(2 * k); return .5 * easing.bounceOut(2 * k - 1) + .5; }, smooth: function smooth(t) { if (t <= 0) return 0; if (t >= 1) return 1; return t * t * (3 - 2 * t); }, fade: function fade(t) { if (t <= 0) return 0; if (t >= 1) return 1; return t * t * t * (t * (6 * t - 15) + 10); } }; function _makeOutIn(fnIn, fnOut) { return function(k) { if (k < .5) return fnOut(2 * k) / 2; return fnIn(2 * k - 1) / 2 + .5; }; } easing.quadOutIn = _makeOutIn(easing.quadIn, easing.quadOut); easing.cubicOutIn = _makeOutIn(easing.cubicIn, easing.cubicOut); easing.quartOutIn = _makeOutIn(easing.quartIn, easing.quartOut); easing.quintOutIn = _makeOutIn(easing.quintIn, easing.quintOut); easing.sineOutIn = _makeOutIn(easing.sineIn, easing.sineOut); easing.expoOutIn = _makeOutIn(easing.expoIn, easing.expoOut); easing.circOutIn = _makeOutIn(easing.circIn, easing.circOut); easing.backOutIn = _makeOutIn(easing.backIn, easing.backOut); easing.bounceIn = function(k) { return 1 - easing.bounceOut(1 - k); }; easing.bounceInOut = function(k) { if (k < .5) return .5 * easing.bounceIn(2 * k); return .5 * easing.bounceOut(2 * k - 1) + .5; }; easing.bounceOutIn = _makeOutIn(easing.bounceIn, easing.bounceOut); cc.easing = module.exports = easing; }), {} ], 17: [ (function(require, module, exports) { "use strict"; require("./bezier"); require("./easing"); require("./types"); require("./motion-path-helper"); require("./animation-curves"); require("./animation-clip"); require("./animation-manager"); require("./animation-state"); require("./animation-animator"); }), { "./animation-animator": 10, "./animation-clip": 11, "./animation-curves": 12, "./animation-manager": 13, "./animation-state": 14, "./bezier": 15, "./easing": 16, "./motion-path-helper": 18, "./types": 20 } ], 18: [ (function(require, module, exports) { "use strict"; var DynamicAnimCurve = require("./animation-curves").DynamicAnimCurve; var computeRatioByType = require("./animation-curves").computeRatioByType; var bezier = require("./bezier").bezier; var binarySearch = require("../core/utils/binary-search").binarySearchEpsilon; var v2 = cc.v2; function Curve(points) { this.points = points || []; this.beziers = []; this.ratios = []; this.progresses = []; this.length = 0; this.computeBeziers(); } Curve.prototype.computeBeziers = function() { this.beziers.length = 0; this.ratios.length = 0; this.progresses.length = 0; this.length = 0; var bezier; for (var i = 1; i < this.points.length; i++) { var startPoint = this.points[i - 1]; var endPoint = this.points[i]; bezier = new Bezier(); bezier.start = startPoint.pos; bezier.startCtrlPoint = startPoint.out; bezier.end = endPoint.pos; bezier.endCtrlPoint = endPoint["in"]; this.beziers.push(bezier); this.length += bezier.getLength(); } var current = 0; for (var i = 0; i < this.beziers.length; i++) { bezier = this.beziers[i]; this.ratios[i] = bezier.getLength() / this.length; this.progresses[i] = current += this.ratios[i]; } return this.beziers; }; function Bezier() { this.start = v2(); this.end = v2(); this.startCtrlPoint = v2(); this.endCtrlPoint = v2(); } Bezier.prototype.getPointAt = function(u) { var t = this.getUtoTmapping(u); return this.getPoint(t); }; Bezier.prototype.getPoint = function(t) { var x = bezier(this.start.x, this.startCtrlPoint.x, this.endCtrlPoint.x, this.end.x, t); var y = bezier(this.start.y, this.startCtrlPoint.y, this.endCtrlPoint.y, this.end.y, t); return new v2(x, y); }; Bezier.prototype.getLength = function() { var lengths = this.getLengths(); return lengths[lengths.length - 1]; }; Bezier.prototype.getLengths = function(divisions) { divisions || (divisions = this.__arcLengthDivisions ? this.__arcLengthDivisions : 200); if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1) return this.cacheArcLengths; var cache = []; var current, last = this.getPoint(0), vector = v2(); var p, sum = 0; cache.push(0); for (p = 1; p <= divisions; p++) { current = this.getPoint(p / divisions); vector.x = last.x - current.x; vector.y = last.y - current.y; sum += vector.mag(); cache.push(sum); last = current; } this.cacheArcLengths = cache; return cache; }; Bezier.prototype.getUtoTmapping = function(u, distance) { var arcLengths = this.getLengths(); var i = 0, il = arcLengths.length; var targetArcLength; targetArcLength = distance || u * arcLengths[il - 1]; var low = 0, high = il - 1, comparison; while (low <= high) { i = Math.floor(low + (high - low) / 2); comparison = arcLengths[i] - targetArcLength; if (comparison < 0) { low = i + 1; continue; } if (comparison > 0) { high = i - 1; continue; } high = i; break; } i = high; if (arcLengths[i] === targetArcLength) { var t = i / (il - 1); return t; } var lengthBefore = arcLengths[i]; var lengthAfter = arcLengths[i + 1]; var segmentLength = lengthAfter - lengthBefore; var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; var t = (i + segmentFraction) / (il - 1); return t; }; function checkMotionPath(motionPath) { if (!Array.isArray(motionPath)) return false; for (var i = 0, l = motionPath.length; i < l; i++) { var controls = motionPath[i]; if (!Array.isArray(controls) || 6 !== controls.length) return false; } return true; } function sampleMotionPaths(motionPaths, data, duration, fps, target) { function createControlPoints(array) { if (array instanceof cc.Vec2) return { in: array, pos: array, out: array }; if (Array.isArray(array) && 6 === array.length) return { in: v2(array[2], array[3]), pos: v2(array[0], array[1]), out: v2(array[4], array[5]) }; return { in: cc.Vec2.ZERO, pos: cc.Vec2.ZERO, out: cc.Vec2.ZERO }; } var values = data.values = data.values.map((function(value) { Array.isArray(value) && (value = 2 === value.length ? cc.v2(value[0], value[1]) : cc.v3(value[0], value[1], value[2])); return value; })); if (0 === motionPaths.length || 0 === values.length) return; var motionPathValid = false; for (var _i = 0; _i < motionPaths.length; _i++) { var _motionPath = motionPaths[_i]; if (_motionPath && !checkMotionPath(_motionPath)) { cc.errorID(3904, target ? target.name : "", "position", _i); _motionPath = null; } if (_motionPath && _motionPath.length > 0) { motionPathValid = true; break; } } if (!motionPathValid) return; if (1 === values.length) return; var types = data.types; var ratios = data.ratios; var newValues = data.values = []; var newTypes = data.types = []; var newRatios = data.ratios = []; function addNewDatas(value, type, ratio) { newValues.push(value); newTypes.push(type); newRatios.push(ratio); } var startRatioOffset = 0; var EPSILON = 1e-6; var newType = DynamicAnimCurve.Linear; for (var i = 0, l = motionPaths.length; i < l - 1; i++) { var motionPath = motionPaths[i]; var ratio = ratios[i]; var nextRatio = ratios[i + 1]; var betweenRatio = nextRatio - ratio; var value = values[i]; var nextValue = values[i + 1]; var type = types[i]; var results = []; var progress = startRatioOffset / betweenRatio; var speed = 1 / (betweenRatio * duration * fps); var finalProgress; if (motionPath && motionPath.length > 0) { var points = []; points.push(createControlPoints(value)); for (var j = 0, l2 = motionPath.length; j < l2; j++) { var controlPoints = createControlPoints(motionPath[j]); points.push(controlPoints); } points.push(createControlPoints(nextValue)); var curve = new Curve(points); curve.computeBeziers(); var progresses = curve.progresses; while (1 - progress > EPSILON) { finalProgress = progress; finalProgress = computeRatioByType(finalProgress, type); var pos, bezier, normal, length; if (finalProgress < 0) { bezier = curve.beziers[0]; length = (0 - finalProgress) * bezier.getLength(); normal = bezier.start.sub(bezier.endCtrlPoint).normalize(); pos = bezier.start.add(normal.mul(length)); } else if (finalProgress > 1) { bezier = curve.beziers[curve.beziers.length - 1]; length = (finalProgress - 1) * bezier.getLength(); normal = bezier.end.sub(bezier.startCtrlPoint).normalize(); pos = bezier.end.add(normal.mul(length)); } else { var bezierIndex = binarySearch(progresses, finalProgress); bezierIndex < 0 && (bezierIndex = ~bezierIndex); finalProgress -= bezierIndex > 0 ? progresses[bezierIndex - 1] : 0; finalProgress /= curve.ratios[bezierIndex]; pos = curve.beziers[bezierIndex].getPointAt(finalProgress); } results.push(pos); progress += speed; } } else while (1 - progress > EPSILON) { finalProgress = progress; finalProgress = computeRatioByType(finalProgress, type); results.push(value.lerp(nextValue, finalProgress)); progress += speed; } newType = "constant" === type ? type : DynamicAnimCurve.Linear; for (var j = 0, l2 = results.length; j < l2; j++) { var newRatio = ratio + startRatioOffset + speed * j * betweenRatio; addNewDatas(results[j], newType, newRatio); } startRatioOffset = Math.abs(progress - 1) > EPSILON ? (progress - 1) * betweenRatio : 0; } ratios[ratios.length - 1] !== newRatios[newRatios.length - 1] && addNewDatas(values[values.length - 1], newType, ratios[ratios.length - 1]); } false; module.exports = { sampleMotionPaths: sampleMotionPaths, Curve: Curve, Bezier: Bezier }; }), { "../core/utils/binary-search": 210, "./animation-curves": 12, "./bezier": 15 } ], 19: [ (function(require, module, exports) { "use strict"; var js = cc.js; var debug = require("../core/CCDebug"); function Playable() { this._isPlaying = false; this._isPaused = false; this._stepOnce = false; } var prototype = Playable.prototype; js.get(prototype, "isPlaying", (function() { return this._isPlaying; }), true); js.get(prototype, "isPaused", (function() { return this._isPaused; }), true); var virtual = function virtual() {}; prototype.onPlay = virtual; prototype.onPause = virtual; prototype.onResume = virtual; prototype.onStop = virtual; prototype.onError = virtual; prototype.play = function() { if (this._isPlaying) if (this._isPaused) { this._isPaused = false; this.onResume(); } else this.onError(debug.getError(3912)); else { this._isPlaying = true; this.onPlay(); } }; prototype.stop = function() { if (this._isPlaying) { this._isPlaying = false; this.onStop(); this._isPaused = false; } }; prototype.pause = function() { if (this._isPlaying && !this._isPaused) { this._isPaused = true; this.onPause(); } }; prototype.resume = function() { if (this._isPlaying && this._isPaused) { this._isPaused = false; this.onResume(); } }; prototype.step = function() { this.pause(); this._stepOnce = true; this._isPlaying || this.play(); }; module.exports = Playable; }), { "../core/CCDebug": 21 } ], 20: [ (function(require, module, exports) { "use strict"; var WrapModeMask = { Loop: 2, ShouldWrap: 4, PingPong: 22, Reverse: 36 }; var WrapMode = cc.Enum({ Default: 0, Normal: 1, Reverse: WrapModeMask.Reverse, Loop: WrapModeMask.Loop, LoopReverse: WrapModeMask.Loop | WrapModeMask.Reverse, PingPong: WrapModeMask.PingPong, PingPongReverse: WrapModeMask.PingPong | WrapModeMask.Reverse }); cc.WrapMode = WrapMode; function WrappedInfo(info) { if (info) { this.set(info); return; } this.ratio = 0; this.time = 0; this.direction = 1; this.stopped = true; this.iterations = 0; this.frameIndex = void 0; } WrappedInfo.prototype.set = function(info) { this.ratio = info.ratio; this.time = info.time; this.direction = info.direction; this.stopped = info.stopped; this.iterations = info.iterations; this.frameIndex = info.frameIndex; }; module.exports = { WrapModeMask: WrapModeMask, WrapMode: WrapMode, WrappedInfo: WrappedInfo }; }), {} ], 21: [ (function(require, module, exports) { "use strict"; var utils = require("./platform/utils"); var debugInfos = require("../../DebugInfos") || {}; var ERROR_MAP_URL = "https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md"; var logList; cc.log = cc.warn = cc.error = cc.assert = console.log.bind ? console.log.bind(console) : console.log; var resetDebugSetting = function resetDebugSetting(mode) { cc.log = cc.warn = cc.error = cc.assert = function() {}; if (mode === DebugMode.NONE) return; if (mode > DebugMode.ERROR) { var logToWebPage = function logToWebPage(msg) { if (!cc.game.canvas) return; if (!logList) { var logDiv = document.createElement("Div"); logDiv.setAttribute("id", "logInfoDiv"); logDiv.setAttribute("width", "200"); logDiv.setAttribute("height", cc.game.canvas.height); var logDivStyle = logDiv.style; logDivStyle.zIndex = "99999"; logDivStyle.position = "absolute"; logDivStyle.top = logDivStyle.left = "0"; logList = document.createElement("textarea"); logList.setAttribute("rows", "20"); logList.setAttribute("cols", "30"); logList.setAttribute("disabled", "true"); var logListStyle = logList.style; logListStyle.backgroundColor = "transparent"; logListStyle.borderBottom = "1px solid #cccccc"; logListStyle.borderTopWidth = logListStyle.borderLeftWidth = logListStyle.borderRightWidth = "0px"; logListStyle.borderTopStyle = logListStyle.borderLeftStyle = logListStyle.borderRightStyle = "none"; logListStyle.padding = "0px"; logListStyle.margin = 0; logDiv.appendChild(logList); cc.game.canvas.parentNode.appendChild(logDiv); } logList.value = logList.value + msg + "\r\n"; logList.scrollTop = logList.scrollHeight; }; cc.error = function() { logToWebPage("ERROR : " + cc.js.formatStr.apply(null, arguments)); }; cc.assert = function(cond, msg) { if (!cond && msg) { msg = cc.js.formatStr.apply(null, cc.js.shiftArguments.apply(null, arguments)); logToWebPage("ASSERT: " + msg); } }; mode !== DebugMode.ERROR_FOR_WEB_PAGE && (cc.warn = function() { logToWebPage("WARN : " + cc.js.formatStr.apply(null, arguments)); }); mode === DebugMode.INFO_FOR_WEB_PAGE && (cc.log = function() { logToWebPage(cc.js.formatStr.apply(null, arguments)); }); } else if (console && console.log.apply) { console.error || (console.error = console.log); console.warn || (console.warn = console.log); false; console.error.bind ? cc.error = console.error.bind(console) : cc.error = (false, function() { return console.error.apply(console, arguments); }); cc.assert = function(cond, msg) { if (!cond) { msg && (msg = cc.js.formatStr.apply(null, cc.js.shiftArguments.apply(null, arguments))); false; false; throw new Error(msg); } }; } if (mode !== DebugMode.ERROR) { false; console.warn.bind ? cc.warn = console.warn.bind(console) : cc.warn = (false, function() { return console.warn.apply(console, arguments); }); } false; if (mode === DebugMode.INFO) { false, false; console.log.bind ? cc.log = console.log.bind(console) : cc.log = function() { return console.log.apply(console, arguments); }; } }; cc._throw = function(error) { utils.callInNextTick((function() { throw error; })); }; function getTypedFormatter(type) { return function() { var id = arguments[0]; var msg = debugInfos[id] || "unknown id"; if (1 === arguments.length) return msg; if (2 === arguments.length) return cc.js.formatStr(msg, arguments[1]); var argsArray = cc.js.shiftArguments.apply(null, arguments); return cc.js.formatStr.apply(null, [ msg ].concat(argsArray)); }; } var logFormatter = getTypedFormatter("Log"); cc.logID = function() { cc.log(logFormatter.apply(null, arguments)); }; var warnFormatter = getTypedFormatter("Warning"); cc.warnID = function() { cc.warn(warnFormatter.apply(null, arguments)); }; var errorFormatter = getTypedFormatter("Error"); cc.errorID = function() { cc.error(errorFormatter.apply(null, arguments)); }; var assertFormatter = getTypedFormatter("Assert"); cc.assertID = function(cond) { if (cond) return; cc.assert(false, assertFormatter.apply(null, cc.js.shiftArguments.apply(null, arguments))); }; var DebugMode = cc.Enum({ NONE: 0, INFO: 1, WARN: 2, ERROR: 3, INFO_FOR_WEB_PAGE: 4, WARN_FOR_WEB_PAGE: 5, ERROR_FOR_WEB_PAGE: 6 }); module.exports = cc.debug = { DebugMode: DebugMode, _resetDebugSetting: resetDebugSetting, getError: getTypedFormatter("ERROR"), isDisplayStats: function isDisplayStats() { return !!cc.profiler && cc.profiler.isShowingStats(); }, setDisplayStats: function setDisplayStats(displayStats) { if (cc.profiler && cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { displayStats ? cc.profiler.showStats() : cc.profiler.hideStats(); cc.game.config.showFPS = !!displayStats; } } }; }), { "../../DebugInfos": 1, "./platform/utils": 153 } ], 22: [ (function(require, module, exports) { "use strict"; var EventTarget = require("./event/event-target"); var ComponentScheduler = require("./component-scheduler"); var NodeActivator = require("./node-activator"); var Obj = require("./platform/CCObject"); var game = require("./CCGame"); var renderer = require("./renderer"); var eventManager = require("./event-manager"); var Scheduler = require("./CCScheduler"); cc.Director = function() { EventTarget.call(this); this._paused = false; this._purgeDirectorInNextLoop = false; this._winSizeInPoints = null; this._scene = null; this._loadingScene = ""; this._totalFrames = 0; this._lastUpdate = 0; this._deltaTime = 0; this._startTime = 0; this._maxParticleDeltaTime = 0; this._scheduler = null; this._compScheduler = null; this._nodeActivator = null; this._actionManager = null; var self = this; game.on(game.EVENT_SHOW, (function() { self._lastUpdate = performance.now(); })); game.once(game.EVENT_ENGINE_INITED, this.init, this); }; cc.Director.prototype = { constructor: cc.Director, init: function init() { this._totalFrames = 0; this._lastUpdate = performance.now(); this._startTime = this._lastUpdate; this._paused = false; this._purgeDirectorInNextLoop = false; this._winSizeInPoints = cc.size(0, 0); this._scheduler = new Scheduler(); if (cc.ActionManager) { this._actionManager = new cc.ActionManager(); this._scheduler.scheduleUpdate(this._actionManager, Scheduler.PRIORITY_SYSTEM, false); } else this._actionManager = null; this.sharedInit(); return true; }, sharedInit: function sharedInit() { this._compScheduler = new ComponentScheduler(); this._nodeActivator = new NodeActivator(); eventManager && eventManager.setEnabled(true); if (cc.AnimationManager) { this._animationManager = new cc.AnimationManager(); this._scheduler.scheduleUpdate(this._animationManager, Scheduler.PRIORITY_SYSTEM, false); } else this._animationManager = null; if (cc.CollisionManager) { this._collisionManager = new cc.CollisionManager(); this._scheduler.scheduleUpdate(this._collisionManager, Scheduler.PRIORITY_SYSTEM, false); } else this._collisionManager = null; if (cc.PhysicsManager) { this._physicsManager = new cc.PhysicsManager(); this._scheduler.scheduleUpdate(this._physicsManager, Scheduler.PRIORITY_SYSTEM, false); } else this._physicsManager = null; if (cc.Physics3DManager && (false, false)) { this._physics3DManager = new cc.Physics3DManager(); this._scheduler.scheduleUpdate(this._physics3DManager, Scheduler.PRIORITY_SYSTEM, false); } else this._physics3DManager = null; cc._widgetManager && cc._widgetManager.init(this); }, calculateDeltaTime: function calculateDeltaTime(now) { now || (now = performance.now()); this._deltaTime = now > this._lastUpdate ? (now - this._lastUpdate) / 1e3 : 0; (true, this._deltaTime > 1) && (this._deltaTime = 1 / 60); this._lastUpdate = now; }, convertToGL: function convertToGL(uiPoint) { var container = game.container; var view = cc.view; var box = container.getBoundingClientRect(); var left = box.left + window.pageXOffset - container.clientLeft; var top = box.top + window.pageYOffset - container.clientTop; var x = view._devicePixelRatio * (uiPoint.x - left); var y = view._devicePixelRatio * (top + box.height - uiPoint.y); return view._isRotated ? cc.v2(view._viewportRect.width - y, x) : cc.v2(x, y); }, convertToUI: function convertToUI(glPoint) { var container = game.container; var view = cc.view; var box = container.getBoundingClientRect(); var left = box.left + window.pageXOffset - container.clientLeft; var top = box.top + window.pageYOffset - container.clientTop; var uiPoint = cc.v2(0, 0); if (view._isRotated) { uiPoint.x = left + glPoint.y / view._devicePixelRatio; uiPoint.y = top + box.height - (view._viewportRect.width - glPoint.x) / view._devicePixelRatio; } else { uiPoint.x = left + glPoint.x * view._devicePixelRatio; uiPoint.y = top + box.height - glPoint.y * view._devicePixelRatio; } return uiPoint; }, end: function end() { this._purgeDirectorInNextLoop = true; }, getWinSize: function getWinSize() { return cc.size(cc.winSize); }, getWinSizeInPixels: function getWinSizeInPixels() { return cc.size(cc.winSize); }, pause: function pause() { if (this._paused) return; this._paused = true; }, purgeCachedData: function purgeCachedData() { cc.assetManager.releaseAll(); }, purgeDirector: function purgeDirector() { this._scheduler.unscheduleAll(); this._compScheduler.unscheduleAll(); this._nodeActivator.reset(); eventManager && eventManager.setEnabled(false); true; cc.isValid(this._scene) && this._scene.destroy(); this._scene = null; cc.renderer.clear(); cc.assetManager.builtins.clear(); cc.game.pause(); cc.assetManager.releaseAll(); }, reset: function reset() { this.purgeDirector(); eventManager && eventManager.setEnabled(true); this._actionManager && this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); this._animationManager && this._scheduler.scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false); this._collisionManager && this._scheduler.scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false); this._physicsManager && this._scheduler.scheduleUpdate(this._physicsManager, cc.Scheduler.PRIORITY_SYSTEM, false); cc.game.resume(); }, runSceneImmediate: function runSceneImmediate(scene, onBeforeLoadScene, onLaunched) { cc.assertID(scene instanceof cc.Scene || scene instanceof cc.SceneAsset, 1216); scene instanceof cc.SceneAsset && (scene = scene.scene); (true, true) && console.time("InitScene"); scene._load(); (true, true) && console.timeEnd("InitScene"); (true, true) && console.time("AttachPersist"); var persistNodeList = Object.keys(game._persistRootNodes).map((function(x) { return game._persistRootNodes[x]; })); for (var i = 0; i < persistNodeList.length; i++) { var node = persistNodeList[i]; var existNode = scene.getChildByUuid(node.uuid); if (existNode) { var index = existNode.getSiblingIndex(); existNode._destroyImmediate(); scene.insertChild(node, index); } else node.parent = scene; } (true, true) && console.timeEnd("AttachPersist"); var oldScene = this._scene; true; (true, true) && console.time("AutoRelease"); cc.assetManager._releaseManager._autoRelease(oldScene, scene, game._persistRootNodes); (true, true) && console.timeEnd("AutoRelease"); (true, true) && console.time("Destroy"); cc.isValid(oldScene) && oldScene.destroy(); this._scene = null; Obj._deferredDestroy(); (true, true) && console.timeEnd("Destroy"); onBeforeLoadScene && onBeforeLoadScene(); this.emit(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, scene); this._scene = scene; (true, true) && console.time("Activate"); scene._activate(); (true, true) && console.timeEnd("Activate"); cc.game.resume(); onLaunched && onLaunched(null, scene); this.emit(cc.Director.EVENT_AFTER_SCENE_LAUNCH, scene); }, runScene: function runScene(scene, onBeforeLoadScene, onLaunched) { cc.assertID(scene, 1205); cc.assertID(scene instanceof cc.Scene || scene instanceof cc.SceneAsset, 1216); scene instanceof cc.SceneAsset && (scene = scene.scene); scene._load(); this.once(cc.Director.EVENT_AFTER_DRAW, (function() { this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched); }), this); }, loadScene: function loadScene(sceneName, onLaunched, _onUnloaded) { if (this._loadingScene) { cc.warnID(1208, sceneName, this._loadingScene); return false; } var bundle = cc.assetManager.bundles.find((function(bundle) { return bundle.getSceneInfo(sceneName); })); if (bundle) { this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName); this._loadingScene = sceneName; var self = this; console.time("LoadScene " + sceneName); bundle.loadScene(sceneName, (function(err, scene) { console.timeEnd("LoadScene " + sceneName); self._loadingScene = ""; if (err) { err = "Failed to load scene: " + err; cc.error(err); onLaunched && onLaunched(err); } else self.runSceneImmediate(scene, _onUnloaded, onLaunched); })); return true; } cc.errorID(1209, sceneName); return false; }, preloadScene: function preloadScene(sceneName, onProgress, onLoaded) { var bundle = cc.assetManager.bundles.find((function(bundle) { return bundle.getSceneInfo(sceneName); })); if (!bundle) { cc.errorID(1209, sceneName); return null; } bundle.preloadScene(sceneName, null, onProgress, onLoaded); }, resume: function resume() { if (!this._paused) return; this._lastUpdate = performance.now(); this._lastUpdate || cc.logID(1200); this._paused = false; this._deltaTime = 0; }, setDepthTest: function setDepthTest(value) { if (!cc.Camera.main) return; cc.Camera.main.depth = !!value; }, setClearColor: function setClearColor(clearColor) { if (!cc.Camera.main) return; cc.Camera.main.backgroundColor = clearColor; }, getRunningScene: function getRunningScene() { return this._scene; }, getScene: function getScene() { return this._scene; }, getAnimationInterval: function getAnimationInterval() { return 1e3 / game.getFrameRate(); }, setAnimationInterval: function setAnimationInterval(value) { game.setFrameRate(Math.round(1e3 / value)); }, getDeltaTime: function getDeltaTime() { return this._deltaTime; }, getTotalTime: function getTotalTime() { return performance.now() - this._startTime; }, getTotalFrames: function getTotalFrames() { return this._totalFrames; }, isPaused: function isPaused() { return this._paused; }, getScheduler: function getScheduler() { return this._scheduler; }, setScheduler: function setScheduler(scheduler) { this._scheduler !== scheduler && (this._scheduler = scheduler); }, getActionManager: function getActionManager() { return this._actionManager; }, setActionManager: function setActionManager(actionManager) { if (this._actionManager !== actionManager) { this._actionManager && this._scheduler.unscheduleUpdate(this._actionManager); this._actionManager = actionManager; this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); } }, getAnimationManager: function getAnimationManager() { return this._animationManager; }, getCollisionManager: function getCollisionManager() { return this._collisionManager; }, getPhysicsManager: function getPhysicsManager() { return this._physicsManager; }, getPhysics3DManager: function getPhysics3DManager() { return this._physics3DManager; }, startAnimation: function startAnimation() { cc.game.resume(); }, stopAnimation: function stopAnimation() { cc.game.pause(); }, _resetDeltaTime: function _resetDeltaTime() { this._lastUpdate = performance.now(); this._deltaTime = 0; }, mainLoop: function(now) { if (this._purgeDirectorInNextLoop) { this._purgeDirectorInNextLoop = false; this.purgeDirector(); } else { this.calculateDeltaTime(now); if (!this._paused) { this.emit(cc.Director.EVENT_BEFORE_UPDATE); this._compScheduler.startPhase(); this._compScheduler.updatePhase(this._deltaTime); this._scheduler.update(this._deltaTime); this._compScheduler.lateUpdatePhase(this._deltaTime); this.emit(cc.Director.EVENT_AFTER_UPDATE); Obj._deferredDestroy(); } this.emit(cc.Director.EVENT_BEFORE_DRAW); renderer.render(this._scene, this._deltaTime); this.emit(cc.Director.EVENT_AFTER_DRAW); eventManager.frameUpdateListeners(); this._totalFrames++; } }, __fastOn: function __fastOn(type, callback, target) { this.on(type, callback, target); }, __fastOff: function __fastOff(type, callback, target) { this.off(type, callback, target); } }; cc.js.addon(cc.Director.prototype, EventTarget.prototype); cc.Director.EVENT_PROJECTION_CHANGED = "director_projection_changed"; cc.Director.EVENT_BEFORE_SCENE_LOADING = "director_before_scene_loading"; cc.Director.EVENT_BEFORE_SCENE_LAUNCH = "director_before_scene_launch"; cc.Director.EVENT_AFTER_SCENE_LAUNCH = "director_after_scene_launch"; cc.Director.EVENT_BEFORE_UPDATE = "director_before_update"; cc.Director.EVENT_AFTER_UPDATE = "director_after_update"; cc.Director.EVENT_BEFORE_VISIT = "director_before_draw"; cc.Director.EVENT_AFTER_VISIT = "director_before_draw"; cc.Director.EVENT_BEFORE_DRAW = "director_before_draw"; cc.Director.EVENT_AFTER_DRAW = "director_after_draw"; cc.Director.PROJECTION_2D = 0; cc.Director.PROJECTION_3D = 1; cc.Director.PROJECTION_CUSTOM = 3; cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_2D; cc.Director.EVENT_BEFORE_PHYSICS = "director_before_physics"; cc.Director.EVENT_AFTER_PHYSICS = "director_after_physics"; cc.director = new cc.Director(); module.exports = cc.director; }), { "./CCGame": 23, "./CCScheduler": 27, "./component-scheduler": 87, "./event-manager": 117, "./event/event-target": 119, "./node-activator": 128, "./platform/CCObject": 135, "./renderer": 160 } ], 23: [ (function(require, module, exports) { "use strict"; var EventTarget = require("./event/event-target"); require("../audio/CCAudioEngine"); var debug = require("./CCDebug"); var renderer = require("./renderer/index.js"); var dynamicAtlasManager = require("../core/renderer/utils/dynamic-atlas/manager"); var game = { EVENT_HIDE: "game_on_hide", EVENT_SHOW: "game_on_show", EVENT_RESTART: "game_on_restart", EVENT_GAME_INITED: "game_inited", EVENT_ENGINE_INITED: "engine_inited", EVENT_RENDERER_INITED: "engine_inited", RENDER_TYPE_CANVAS: 0, RENDER_TYPE_WEBGL: 1, RENDER_TYPE_OPENGL: 2, _persistRootNodes: {}, _paused: true, _configLoaded: false, _isCloning: false, _prepared: false, _rendererInitialized: false, _renderContext: null, _intervalId: null, _lastTime: null, _frameTime: null, frame: null, container: null, canvas: null, renderType: -1, config: null, onStart: null, setFrameRate: function setFrameRate(frameRate) { var config = this.config; config.frameRate = frameRate; this._intervalId && window.cancelAnimFrame(this._intervalId); this._intervalId = 0; this._paused = true; this._setAnimFrame(); this._runMainLoop(); }, getFrameRate: function getFrameRate() { return this.config.frameRate; }, step: function step() { cc.director.mainLoop(); }, pause: function pause() { if (this._paused) return; this._paused = true; cc.audioEngine && cc.audioEngine._break(); this._intervalId && window.cancelAnimFrame(this._intervalId); this._intervalId = 0; }, resume: function resume() { if (!this._paused) return; this._paused = false; cc.audioEngine && cc.audioEngine._restore(); cc.director._resetDeltaTime(); this._runMainLoop(); }, isPaused: function isPaused() { return this._paused; }, restart: function restart() { cc.director.once(cc.Director.EVENT_AFTER_DRAW, (function() { for (var id in game._persistRootNodes) game.removePersistRootNode(game._persistRootNodes[id]); cc.director.getScene().destroy(); cc.Object._deferredDestroy(); cc.audioEngine && cc.audioEngine.uncacheAll(); cc.director.reset(); game.pause(); cc.assetManager.builtins.init((function() { game.onStart(); game.emit(game.EVENT_RESTART); })); })); }, end: function end() { close(); }, _initEngine: function _initEngine() { if (this._rendererInitialized) return; this._initRenderer(); true; this._initEvents(); this.emit(this.EVENT_ENGINE_INITED); }, _loadPreviewScript: function _loadPreviewScript(cb) { false; cb(); }, _prepareFinished: function _prepareFinished(cb) { var _this = this; this._initEngine(); this._setAnimFrame(); cc.assetManager.builtins.init((function() { console.log("Cocos Creator SP v" + cc.ENGINE_VERSION); _this._prepared = true; _this._runMainLoop(); _this.emit(_this.EVENT_GAME_INITED); cb && cb(); })); }, eventTargetOn: EventTarget.prototype.on, eventTargetOnce: EventTarget.prototype.once, on: function on(type, callback, target, once) { this._prepared && type === this.EVENT_ENGINE_INITED || !this._paused && type === this.EVENT_GAME_INITED ? callback.call(target) : this.eventTargetOn(type, callback, target, once); }, once: function once(type, callback, target) { this._prepared && type === this.EVENT_ENGINE_INITED || !this._paused && type === this.EVENT_GAME_INITED ? callback.call(target) : this.eventTargetOnce(type, callback, target); }, prepare: function prepare(cb) { var _this2 = this; if (this._prepared) { cb && cb(); return; } this._loadPreviewScript((function() { _this2._prepareFinished(cb); })); }, run: function run(config, onStart) { this._initConfig(config); this.onStart = onStart; this.prepare(game.onStart && game.onStart.bind(game)); }, addPersistRootNode: function addPersistRootNode(node) { if (!cc.Node.isNode(node) || !node.uuid) { cc.warnID(3800); return; } var id = node.uuid; if (!this._persistRootNodes[id]) { var scene = cc.director._scene; if (cc.isValid(scene)) if (node.parent) { if (!(node.parent instanceof cc.Scene)) { cc.warnID(3801); return; } if (node.parent !== scene) { cc.warnID(3802); return; } } else node.parent = scene; this._persistRootNodes[id] = node; node._persistNode = true; cc.assetManager._releaseManager._addPersistNodeRef(node); } }, removePersistRootNode: function removePersistRootNode(node) { var id = node.uuid || ""; if (node === this._persistRootNodes[id]) { delete this._persistRootNodes[id]; node._persistNode = false; cc.assetManager._releaseManager._removePersistNodeRef(node); } }, isPersistRootNode: function isPersistRootNode(node) { return node._persistNode; }, _setAnimFrame: function _setAnimFrame() { this._lastTime = performance.now(); var frameRate = game.config.frameRate; this._frameTime = 1e3 / frameRate; cc.director._maxParticleDeltaTime = this._frameTime / 1e3 * 2; false, false; var rAF = window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; if (60 !== frameRate && 30 !== frameRate) { window.requestAnimFrame = rAF ? this._stTimeWithRAF : this._stTime; window.cancelAnimFrame = this._ctTime; } else { window.requestAnimFrame = rAF || this._stTime; window.cancelAnimFrame = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.oCancelAnimationFrame || this._ctTime; } }, _stTimeWithRAF: function _stTimeWithRAF(callback) { var currTime = performance.now(); var timeToCall = Math.max(0, game._frameTime - (currTime - game._lastTime)); var id = window.setTimeout((function() { window.requestAnimationFrame(callback); }), timeToCall); game._lastTime = currTime + timeToCall; return id; }, _stTime: function _stTime(callback) { var currTime = performance.now(); var timeToCall = Math.max(0, game._frameTime - (currTime - game._lastTime)); var id = window.setTimeout((function() { callback(); }), timeToCall); game._lastTime = currTime + timeToCall; return id; }, _ctTime: function _ctTime(id) { window.clearTimeout(id); }, _runMainLoop: function _runMainLoop() { false; if (!this._prepared) return; var self = this, _callback, config = self.config, director = cc.director, skip = true, frameRate = config.frameRate; debug.setDisplayStats(config.showFPS); _callback = function callback(now) { if (!self._paused) { self._intervalId = window.requestAnimFrame(_callback); if ((true, true) && 30 === frameRate && (skip = !skip)) return; director.mainLoop(now); } }; self._intervalId = window.requestAnimFrame(_callback); self._paused = false; }, _initConfig: function _initConfig(config) { "number" !== typeof config.debugMode && (config.debugMode = 0); config.exposeClassName = !!config.exposeClassName; "number" !== typeof config.frameRate && (config.frameRate = 60); var renderMode = config.renderMode; ("number" !== typeof renderMode || renderMode > 2 || renderMode < 0) && (config.renderMode = 0); "boolean" !== typeof config.registerSystemEvent && (config.registerSystemEvent = true); config.showFPS = 1 !== renderMode && !!config.showFPS; this.collisionMatrix = config.collisionMatrix || []; this.groupList = config.groupList || []; debug._resetDebugSetting(config.debugMode); this.config = config; this._configLoaded = true; }, _determineRenderType: function _determineRenderType() { var config = this.config, userRenderMode = parseInt(config.renderMode) || 0; this.renderType = this.RENDER_TYPE_CANVAS; var supportRender = false; if (0 === userRenderMode) { if (cc.sys.capabilities["opengl"]) { this.renderType = this.RENDER_TYPE_WEBGL; supportRender = true; } else if (cc.sys.capabilities["canvas"]) { this.renderType = this.RENDER_TYPE_CANVAS; supportRender = true; } } else if (1 === userRenderMode && cc.sys.capabilities["canvas"]) { this.renderType = this.RENDER_TYPE_CANVAS; supportRender = true; } else if (2 === userRenderMode && cc.sys.capabilities["opengl"]) { this.renderType = this.RENDER_TYPE_WEBGL; supportRender = true; } if (!supportRender) throw new Error(debug.getError(3820, userRenderMode)); }, _initRenderer: function _initRenderer() { if (this._rendererInitialized) return; var el = this.config.id, width, height, localCanvas, localContainer; false, false; var addClass = function addClass(element, name) { var hasClass = (" " + element.className + " ").indexOf(" " + name + " ") > -1; if (!hasClass) { element.className && (element.className += " "); element.className += name; } }; var element = el instanceof HTMLElement ? el : document.querySelector(el) || document.querySelector("#" + el); if ("CANVAS" === element.tagName) { width = element.width; height = element.height; this.canvas = localCanvas = element; this.container = localContainer = document.createElement("DIV"); localCanvas.parentNode && localCanvas.parentNode.insertBefore(localContainer, localCanvas); } else { "DIV" !== element.tagName && cc.warnID(3819); width = element.clientWidth; height = element.clientHeight; this.canvas = localCanvas = document.createElement("CANVAS"); this.container = localContainer = document.createElement("DIV"); element.appendChild(localContainer); } localContainer.setAttribute("id", "Cocos2dGameContainer"); localContainer.appendChild(localCanvas); this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; addClass(localCanvas, "gameCanvas"); localCanvas.setAttribute("width", width || 480); localCanvas.setAttribute("height", height || 320); localCanvas.setAttribute("tabindex", 99); this._determineRenderType(); if (this.renderType === this.RENDER_TYPE_WEBGL) { var opts = { stencil: true, antialias: cc.macro.ENABLE_WEBGL_ANTIALIAS, alpha: cc.macro.ENABLE_TRANSPARENT_CANVAS }; renderer.initWebGL(localCanvas, opts); this._renderContext = renderer.device._gl; !cc.macro.CLEANUP_IMAGE_CACHE && dynamicAtlasManager && (dynamicAtlasManager.enabled = true); } if (!this._renderContext) { this.renderType = this.RENDER_TYPE_CANVAS; renderer.initCanvas(localCanvas); this._renderContext = renderer.device._ctx; } this.canvas.oncontextmenu = function() { if (!cc._isContextMenuEnable) return false; }; this._rendererInitialized = true; }, _initEvents: function _initEvents() { var win = window, hiddenPropName; this.config.registerSystemEvent && cc.internal.inputManager.registerSystemEvent(this.canvas); "undefined" !== typeof document.hidden ? hiddenPropName = "hidden" : "undefined" !== typeof document.mozHidden ? hiddenPropName = "mozHidden" : "undefined" !== typeof document.msHidden ? hiddenPropName = "msHidden" : "undefined" !== typeof document.webkitHidden && (hiddenPropName = "webkitHidden"); var hidden = false; function onHidden() { if (!hidden) { hidden = true; game.emit(game.EVENT_HIDE); } } function onShown(arg0, arg1, arg2, arg3, arg4) { if (hidden) { hidden = false; game.emit(game.EVENT_SHOW, arg0, arg1, arg2, arg3, arg4); } } if (hiddenPropName) { var changeList = [ "visibilitychange", "mozvisibilitychange", "msvisibilitychange", "webkitvisibilitychange", "qbrowserVisibilityChange" ]; for (var i = 0; i < changeList.length; i++) document.addEventListener(changeList[i], (function(event) { var visible = document[hiddenPropName]; visible = visible || event["hidden"]; visible ? onHidden() : onShown(); })); } else { win.addEventListener("blur", onHidden); win.addEventListener("focus", onShown); } navigator.userAgent.indexOf("MicroMessenger") > -1 && (win.onfocus = onShown); if ("onpageshow" in window && "onpagehide" in window) { win.addEventListener("pagehide", onHidden); win.addEventListener("pageshow", onShown); document.addEventListener("pagehide", onHidden); document.addEventListener("pageshow", onShown); } this.on(game.EVENT_HIDE, (function() { game.pause(); })); this.on(game.EVENT_SHOW, (function() { game.resume(); })); } }; EventTarget.call(game); cc.js.addon(game, EventTarget.prototype); cc.game = module.exports = game; }), { "../audio/CCAudioEngine": void 0, "../core/renderer/utils/dynamic-atlas/manager": 162, "./CCDebug": 21, "./event/event-target": 119, "./renderer/index.js": 160 } ], 24: [ (function(require, module, exports) { "use strict"; var _valueTypes = require("./value-types"); var _utils = require("./value-types/utils"); var BaseNode = require("./utils/base-node"); var PrefabHelper = require("./utils/prefab-helper"); var nodeMemPool = require("./utils/trans-pool").NodeMemPool; var AffineTrans = require("./utils/affine-transform"); var eventManager = require("./event-manager"); var macro = require("./platform/CCMacro"); var js = require("./platform/js"); var Event = require("./event/event"); var EventTarget = require("./event/event-target"); var RenderFlow = require("./renderer/render-flow"); var Flags = cc.Object.Flags; var Destroying = Flags.Destroying; var ERR_INVALID_NUMBER = false; var ONE_DEGREE = Math.PI / 180; var ActionManagerExist = !!cc.ActionManager; var emptyFunc = function emptyFunc() {}; var _gwpVec3 = new _valueTypes.Vec3(); var _gwpQuat = new _valueTypes.Quat(); var _tpVec3a = new _valueTypes.Vec3(); var _tpVec3b = new _valueTypes.Vec3(); var _tpQuata = new _valueTypes.Quat(); var _tpQuatb = new _valueTypes.Quat(); var _swpVec3 = new _valueTypes.Vec3(); var _gwsVec3 = new _valueTypes.Vec3(); var _swsVec3 = new _valueTypes.Vec3(); var _gwrtVec3a = new _valueTypes.Vec3(); var _gwrtVec3b = new _valueTypes.Vec3(); var _gwrtQuata = new _valueTypes.Quat(); var _gwrtQuatb = new _valueTypes.Quat(); var _laVec3 = new _valueTypes.Vec3(); var _laQuat = new _valueTypes.Quat(); var _urfVec3 = new _valueTypes.Vec3(); var _urfQuat = new _valueTypes.Quat(); var _htVec3a = new _valueTypes.Vec3(); var _htVec3b = new _valueTypes.Vec3(); var _gwrQuat = new _valueTypes.Quat(); var _swrQuat = new _valueTypes.Quat(); var _quata = new _valueTypes.Quat(); var _mat4_temp = cc.mat4(); var _vec3_temp = new _valueTypes.Vec3(); var POSITION_ON = 1; var SCALE_ON = 2; var ROTATION_ON = 4; var SIZE_ON = 8; var ANCHOR_ON = 16; var COLOR_ON = 32; var _cachedPool = new js.Pool(); _cachedPool.get = function() { return this._get() || []; }; var BuiltinGroupIndex = cc.Enum({ DEBUG: 31 }); var LocalDirtyFlag = cc.Enum({ POSITION: 1, SCALE: 2, ROTATION: 4, SKEW: 8, TRS: 7, RS: 6, TRSS: 15, PHYSICS_POSITION: 16, PHYSICS_SCALE: 32, PHYSICS_ROTATION: 64, PHYSICS_TRS: 112, PHYSICS_RS: 96, ALL_POSITION: 17, ALL_SCALE: 34, ALL_ROTATION: 68, ALL_TRS: 119, ALL: 65535 }); var EventType = cc.Enum({ TOUCH_START: "touchstart", TOUCH_MOVE: "touchmove", TOUCH_END: "touchend", TOUCH_CANCEL: "touchcancel", MOUSE_DOWN: "mousedown", MOUSE_MOVE: "mousemove", MOUSE_ENTER: "mouseenter", MOUSE_LEAVE: "mouseleave", MOUSE_UP: "mouseup", MOUSE_WHEEL: "mousewheel", POSITION_CHANGED: "position-changed", ROTATION_CHANGED: "rotation-changed", SCALE_CHANGED: "scale-changed", SIZE_CHANGED: "size-changed", ANCHOR_CHANGED: "anchor-changed", COLOR_CHANGED: "color-changed", CHILD_ADDED: "child-added", CHILD_REMOVED: "child-removed", CHILD_REORDER: "child-reorder", GROUP_CHANGED: "group-changed", SIBLING_ORDER_CHANGED: "sibling-order-changed" }); var _touchEvents = [ EventType.TOUCH_START, EventType.TOUCH_MOVE, EventType.TOUCH_END, EventType.TOUCH_CANCEL ]; var _mouseEvents = [ EventType.MOUSE_DOWN, EventType.MOUSE_ENTER, EventType.MOUSE_MOVE, EventType.MOUSE_LEAVE, EventType.MOUSE_UP, EventType.MOUSE_WHEEL ]; var _skewNeedWarn = true; var _skewWarn = function _skewWarn(value, node) { if (0 !== value) { var nodePath = ""; var NodeUtils; false; _skewNeedWarn && cc.warn("`cc.Node.skewX/Y` is deprecated since v2.2.1, please use 3D node instead.", nodePath); true, _skewNeedWarn = false; } }; var _currentHovered = null; var _touchStartHandler = function _touchStartHandler(touch, event) { var pos = touch.getLocation(); var node = this.owner; if (node._hitTest(pos, this)) { event.type = EventType.TOUCH_START; event.touch = touch; event.bubbles = true; node.dispatchEvent(event); return true; } return false; }; var _touchMoveHandler = function _touchMoveHandler(touch, event) { var node = this.owner; event.type = EventType.TOUCH_MOVE; event.touch = touch; event.bubbles = true; node.dispatchEvent(event); }; var _touchEndHandler = function _touchEndHandler(touch, event) { var pos = touch.getLocation(); var node = this.owner; node._hitTest(pos, this) ? event.type = EventType.TOUCH_END : event.type = EventType.TOUCH_CANCEL; event.touch = touch; event.bubbles = true; node.dispatchEvent(event); }; var _touchCancelHandler = function _touchCancelHandler(touch, event) { var pos = touch.getLocation(); var node = this.owner; event.type = EventType.TOUCH_CANCEL; event.touch = touch; event.bubbles = true; node.dispatchEvent(event); }; var _mouseDownHandler = function _mouseDownHandler(event) { var pos = event.getLocation(); var node = this.owner; if (node._hitTest(pos, this)) { event.type = EventType.MOUSE_DOWN; event.bubbles = true; node.dispatchEvent(event); } }; var _mouseMoveHandler = function _mouseMoveHandler(event) { var pos = event.getLocation(); var node = this.owner; var hit = node._hitTest(pos, this); if (hit) { if (!this._previousIn) { if (_currentHovered && _currentHovered._mouseListener) { event.type = EventType.MOUSE_LEAVE; _currentHovered.dispatchEvent(event); _currentHovered._mouseListener._previousIn = false; } _currentHovered = this.owner; event.type = EventType.MOUSE_ENTER; node.dispatchEvent(event); this._previousIn = true; } event.type = EventType.MOUSE_MOVE; event.bubbles = true; node.dispatchEvent(event); } else { if (!this._previousIn) return; event.type = EventType.MOUSE_LEAVE; node.dispatchEvent(event); this._previousIn = false; _currentHovered = null; } event.stopPropagation(); }; var _mouseUpHandler = function _mouseUpHandler(event) { var pos = event.getLocation(); var node = this.owner; if (node._hitTest(pos, this)) { event.type = EventType.MOUSE_UP; event.bubbles = true; node.dispatchEvent(event); event.stopPropagation(); } }; var _mouseWheelHandler = function _mouseWheelHandler(event) { var pos = event.getLocation(); var node = this.owner; if (node._hitTest(pos, this)) { event.type = EventType.MOUSE_WHEEL; event.bubbles = true; node.dispatchEvent(event); event.stopPropagation(); } }; function _searchComponentsInParent(node, comp) { if (comp) { var index = 0; var list = null; for (var curr = node; curr && cc.Node.isNode(curr); curr = curr._parent, ++index) if (curr.getComponent(comp)) { var next = { index: index, node: curr }; list ? list.push(next) : list = [ next ]; } return list; } return null; } function _checkListeners(node, events) { if (!(node._objFlags & Destroying)) { if (node._bubblingListeners) for (var i = 0, l = events.length; i < l; ++i) if (node._bubblingListeners.hasEventListener(events[i])) return true; if (node._capturingListeners) for (var _i = 0, _l = events.length; _i < _l; ++_i) if (node._capturingListeners.hasEventListener(events[_i])) return true; return false; } return true; } function _doDispatchEvent(owner, event, cachedArray) { var target, i; event.target = owner; cachedArray.length = 0; owner._getCapturingTargets(event.type, cachedArray); event.eventPhase = 1; for (i = cachedArray.length - 1; i >= 0; --i) { target = cachedArray[i]; if (target._capturingListeners) { event.currentTarget = target; target._capturingListeners.emit(event.type, event, cachedArray); if (event._propagationStopped) { cachedArray.length = 0; return; } } } cachedArray.length = 0; event.eventPhase = 2; event.currentTarget = owner; owner._capturingListeners && owner._capturingListeners.emit(event.type, event); !event._propagationImmediateStopped && owner._bubblingListeners && owner._bubblingListeners.emit(event.type, event); if (!event._propagationStopped && event.bubbles) { owner._getBubblingTargets(event.type, cachedArray); event.eventPhase = 3; for (i = 0; i < cachedArray.length; ++i) { target = cachedArray[i]; if (target._bubblingListeners) { event.currentTarget = target; target._bubblingListeners.emit(event.type, event); if (event._propagationStopped) { cachedArray.length = 0; return; } } } } cachedArray.length = 0; } function _getActualGroupIndex(node) { var groupIndex = node.groupIndex; 0 === groupIndex && node.parent && (groupIndex = _getActualGroupIndex(node.parent)); return groupIndex; } function _updateCullingMask(node) { var index = _getActualGroupIndex(node); node._cullingMask = 1 << index; false; for (var i = 0; i < node._children.length; i++) _updateCullingMask(node._children[i]); } function updateLocalMatrix3D() { if (this._localMatDirty & LocalDirtyFlag.TRSS) { var t = this._matrix; var tm = t.m; _valueTypes.Trs.toMat4(t, this._trs); if (this._skewX || this._skewY) { var a = tm[0], b = tm[1], c = tm[4], d = tm[5]; var skx = Math.tan(this._skewX * ONE_DEGREE); var sky = Math.tan(this._skewY * ONE_DEGREE); Infinity === skx && (skx = 99999999); Infinity === sky && (sky = 99999999); tm[0] = a + c * sky; tm[1] = b + d * sky; tm[4] = c + a * skx; tm[5] = d + b * skx; } this._localMatDirty &= ~LocalDirtyFlag.TRSS; this._worldMatDirty = true; } } function updateLocalMatrix2D() { var dirtyFlag = this._localMatDirty; if (!(dirtyFlag & LocalDirtyFlag.TRSS)) return; var t = this._matrix; var tm = t.m; var trs = this._trs; if (dirtyFlag & (LocalDirtyFlag.RS | LocalDirtyFlag.SKEW)) { var rotation = -this._eulerAngles.z; var hasSkew = this._skewX || this._skewY; var sx = trs[7], sy = trs[8]; if (rotation || hasSkew) { var a = 1, b = 0, c = 0, d = 1; if (rotation) { var rotationRadians = rotation * ONE_DEGREE; c = Math.sin(rotationRadians); d = Math.cos(rotationRadians); a = d; b = -c; } tm[0] = a *= sx; tm[1] = b *= sx; tm[4] = c *= sy; tm[5] = d *= sy; if (hasSkew) { var _a = tm[0], _b = tm[1], _c = tm[4], _d = tm[5]; var skx = Math.tan(this._skewX * ONE_DEGREE); var sky = Math.tan(this._skewY * ONE_DEGREE); Infinity === skx && (skx = 99999999); Infinity === sky && (sky = 99999999); tm[0] = _a + _c * sky; tm[1] = _b + _d * sky; tm[4] = _c + _a * skx; tm[5] = _d + _b * skx; } } else { tm[0] = sx; tm[1] = 0; tm[4] = 0; tm[5] = sy; } } tm[12] = trs[0]; tm[13] = trs[1]; this._localMatDirty &= ~LocalDirtyFlag.TRSS; this._worldMatDirty = true; } function calculWorldMatrix3D() { this._localMatDirty & LocalDirtyFlag.TRSS && this._updateLocalMatrix(); if (this._parent) { var parentMat = this._parent._worldMatrix; _valueTypes.Mat4.mul(this._worldMatrix, parentMat, this._matrix); } else _valueTypes.Mat4.copy(this._worldMatrix, this._matrix); this._worldMatDirty = false; } function calculWorldMatrix2D() { this._localMatDirty & LocalDirtyFlag.TRSS && this._updateLocalMatrix(); var parent = this._parent; parent ? this._mulMat(this._worldMatrix, parent._worldMatrix, this._matrix) : _valueTypes.Mat4.copy(this._worldMatrix, this._matrix); this._worldMatDirty = false; } function mulMat2D(out, a, b) { var am = a.m, bm = b.m, outm = out.m; var aa = am[0], ab = am[1], ac = am[4], ad = am[5], atx = am[12], aty = am[13]; var ba = bm[0], bb = bm[1], bc = bm[4], bd = bm[5], btx = bm[12], bty = bm[13]; if (0 !== ab || 0 !== ac) { outm[0] = ba * aa + bb * ac; outm[1] = ba * ab + bb * ad; outm[4] = bc * aa + bd * ac; outm[5] = bc * ab + bd * ad; outm[12] = aa * btx + ac * bty + atx; outm[13] = ab * btx + ad * bty + aty; } else { outm[0] = ba * aa; outm[1] = bb * ad; outm[4] = bc * aa; outm[5] = bd * ad; outm[12] = aa * btx + atx; outm[13] = ad * bty + aty; } } var mulMat3D = _valueTypes.Mat4.mul; var NodeDefines = { name: "cc.Node", extends: BaseNode, properties: { _opacity: 255, _color: cc.Color.WHITE, _contentSize: cc.Size, _anchorPoint: cc.v2(.5, .5), _position: void 0, _scale: void 0, _trs: null, _eulerAngles: cc.Vec3, _skewX: 0, _skewY: 0, _zIndex: { default: void 0, type: cc.Integer }, _localZOrder: { default: 0, serializable: false }, _is3DNode: false, _groupIndex: { default: 0, formerlySerializedAs: "groupIndex" }, groupIndex: { get: function get() { return this._groupIndex; }, set: function set(value) { this._groupIndex = value; _updateCullingMask(this); this.emit(EventType.GROUP_CHANGED, this); } }, group: { get: function get() { return cc.game.groupList[this.groupIndex] || ""; }, set: function set(value) { this.groupIndex = cc.game.groupList.indexOf(value); } }, x: { get: function get() { return this._trs[0]; }, set: function set(value) { var trs = this._trs; if (value !== trs[0]) { true; var oldValue; false; trs[0] = value; this.setLocalDirty(LocalDirtyFlag.ALL_POSITION); if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } } } }, y: { get: function get() { return this._trs[1]; }, set: function set(value) { var trs = this._trs; if (value !== trs[1]) { true; var oldValue; false; trs[1] = value; this.setLocalDirty(LocalDirtyFlag.ALL_POSITION); if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } } } }, z: { get: function get() { return this._trs[2]; }, set: function set(value) { var trs = this._trs; if (value !== trs[2]) { true; var oldValue; false; trs[2] = value; this.setLocalDirty(LocalDirtyFlag.ALL_POSITION); true, this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } } } }, rotation: { get: function get() { true; cc.warn("`cc.Node.rotation` is deprecated since v2.1.0, please use `-angle` instead. (`this.node.rotation` -> `-this.node.angle`)"); return -this.angle; }, set: function set(value) { true; cc.warn("`cc.Node.rotation` is deprecated since v2.1.0, please set `-angle` instead. (`this.node.rotation = x` -> `this.node.angle = -x`)"); this.angle = -value; } }, angle: { get: function get() { return this._eulerAngles.z; }, set: function set(value) { _valueTypes.Vec3.set(this._eulerAngles, 0, 0, value); _valueTypes.Trs.fromAngleZ(this._trs, value); this.setLocalDirty(LocalDirtyFlag.ALL_ROTATION); this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } }, rotationX: { get: function get() { true; cc.warn("`cc.Node.rotationX` is deprecated since v2.1.0, please use `eulerAngles.x` instead. (`this.node.rotationX` -> `this.node.eulerAngles.x`)"); return this._eulerAngles.x; }, set: function set(value) { true; cc.warn("`cc.Node.rotationX` is deprecated since v2.1.0, please set `eulerAngles` instead. (`this.node.rotationX = x` -> `this.node.is3DNode = true; this.node.eulerAngles = cc.v3(x, 0, 0)`"); if (this._eulerAngles.x !== value) { this._eulerAngles.x = value; this._eulerAngles.x === this._eulerAngles.y ? _valueTypes.Trs.fromAngleZ(this._trs, -value) : _valueTypes.Trs.fromEulerNumber(this._trs, value, this._eulerAngles.y, 0); this.setLocalDirty(LocalDirtyFlag.ALL_ROTATION); this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } } }, rotationY: { get: function get() { true; cc.warn("`cc.Node.rotationY` is deprecated since v2.1.0, please use `eulerAngles.y` instead. (`this.node.rotationY` -> `this.node.eulerAngles.y`)"); return this._eulerAngles.y; }, set: function set(value) { true; cc.warn("`cc.Node.rotationY` is deprecated since v2.1.0, please set `eulerAngles` instead. (`this.node.rotationY = y` -> `this.node.is3DNode = true; this.node.eulerAngles = cc.v3(0, y, 0)`"); if (this._eulerAngles.y !== value) { this._eulerAngles.y = value; this._eulerAngles.x === this._eulerAngles.y ? _valueTypes.Trs.fromAngleZ(this._trs, -value) : _valueTypes.Trs.fromEulerNumber(this._trs, this._eulerAngles.x, value, 0); this.setLocalDirty(LocalDirtyFlag.ALL_ROTATION); this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } } }, eulerAngles: { get: function get() { false; return _valueTypes.Trs.toEuler(this._eulerAngles, this._trs); }, set: function set(v) { false; _valueTypes.Trs.fromEuler(this._trs, v); this.setLocalDirty(LocalDirtyFlag.ALL_ROTATION); true, this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } }, quat: { get: function get() { var trs = this._trs; return new _valueTypes.Quat(trs[3], trs[4], trs[5], trs[6]); }, set: function set(v) { this.setRotation(v); } }, scale: { get: function get() { return this._trs[7]; }, set: function set(v) { this.setScale(v); } }, scaleX: { get: function get() { return this._trs[7]; }, set: function set(value) { if (this._trs[7] !== value) { this._trs[7] = value; this.setLocalDirty(LocalDirtyFlag.ALL_SCALE); this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } } }, scaleY: { get: function get() { return this._trs[8]; }, set: function set(value) { if (this._trs[8] !== value) { this._trs[8] = value; this.setLocalDirty(LocalDirtyFlag.ALL_SCALE); this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } } }, scaleZ: { get: function get() { return this._trs[9]; }, set: function set(value) { if (this._trs[9] !== value) { this._trs[9] = value; this.setLocalDirty(LocalDirtyFlag.ALL_SCALE); true, this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } } }, skewX: { get: function get() { return this._skewX; }, set: function set(value) { _skewWarn(value, this); this._skewX = value; this.setLocalDirty(LocalDirtyFlag.SKEW); false; } }, skewY: { get: function get() { return this._skewY; }, set: function set(value) { _skewWarn(value, this); this._skewY = value; this.setLocalDirty(LocalDirtyFlag.SKEW); false; } }, opacity: { get: function get() { return this._opacity; }, set: function set(value) { value = cc.misc.clampf(value, 0, 255); if (this._opacity !== value) { this._opacity = value; false; this._renderFlag |= RenderFlow.FLAG_OPACITY_COLOR; } }, range: [ 0, 255 ] }, color: { get: function get() { return this._color.clone(); }, set: function set(value) { if (!this._color.equals(value)) { this._color.set(value); false; this._renderFlag |= RenderFlow.FLAG_COLOR; this._eventMask & COLOR_ON && this.emit(EventType.COLOR_CHANGED, value); } } }, anchorX: { get: function get() { return this._anchorPoint.x; }, set: function set(value) { var anchorPoint = this._anchorPoint; if (anchorPoint.x !== value) { anchorPoint.x = value; this._eventMask & ANCHOR_ON && this.emit(EventType.ANCHOR_CHANGED); } } }, anchorY: { get: function get() { return this._anchorPoint.y; }, set: function set(value) { var anchorPoint = this._anchorPoint; if (anchorPoint.y !== value) { anchorPoint.y = value; this._eventMask & ANCHOR_ON && this.emit(EventType.ANCHOR_CHANGED); } } }, width: { get: function get() { return this._contentSize.width; }, set: function set(value) { if (value !== this._contentSize.width) { var clone; false; this._contentSize.width = value; if (this._eventMask & SIZE_ON) { false; this.emit(EventType.SIZE_CHANGED); } } } }, height: { get: function get() { return this._contentSize.height; }, set: function set(value) { if (value !== this._contentSize.height) { var clone; false; this._contentSize.height = value; if (this._eventMask & SIZE_ON) { false; this.emit(EventType.SIZE_CHANGED); } } } }, zIndex: { get: function get() { return this._localZOrder >> 16; }, set: function set(value) { if (value > macro.MAX_ZINDEX) { cc.warnID(1636); value = macro.MAX_ZINDEX; } else if (value < macro.MIN_ZINDEX) { cc.warnID(1637); value = macro.MIN_ZINDEX; } if (this.zIndex !== value) { this._localZOrder = 65535 & this._localZOrder | value << 16; this.emit(EventType.SIBLING_ORDER_CHANGED); this._onSiblingIndexChanged(); } } }, is3DNode: { get: function get() { return this._is3DNode; }, set: function set(v) { if (this._is3DNode === v) return; this._is3DNode = v; this._update3DFunction(); } }, up: { get: function get() { var _up = _valueTypes.Vec3.transformQuat(_urfVec3, _valueTypes.Vec3.UP, this.getWorldRotation(_urfQuat)); return _up.clone(); } }, right: { get: function get() { var _right = _valueTypes.Vec3.transformQuat(_urfVec3, _valueTypes.Vec3.RIGHT, this.getWorldRotation(_urfQuat)); return _right.clone(); } }, forward: { get: function get() { var _forward = _valueTypes.Vec3.transformQuat(_urfVec3, _valueTypes.Vec3.FORWARD, this.getWorldRotation(_urfQuat)); return _forward.clone(); } } }, ctor: function ctor() { this._reorderChildDirty = false; this._widget = null; this._renderComponent = null; this._capturingListeners = null; this._bubblingListeners = null; this._touchListener = null; this._mouseListener = null; this._initDataFromPool(); this._eventMask = 0; this._cullingMask = 1; this._childArrivalOrder = 1; false; this._renderFlag = RenderFlow.FLAG_TRANSFORM | RenderFlow.FLAG_OPACITY_COLOR; }, statics: { EventType: EventType, _LocalDirtyFlag: LocalDirtyFlag, isNode: function isNode(obj) { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); }, BuiltinGroupIndex: BuiltinGroupIndex }, _onSiblingIndexChanged: function _onSiblingIndexChanged() { this._parent && this._parent._delaySort(); }, _onPreDestroy: function _onPreDestroy() { var destroyByParent = this._onPreDestroyBase(); ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this); _currentHovered === this && (_currentHovered = null); this._bubblingListeners && this._bubblingListeners.clear(); this._capturingListeners && this._capturingListeners.clear(); if (this._touchListener || this._mouseListener) { eventManager.removeListeners(this); if (this._touchListener) { this._touchListener.owner = null; this._touchListener.mask = null; this._touchListener = null; } if (this._mouseListener) { this._mouseListener.owner = null; this._mouseListener.mask = null; this._mouseListener = null; } } false; this._backDataIntoPool(); this._reorderChildDirty && cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); destroyByParent || false; }, _onPostActivated: function _onPostActivated(active) { var actionManager = ActionManagerExist ? cc.director.getActionManager() : null; if (active) { this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; actionManager && actionManager.resumeTarget(this); eventManager.resumeTarget(this); this._checkListenerMask(); } else { actionManager && actionManager.pauseTarget(this); eventManager.pauseTarget(this); } }, _onHierarchyChanged: function _onHierarchyChanged(oldParent) { this._updateOrderOfArrival(); _updateCullingMask(this); this._parent && this._parent._delaySort(); this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM | RenderFlow.FLAG_OPACITY_COLOR; this._onHierarchyChangedBase(oldParent); cc._widgetManager && (cc._widgetManager._nodesOrderDirty = true); oldParent && this._activeInHierarchy && this._checkListenerMask(); false; }, _update3DFunction: function _update3DFunction() { if (this._is3DNode) { this._updateLocalMatrix = updateLocalMatrix3D; this._calculWorldMatrix = calculWorldMatrix3D; this._mulMat = mulMat3D; } else { this._updateLocalMatrix = updateLocalMatrix2D; this._calculWorldMatrix = calculWorldMatrix2D; this._mulMat = mulMat2D; } this._renderComponent && this._renderComponent._on3DNodeChanged && this._renderComponent._on3DNodeChanged(); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._localMatDirty = LocalDirtyFlag.ALL; false; }, _initDataFromPool: function _initDataFromPool() { if (!this._spaceInfo) { false, false; this._spaceInfo = nodeMemPool.pop(); } var spaceInfo = this._spaceInfo; this._matrix = cc.mat4(spaceInfo.localMat); _valueTypes.Mat4.identity(this._matrix); this._worldMatrix = cc.mat4(spaceInfo.worldMat); _valueTypes.Mat4.identity(this._worldMatrix); this._localMatDirty = LocalDirtyFlag.ALL; this._worldMatDirty = true; var trs = this._trs = spaceInfo.trs; trs[0] = 0; trs[1] = 0; trs[2] = 0; trs[3] = 0; trs[4] = 0; trs[5] = 0; trs[6] = 1; trs[7] = 1; trs[8] = 1; trs[9] = 1; }, _backDataIntoPool: function _backDataIntoPool() { if (!(false, false)) { nodeMemPool.push(this._spaceInfo); this._matrix = null; this._worldMatrix = null; this._trs = null; this._spaceInfo = null; } }, _toEuler: function _toEuler() { if (this.is3DNode) _valueTypes.Trs.toEuler(this._eulerAngles, this._trs); else { var z = Math.asin(this._trs[5]) / ONE_DEGREE * 2; _valueTypes.Vec3.set(this._eulerAngles, 0, 0, z); } }, _fromEuler: function _fromEuler() { this.is3DNode ? _valueTypes.Trs.fromEuler(this._trs, this._eulerAngles) : _valueTypes.Trs.fromAngleZ(this._trs, this._eulerAngles.z); }, _initProperties: function _initProperties() { this._is3DNode && this._update3DFunction(); var trs = this._trs; if (trs) { var desTrs = trs; trs = this._trs = this._spaceInfo.trs; 11 === desTrs.length ? trs.set(desTrs.subarray(1)) : trs.set(desTrs); } else trs = this._trs = this._spaceInfo.trs; var NodeUtils; false; this._fromEuler(); false; }, _onBatchCreated: function _onBatchCreated(dontSyncChildPrefab) { this._initProperties(); this._cullingMask = 1 << _getActualGroupIndex(this); false; if (!this._activeInHierarchy) { ActionManagerExist && cc.director.getActionManager().pauseTarget(this); eventManager.pauseTarget(this); } var children = this._children; for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; if (!dontSyncChildPrefab) { var prefabInfo = child._prefab; prefabInfo && prefabInfo.sync && prefabInfo.root === child && PrefabHelper.syncWithPrefab(child); child._updateOrderOfArrival(); } child._onBatchCreated(dontSyncChildPrefab); } children.length > 0 && (this._renderFlag |= RenderFlow.FLAG_CHILDREN); false; }, _checkListenerMask: function _checkListenerMask() { if (this._touchListener) { var mask = this._touchListener.mask = _searchComponentsInParent(this, cc.Mask); this._mouseListener && (this._mouseListener.mask = mask); } else this._mouseListener && (this._mouseListener.mask = _searchComponentsInParent(this, cc.Mask)); }, _checknSetupSysEvent: function _checknSetupSysEvent(type) { var newAdded = false; var forDispatch = false; if (-1 !== _touchEvents.indexOf(type)) { if (!this._touchListener) { this._touchListener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, owner: this, mask: _searchComponentsInParent(this, cc.Mask), onTouchBegan: _touchStartHandler, onTouchMoved: _touchMoveHandler, onTouchEnded: _touchEndHandler, onTouchCancelled: _touchCancelHandler }); eventManager.addListener(this._touchListener, this); newAdded = true; } forDispatch = true; } else if (-1 !== _mouseEvents.indexOf(type)) { if (!this._mouseListener) { this._mouseListener = cc.EventListener.create({ event: cc.EventListener.MOUSE, _previousIn: false, owner: this, mask: _searchComponentsInParent(this, cc.Mask), onMouseDown: _mouseDownHandler, onMouseMove: _mouseMoveHandler, onMouseUp: _mouseUpHandler, onMouseScroll: _mouseWheelHandler }); eventManager.addListener(this._mouseListener, this); newAdded = true; } forDispatch = true; } newAdded && !this._activeInHierarchy && cc.director.getScheduler().schedule((function() { this._activeInHierarchy || eventManager.pauseTarget(this); }), this, 0, 0, 0, false); return forDispatch; }, on: function on(type, callback, target, useCapture) { var forDispatch = this._checknSetupSysEvent(type); if (forDispatch) return this._onDispatch(type, callback, target, useCapture); switch (type) { case EventType.POSITION_CHANGED: this._eventMask |= POSITION_ON; break; case EventType.SCALE_CHANGED: this._eventMask |= SCALE_ON; break; case EventType.ROTATION_CHANGED: this._eventMask |= ROTATION_ON; break; case EventType.SIZE_CHANGED: this._eventMask |= SIZE_ON; break; case EventType.ANCHOR_CHANGED: this._eventMask |= ANCHOR_ON; break; case EventType.COLOR_CHANGED: this._eventMask |= COLOR_ON; } this._bubblingListeners || (this._bubblingListeners = new EventTarget()); return this._bubblingListeners.on(type, callback, target); }, once: function once(type, callback, target, useCapture) { var _this = this; var forDispatch = this._checknSetupSysEvent(type); var listeners = null; listeners = forDispatch && useCapture ? this._capturingListeners = this._capturingListeners || new EventTarget() : this._bubblingListeners = this._bubblingListeners || new EventTarget(); listeners.once(type, callback, target); listeners.once(type, (function() { _this.off(type, callback, target); }), void 0); }, _onDispatch: function _onDispatch(type, callback, target, useCapture) { if ("boolean" === typeof target) { useCapture = target; target = void 0; } else useCapture = !!useCapture; if (!callback) { cc.errorID(6800); return; } var listeners = null; listeners = useCapture ? this._capturingListeners = this._capturingListeners || new EventTarget() : this._bubblingListeners = this._bubblingListeners || new EventTarget(); if (!listeners.hasEventListener(type, callback, target)) { listeners.on(type, callback, target); target && target.__eventTargets && target.__eventTargets.push(this); } return callback; }, off: function off(type, callback, target, useCapture) { var touchEvent = -1 !== _touchEvents.indexOf(type); var mouseEvent = !touchEvent && -1 !== _mouseEvents.indexOf(type); if (touchEvent || mouseEvent) { this._offDispatch(type, callback, target, useCapture); if (touchEvent) { if (this._touchListener && !_checkListeners(this, _touchEvents)) { eventManager.removeListener(this._touchListener); this._touchListener = null; } } else if (mouseEvent && this._mouseListener && !_checkListeners(this, _mouseEvents)) { eventManager.removeListener(this._mouseListener); this._mouseListener = null; } } else if (this._bubblingListeners) { this._bubblingListeners.off(type, callback, target); var hasListeners = this._bubblingListeners.hasEventListener(type); if (!hasListeners) switch (type) { case EventType.POSITION_CHANGED: this._eventMask &= ~POSITION_ON; break; case EventType.SCALE_CHANGED: this._eventMask &= ~SCALE_ON; break; case EventType.ROTATION_CHANGED: this._eventMask &= ~ROTATION_ON; break; case EventType.SIZE_CHANGED: this._eventMask &= ~SIZE_ON; break; case EventType.ANCHOR_CHANGED: this._eventMask &= ~ANCHOR_ON; break; case EventType.COLOR_CHANGED: this._eventMask &= ~COLOR_ON; } } }, _offDispatch: function _offDispatch(type, callback, target, useCapture) { if ("boolean" === typeof target) { useCapture = target; target = void 0; } else useCapture = !!useCapture; if (callback) { var listeners = useCapture ? this._capturingListeners : this._bubblingListeners; if (listeners) { listeners.off(type, callback, target); target && target.__eventTargets && js.array.fastRemove(target.__eventTargets, this); } } else { this._capturingListeners && this._capturingListeners.removeAll(type); this._bubblingListeners && this._bubblingListeners.removeAll(type); } }, targetOff: function targetOff(target) { var listeners = this._bubblingListeners; if (listeners) { listeners.targetOff(target); this._eventMask & POSITION_ON && !listeners.hasEventListener(EventType.POSITION_CHANGED) && (this._eventMask &= ~POSITION_ON); this._eventMask & SCALE_ON && !listeners.hasEventListener(EventType.SCALE_CHANGED) && (this._eventMask &= ~SCALE_ON); this._eventMask & ROTATION_ON && !listeners.hasEventListener(EventType.ROTATION_CHANGED) && (this._eventMask &= ~ROTATION_ON); this._eventMask & SIZE_ON && !listeners.hasEventListener(EventType.SIZE_CHANGED) && (this._eventMask &= ~SIZE_ON); this._eventMask & ANCHOR_ON && !listeners.hasEventListener(EventType.ANCHOR_CHANGED) && (this._eventMask &= ~ANCHOR_ON); this._eventMask & COLOR_ON && !listeners.hasEventListener(EventType.COLOR_CHANGED) && (this._eventMask &= ~COLOR_ON); } this._capturingListeners && this._capturingListeners.targetOff(target); target && target.__eventTargets && js.array.fastRemove(target.__eventTargets, this); if (this._touchListener && !_checkListeners(this, _touchEvents)) { eventManager.removeListener(this._touchListener); this._touchListener = null; } if (this._mouseListener && !_checkListeners(this, _mouseEvents)) { eventManager.removeListener(this._mouseListener); this._mouseListener = null; } }, hasEventListener: function hasEventListener(type) { var has = false; this._bubblingListeners && (has = this._bubblingListeners.hasEventListener(type)); !has && this._capturingListeners && (has = this._capturingListeners.hasEventListener(type)); return has; }, emit: function emit(type, arg1, arg2, arg3, arg4, arg5) { this._bubblingListeners && this._bubblingListeners.emit(type, arg1, arg2, arg3, arg4, arg5); }, dispatchEvent: function dispatchEvent(event) { var _array = _cachedPool.get(); _doDispatchEvent(this, event, _array); _cachedPool.put(_array); }, pauseSystemEvents: function pauseSystemEvents(recursive) { eventManager.pauseTarget(this, recursive); }, resumeSystemEvents: function resumeSystemEvents(recursive) { eventManager.resumeTarget(this, recursive); }, _hitTest: function _hitTest(point, listener) { var w = this._contentSize.width, h = this._contentSize.height, cameraPt = _htVec3a, testPt = _htVec3b; var camera = cc.Camera.findCamera(this); camera ? camera.getScreenToWorldPoint(point, cameraPt) : cameraPt.set(point); this._updateWorldMatrix(); if (!_valueTypes.Mat4.invert(_mat4_temp, this._worldMatrix)) return false; _valueTypes.Vec2.transformMat4(testPt, cameraPt, _mat4_temp); testPt.x += this._anchorPoint.x * w; testPt.y += this._anchorPoint.y * h; var hit = false; if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { hit = true; if (listener && listener.mask) { var mask = listener.mask; var parent = this; var length = mask ? mask.length : 0; for (var i = 0, j = 0; parent && j < length; ++i, parent = parent.parent) { var temp = mask[j]; if (i === temp.index) { if (parent !== temp.node) { mask.length = j; break; } var comp = parent.getComponent(cc.Mask); if (comp && comp._enabled && !comp._hitTest(cameraPt)) { hit = false; break; } j++; } else if (i > temp.index) { mask.length = j; break; } } } } return hit; }, _getCapturingTargets: function _getCapturingTargets(type, array) { var parent = this.parent; while (parent) { parent._capturingListeners && parent._capturingListeners.hasEventListener(type) && array.push(parent); parent = parent.parent; } }, _getBubblingTargets: function _getBubblingTargets(type, array) { var parent = this.parent; while (parent) { parent._bubblingListeners && parent._bubblingListeners.hasEventListener(type) && array.push(parent); parent = parent.parent; } }, runAction: ActionManagerExist ? function(action) { if (!this.active) return; cc.assertID(action, 1618); var am = cc.director.getActionManager(); if (!am._suppressDeprecation) { am._suppressDeprecation = true; cc.warnID(1639); } am.addAction(action, this, false); return action; } : emptyFunc, pauseAllActions: ActionManagerExist ? function() { cc.director.getActionManager().pauseTarget(this); } : emptyFunc, resumeAllActions: ActionManagerExist ? function() { cc.director.getActionManager().resumeTarget(this); } : emptyFunc, stopAllActions: ActionManagerExist ? function() { cc.director.getActionManager().removeAllActionsFromTarget(this); } : emptyFunc, stopAction: ActionManagerExist ? function(action) { cc.director.getActionManager().removeAction(action); } : emptyFunc, stopActionByTag: ActionManagerExist ? function(tag) { if (tag === cc.Action.TAG_INVALID) { cc.logID(1612); return; } cc.director.getActionManager().removeActionByTag(tag, this); } : emptyFunc, getActionByTag: ActionManagerExist ? function(tag) { if (tag === cc.Action.TAG_INVALID) { cc.logID(1613); return null; } return cc.director.getActionManager().getActionByTag(tag, this); } : function() { return null; }, getNumberOfRunningActions: ActionManagerExist ? function() { return cc.director.getActionManager().getNumberOfRunningActionsInTarget(this); } : function() { return 0; }, getPosition: function getPosition(out) { out = out || new _valueTypes.Vec3(); return _valueTypes.Trs.toPosition(out, this._trs); }, setPosition: function setPosition(newPosOrX, y, z) { var x; if (void 0 === y) { x = newPosOrX.x; y = newPosOrX.y; z = newPosOrX.z; } else x = newPosOrX; var trs = this._trs; void 0 === z && (z = trs[2]); if (trs[0] === x && trs[1] === y && trs[2] === z) return; var oldPosition; false; trs[0] = x; trs[1] = y; trs[2] = z; this.setLocalDirty(LocalDirtyFlag.ALL_POSITION); true, this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } }, getScale: function getScale(out) { if (void 0 !== out) return _valueTypes.Trs.toScale(out, this._trs); cc.errorID(1400, "cc.Node.getScale", "cc.Node.scale or cc.Node.getScale(cc.Vec3)"); return this._trs[7]; }, setScale: function setScale(newScaleOrX, y, z) { var x; if (newScaleOrX && "number" !== typeof newScaleOrX) { x = newScaleOrX.x; y = newScaleOrX.y; z = newScaleOrX.z; } else if (void 0 !== newScaleOrX && void 0 === y) { x = newScaleOrX; y = newScaleOrX; z = newScaleOrX; } else x = newScaleOrX; var trs = this._trs; void 0 === z && (z = trs[9]); if (trs[7] !== x || trs[8] !== y || trs[9] !== z) { trs[7] = x; trs[8] = y; trs[9] = z; this.setLocalDirty(LocalDirtyFlag.ALL_SCALE); true, this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } }, getRotation: function getRotation(out) { if (out instanceof _valueTypes.Quat) return _valueTypes.Trs.toRotation(out, this._trs); true; cc.warn("`cc.Node.getRotation()` is deprecated since v2.1.0, please use `-cc.Node.angle` instead. (`this.node.getRotation()` -> `-this.node.angle`)"); return -this.angle; }, setRotation: function setRotation(rotation, y, z, w) { if ("number" === typeof rotation && void 0 === y) { true; cc.warn("`cc.Node.setRotation(degree)` is deprecated since v2.1.0, please set `-cc.Node.angle` instead. (`this.node.setRotation(x)` -> `this.node.angle = -x`)"); this.angle = -rotation; } else { var x = rotation; if (void 0 === y) { x = rotation.x; y = rotation.y; z = rotation.z; w = rotation.w; } var trs = this._trs; if (trs[3] !== x || trs[4] !== y || trs[5] !== z || trs[6] !== w) { trs[3] = x; trs[4] = y; trs[5] = z; trs[6] = w; this.setLocalDirty(LocalDirtyFlag.ALL_ROTATION); this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); false; } } }, getContentSize: function getContentSize() { return cc.size(this._contentSize.width, this._contentSize.height); }, setContentSize: function setContentSize(size, height) { var locContentSize = this._contentSize; var clone; if (void 0 === height) { if ((0, _utils.approx)(size.width, locContentSize.width) && (0, _utils.approx)(size.height, locContentSize.height)) return; false; locContentSize.width = size.width; locContentSize.height = size.height; } else { if ((0, _utils.approx)(size, locContentSize.width) && (0, _utils.approx)(height, locContentSize.height)) return; false; locContentSize.width = size; locContentSize.height = height; } if (this._eventMask & SIZE_ON) { false; this.emit(EventType.SIZE_CHANGED); } }, getAnchorPoint: function getAnchorPoint() { return cc.v2(this._anchorPoint); }, setAnchorPoint: function setAnchorPoint(point, y) { var locAnchorPoint = this._anchorPoint; if (void 0 === y) { if (point.x === locAnchorPoint.x && point.y === locAnchorPoint.y) return; locAnchorPoint.x = point.x; locAnchorPoint.y = point.y; } else { if (point === locAnchorPoint.x && y === locAnchorPoint.y) return; locAnchorPoint.x = point; locAnchorPoint.y = y; } this.setLocalDirty(LocalDirtyFlag.ALL_POSITION); this._eventMask & ANCHOR_ON && this.emit(EventType.ANCHOR_CHANGED); }, _invTransformPoint: function _invTransformPoint(out, pos) { this._parent ? this._parent._invTransformPoint(out, pos) : _valueTypes.Vec3.copy(out, pos); var ltrs = this._trs; _valueTypes.Trs.toPosition(_tpVec3a, ltrs); _valueTypes.Vec3.sub(out, out, _tpVec3a); _valueTypes.Trs.toRotation(_tpQuata, ltrs); _valueTypes.Quat.conjugate(_tpQuatb, _tpQuata); _valueTypes.Vec3.transformQuat(out, out, _tpQuatb); _valueTypes.Trs.toScale(_tpVec3a, ltrs); _valueTypes.Vec3.inverseSafe(_tpVec3b, _tpVec3a); _valueTypes.Vec3.mul(out, out, _tpVec3b); return out; }, getWorldPosition: function getWorldPosition(out) { _valueTypes.Trs.toPosition(out, this._trs); var curr = this._parent; var ltrs; while (curr) { ltrs = curr._trs; _valueTypes.Trs.toScale(_gwpVec3, ltrs); _valueTypes.Vec3.mul(out, out, _gwpVec3); _valueTypes.Trs.toRotation(_gwpQuat, ltrs); _valueTypes.Vec3.transformQuat(out, out, _gwpQuat); _valueTypes.Trs.toPosition(_gwpVec3, ltrs); _valueTypes.Vec3.add(out, out, _gwpVec3); curr = curr._parent; } return out; }, setWorldPosition: function setWorldPosition(pos) { var ltrs = this._trs; var oldPosition; false; this._parent ? this._parent._invTransformPoint(_swpVec3, pos) : _valueTypes.Vec3.copy(_swpVec3, pos); _valueTypes.Trs.fromPosition(ltrs, _swpVec3); this.setLocalDirty(LocalDirtyFlag.ALL_POSITION); if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } }, getWorldRotation: function getWorldRotation(out) { _valueTypes.Trs.toRotation(_gwrQuat, this._trs); _valueTypes.Quat.copy(out, _gwrQuat); var curr = this._parent; while (curr) { _valueTypes.Trs.toRotation(_gwrQuat, curr._trs); _valueTypes.Quat.mul(out, _gwrQuat, out); curr = curr._parent; } return out; }, setWorldRotation: function setWorldRotation(val) { if (this._parent) { this._parent.getWorldRotation(_swrQuat); _valueTypes.Quat.conjugate(_swrQuat, _swrQuat); _valueTypes.Quat.mul(_swrQuat, _swrQuat, val); } else _valueTypes.Quat.copy(_swrQuat, val); _valueTypes.Trs.fromRotation(this._trs, _swrQuat); false; this.setLocalDirty(LocalDirtyFlag.ALL_ROTATION); }, getWorldScale: function getWorldScale(out) { _valueTypes.Trs.toScale(_gwsVec3, this._trs); _valueTypes.Vec3.copy(out, _gwsVec3); var curr = this._parent; while (curr) { _valueTypes.Trs.toScale(_gwsVec3, curr._trs); _valueTypes.Vec3.mul(out, out, _gwsVec3); curr = curr._parent; } return out; }, setWorldScale: function setWorldScale(scale) { if (this._parent) { this._parent.getWorldScale(_swsVec3); _valueTypes.Vec3.div(_swsVec3, scale, _swsVec3); } else _valueTypes.Vec3.copy(_swsVec3, scale); _valueTypes.Trs.fromScale(this._trs, _swsVec3); this.setLocalDirty(LocalDirtyFlag.ALL_SCALE); }, getWorldRT: function getWorldRT(out) { var opos = _gwrtVec3a; var orot = _gwrtQuata; var ltrs = this._trs; _valueTypes.Trs.toPosition(opos, ltrs); _valueTypes.Trs.toRotation(orot, ltrs); var curr = this._parent; while (curr) { ltrs = curr._trs; _valueTypes.Trs.toScale(_gwrtVec3b, ltrs); _valueTypes.Vec3.mul(opos, opos, _gwrtVec3b); _valueTypes.Trs.toRotation(_gwrtQuatb, ltrs); _valueTypes.Vec3.transformQuat(opos, opos, _gwrtQuatb); _valueTypes.Trs.toPosition(_gwrtVec3b, ltrs); _valueTypes.Vec3.add(opos, opos, _gwrtVec3b); _valueTypes.Quat.mul(orot, _gwrtQuatb, orot); curr = curr._parent; } _valueTypes.Mat4.fromRT(out, orot, opos); return out; }, lookAt: function lookAt(pos, up) { this.getWorldPosition(_laVec3); _valueTypes.Vec3.sub(_laVec3, _laVec3, pos); _valueTypes.Vec3.normalize(_laVec3, _laVec3); _valueTypes.Quat.fromViewUp(_laQuat, _laVec3, up); this.setWorldRotation(_laQuat); }, _updateLocalMatrix: updateLocalMatrix2D, _calculWorldMatrix: function _calculWorldMatrix() { this._localMatDirty & LocalDirtyFlag.TRSS && this._updateLocalMatrix(); var parent = this._parent; parent ? this._mulMat(this._worldMatrix, parent._worldMatrix, this._matrix) : _valueTypes.Mat4.copy(this._worldMatrix, this._matrix); this._worldMatDirty = false; }, _mulMat: mulMat2D, _updateWorldMatrix: function _updateWorldMatrix() { this._parent && this._parent._updateWorldMatrix(); if (this._worldMatDirty) { this._calculWorldMatrix(); var children = this._children; for (var i = 0, l = children.length; i < l; i++) children[i]._worldMatDirty = true; } }, setLocalDirty: function setLocalDirty(flag) { this._localMatDirty |= flag; this._worldMatDirty = true; flag === LocalDirtyFlag.ALL_POSITION || flag === LocalDirtyFlag.POSITION ? this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM : this._renderFlag |= RenderFlow.FLAG_TRANSFORM; }, setWorldDirty: function setWorldDirty() { this._worldMatDirty = true; }, getLocalMatrix: function getLocalMatrix(out) { this._updateLocalMatrix(); return _valueTypes.Mat4.copy(out, this._matrix); }, getWorldMatrix: function getWorldMatrix(out) { this._updateWorldMatrix(); return _valueTypes.Mat4.copy(out, this._worldMatrix); }, convertToNodeSpaceAR: function convertToNodeSpaceAR(worldPoint, out) { this._updateWorldMatrix(); _valueTypes.Mat4.invert(_mat4_temp, this._worldMatrix); if (worldPoint instanceof cc.Vec2) { out = out || new cc.Vec2(); return _valueTypes.Vec2.transformMat4(out, worldPoint, _mat4_temp); } out = out || new cc.Vec3(); return _valueTypes.Vec3.transformMat4(out, worldPoint, _mat4_temp); }, convertToWorldSpaceAR: function convertToWorldSpaceAR(nodePoint, out) { this._updateWorldMatrix(); if (nodePoint instanceof cc.Vec2) { out = out || new cc.Vec2(); return _valueTypes.Vec2.transformMat4(out, nodePoint, this._worldMatrix); } out = out || new cc.Vec3(); return _valueTypes.Vec3.transformMat4(out, nodePoint, this._worldMatrix); }, convertToNodeSpace: function convertToNodeSpace(worldPoint) { this._updateWorldMatrix(); _valueTypes.Mat4.invert(_mat4_temp, this._worldMatrix); var out = new cc.Vec2(); _valueTypes.Vec2.transformMat4(out, worldPoint, _mat4_temp); out.x += this._anchorPoint.x * this._contentSize.width; out.y += this._anchorPoint.y * this._contentSize.height; return out; }, convertToWorldSpace: function convertToWorldSpace(nodePoint) { this._updateWorldMatrix(); var out = new cc.Vec2(nodePoint.x - this._anchorPoint.x * this._contentSize.width, nodePoint.y - this._anchorPoint.y * this._contentSize.height); return _valueTypes.Vec2.transformMat4(out, out, this._worldMatrix); }, getNodeToParentTransform: function getNodeToParentTransform(out) { out || (out = AffineTrans.identity()); this._updateLocalMatrix(); var contentSize = this._contentSize; _vec3_temp.x = -this._anchorPoint.x * contentSize.width; _vec3_temp.y = -this._anchorPoint.y * contentSize.height; _valueTypes.Mat4.copy(_mat4_temp, this._matrix); _valueTypes.Mat4.transform(_mat4_temp, _mat4_temp, _vec3_temp); return AffineTrans.fromMat4(out, _mat4_temp); }, getNodeToParentTransformAR: function getNodeToParentTransformAR(out) { out || (out = AffineTrans.identity()); this._updateLocalMatrix(); return AffineTrans.fromMat4(out, this._matrix); }, getNodeToWorldTransform: function getNodeToWorldTransform(out) { out || (out = AffineTrans.identity()); this._updateWorldMatrix(); var contentSize = this._contentSize; _vec3_temp.x = -this._anchorPoint.x * contentSize.width; _vec3_temp.y = -this._anchorPoint.y * contentSize.height; _valueTypes.Mat4.copy(_mat4_temp, this._worldMatrix); _valueTypes.Mat4.transform(_mat4_temp, _mat4_temp, _vec3_temp); return AffineTrans.fromMat4(out, _mat4_temp); }, getNodeToWorldTransformAR: function getNodeToWorldTransformAR(out) { out || (out = AffineTrans.identity()); this._updateWorldMatrix(); return AffineTrans.fromMat4(out, this._worldMatrix); }, getParentToNodeTransform: function getParentToNodeTransform(out) { out || (out = AffineTrans.identity()); this._updateLocalMatrix(); _valueTypes.Mat4.invert(_mat4_temp, this._matrix); return AffineTrans.fromMat4(out, _mat4_temp); }, getWorldToNodeTransform: function getWorldToNodeTransform(out) { out || (out = AffineTrans.identity()); this._updateWorldMatrix(); _valueTypes.Mat4.invert(_mat4_temp, this._worldMatrix); return AffineTrans.fromMat4(out, _mat4_temp); }, convertTouchToNodeSpace: function convertTouchToNodeSpace(touch) { return this.convertToNodeSpace(touch.getLocation()); }, convertTouchToNodeSpaceAR: function convertTouchToNodeSpaceAR(touch) { return this.convertToNodeSpaceAR(touch.getLocation()); }, getBoundingBox: function getBoundingBox() { this._updateLocalMatrix(); var width = this._contentSize.width; var height = this._contentSize.height; var rect = cc.rect(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height); return rect.transformMat4(rect, this._matrix); }, getBoundingBoxToWorld: function getBoundingBoxToWorld() { if (this._parent) { this._parent._updateWorldMatrix(); return this._getBoundingBoxTo(); } return this.getBoundingBox(); }, _getBoundingBoxTo: function _getBoundingBoxTo() { var width = this._contentSize.width; var height = this._contentSize.height; var rect = cc.rect(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height); this._calculWorldMatrix(); rect.transformMat4(rect, this._worldMatrix); if (!this._children) return rect; var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var child = locChildren[i]; if (child && child.active) { var childRect = child._getBoundingBoxTo(); childRect && rect.union(rect, childRect); } } return rect; }, _updateOrderOfArrival: function _updateOrderOfArrival() { var arrivalOrder = this._parent ? ++this._parent._childArrivalOrder : 0; this._localZOrder = 4294901760 & this._localZOrder | arrivalOrder; this.emit(EventType.SIBLING_ORDER_CHANGED); }, setSelfGroupIndex: function setSelfGroupIndex(groupIndex) { this._groupIndex = groupIndex || 0; this._cullingMask = 1 << groupIndex; false; }, addChild: function addChild(child, zIndex, name) { false; cc.assertID(child, 1606); cc.assertID(null === child._parent, 1605); child.parent = this; void 0 !== zIndex && (child.zIndex = zIndex); void 0 !== name && (child.name = name); }, cleanup: function cleanup() { ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this); eventManager.removeListeners(this); var i, len = this._children.length, node; for (i = 0; i < len; ++i) { node = this._children[i]; node && node.cleanup(); } }, sortAllChildren: function sortAllChildren() { if (this._reorderChildDirty) { this._reorderChildDirty = false; var _children = this._children, child; this._childArrivalOrder = 1; for (var i = 0, len = _children.length; i < len; i++) { child = _children[i]; child._updateOrderOfArrival(); } eventManager._setDirtyForNode(this); if (_children.length > 1) { var _child, child2; for (var _i2 = 1, count = _children.length; _i2 < count; _i2++) { _child = _children[_i2]; var j = _i2; for (;j > 0 && (child2 = _children[j - 1])._localZOrder > _child._localZOrder; j--) _children[j] = child2; _children[j] = _child; } this.emit(EventType.CHILD_REORDER, this); } cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); } }, _delaySort: function _delaySort() { if (!this._reorderChildDirty) { this._reorderChildDirty = true; cc.director.__fastOn(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); } }, _restoreProperties: false, onRestore: false }; false; var Node = cc.Class(NodeDefines); var _p = Node.prototype; js.getset(_p, "position", _p.getPosition, _p.setPosition, false, true); var vec3_tmp; false; cc.Node = module.exports = Node; }), { "./event-manager": 117, "./event/event": 120, "./event/event-target": 119, "./platform/CCMacro": 134, "./platform/js": 150, "./renderer/render-flow": 161, "./utils/affine-transform": 208, "./utils/base-node": 209, "./utils/prefab-helper": 220, "./utils/trans-pool": 226, "./value-types": 232, "./value-types/utils": 239 } ], 25: [ (function(require, module, exports) { "use strict"; function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = "undefined" !== typeof Symbol && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && "number" === typeof o.length) { it && (o = it); var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if ("string" === typeof o) return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); "Object" === n && o.constructor && (n = o.constructor.name); if ("Map" === n || "Set" === n) return Array.from(o); if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { (null == len || len > arr.length) && (len = arr.length); for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var Node = require("./CCNode"); var RenderFlow = require("./renderer/render-flow"); var HideInHierarchy = cc.Object.Flags.HideInHierarchy; var LocalDirtyFlag = Node._LocalDirtyFlag; var POSITION_ON = 1; var PrivateNode = cc.Class({ name: "cc.PrivateNode", extends: Node, properties: { x: { get: function get() { return this._originPos.x; }, set: function set(value) { var localPosition = this._originPos; if (value !== localPosition.x) { localPosition.x = value; this._posDirty(true); } }, override: true }, y: { get: function get() { return this._originPos.y; }, set: function set(value) { var localPosition = this._originPos; if (value !== localPosition.y) { localPosition.y = value; this._posDirty(true); } }, override: true }, zIndex: { get: function get() { return cc.macro.MIN_ZINDEX; }, set: function set() {}, override: true }, showInEditor: { default: false, editorOnly: true, override: true } }, ctor: function ctor(name) { this._localZOrder = cc.macro.MIN_ZINDEX << 16; this._originPos = cc.v2(); false; }, _posDirty: function _posDirty(sendEvent) { this.setLocalDirty(LocalDirtyFlag.POSITION); true, this._renderFlag |= RenderFlow.FLAG_TRANSFORM; true === sendEvent && this._eventMask & POSITION_ON && this.emit(Node.EventType.POSITION_CHANGED); }, _updateLocalMatrix: function _updateLocalMatrix() { if (!this._localMatDirty) return; var parent = this.parent; if (parent) { this._trs[0] = this._originPos.x - (parent._anchorPoint.x - .5) * parent._contentSize.width; this._trs[1] = this._originPos.y - (parent._anchorPoint.y - .5) * parent._contentSize.height; } this._super(); }, getPosition: function getPosition() { return new cc.Vec2(this._originPos); }, setPosition: function setPosition(x, y) { if (void 0 === y) { x = x.x; y = x.y; } var pos = this._originPos; if (pos.x === x && pos.y === y) return; pos.x = x; pos.y = y; this._posDirty(true); }, setParent: function setParent(value) { var oldParent = this._parent; this._super(value); if (oldParent !== value) { oldParent && oldParent.off(Node.EventType.ANCHOR_CHANGED, this._posDirty, this); value && value.on(Node.EventType.ANCHOR_CHANGED, this._posDirty, this); } }, _updateOrderOfArrival: function _updateOrderOfArrival() {} }); var proto = PrivateNode.prototype; cc.js.getset(proto, "parent", proto.getParent, proto.setParent); cc.js.getset(proto, "position", proto.getPosition, proto.setPosition); false; cc.PrivateNode = module.exports = PrivateNode; }), { "./CCNode": 24, "./renderer/render-flow": 161 } ], 26: [ (function(require, module, exports) { "use strict"; var NIL = function NIL() {}; cc.Scene = cc.Class({ name: "cc.Scene", extends: require("./CCNode"), properties: { _is3DNode: { default: true, override: true }, autoReleaseAssets: false }, ctor: function ctor() { this._anchorPoint.x = 0; this._anchorPoint.y = 0; this._activeInHierarchy = false; this._inited = !cc.game._isCloning; false; this.dependAssets = null; }, destroy: function destroy() { if (cc.Object.prototype.destroy.call(this)) { var children = this._children; for (var i = 0; i < children.length; ++i) children[i].active = false; } this._active = false; this._activeInHierarchy = false; }, _onHierarchyChanged: NIL, _instantiate: null, _load: function _load() { if (!this._inited) { false; this._onBatchCreated(false); this._inited = true; } }, _activate: function _activate(active) { active = false !== active; false, false; cc.director._nodeActivator.activateNode(this, active); } }); module.exports = cc.Scene; }), { "./CCNode": 24 } ], 27: [ (function(require, module, exports) { "use strict"; var js = require("./platform/js"); var IdGenerater = require("./platform/id-generater"); var MAX_POOL_SIZE = 20; var idGenerater = new IdGenerater("Scheduler"); var ListEntry = function ListEntry(target, priority, paused, markedForDeletion) { this.target = target; this.priority = priority; this.paused = paused; this.markedForDeletion = markedForDeletion; }; var _listEntries = []; ListEntry.get = function(target, priority, paused, markedForDeletion) { var result = _listEntries.pop(); if (result) { result.target = target; result.priority = priority; result.paused = paused; result.markedForDeletion = markedForDeletion; } else result = new ListEntry(target, priority, paused, markedForDeletion); return result; }; ListEntry.put = function(entry) { if (_listEntries.length < MAX_POOL_SIZE) { entry.target = null; _listEntries.push(entry); } }; var HashUpdateEntry = function HashUpdateEntry(list, entry, target, callback) { this.list = list; this.entry = entry; this.target = target; this.callback = callback; }; var _hashUpdateEntries = []; HashUpdateEntry.get = function(list, entry, target, callback) { var result = _hashUpdateEntries.pop(); if (result) { result.list = list; result.entry = entry; result.target = target; result.callback = callback; } else result = new HashUpdateEntry(list, entry, target, callback); return result; }; HashUpdateEntry.put = function(entry) { if (_hashUpdateEntries.length < MAX_POOL_SIZE) { entry.list = entry.entry = entry.target = entry.callback = null; _hashUpdateEntries.push(entry); } }; var HashTimerEntry = function HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) { var _t = this; _t.timers = timers; _t.target = target; _t.timerIndex = timerIndex; _t.currentTimer = currentTimer; _t.currentTimerSalvaged = currentTimerSalvaged; _t.paused = paused; }; var _hashTimerEntries = []; HashTimerEntry.get = function(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) { var result = _hashTimerEntries.pop(); if (result) { result.timers = timers; result.target = target; result.timerIndex = timerIndex; result.currentTimer = currentTimer; result.currentTimerSalvaged = currentTimerSalvaged; result.paused = paused; } else result = new HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused); return result; }; HashTimerEntry.put = function(entry) { if (_hashTimerEntries.length < MAX_POOL_SIZE) { entry.timers = entry.target = entry.currentTimer = null; _hashTimerEntries.push(entry); } }; function CallbackTimer() { this._lock = false; this._scheduler = null; this._elapsed = -1; this._runForever = false; this._useDelay = false; this._timesExecuted = 0; this._repeat = 0; this._delay = 0; this._interval = 0; this._target = null; this._callback = null; } var proto = CallbackTimer.prototype; proto.initWithCallback = function(scheduler, callback, target, seconds, repeat, delay) { this._lock = false; this._scheduler = scheduler; this._target = target; this._callback = callback; this._elapsed = -1; this._interval = seconds; this._delay = delay; this._useDelay = this._delay > 0; this._repeat = repeat; this._runForever = this._repeat === cc.macro.REPEAT_FOREVER; return true; }; proto.getInterval = function() { return this._interval; }; proto.setInterval = function(interval) { this._interval = interval; }; proto.update = function(dt) { if (-1 === this._elapsed) { this._elapsed = 0; this._timesExecuted = 0; } else { this._elapsed += dt; if (this._runForever && !this._useDelay) { if (this._elapsed >= this._interval) { this.trigger(); this._elapsed = 0; } } else { if (this._useDelay) { if (this._elapsed >= this._delay) { this.trigger(); this._elapsed -= this._delay; this._timesExecuted += 1; this._useDelay = false; } } else if (this._elapsed >= this._interval) { this.trigger(); this._elapsed = 0; this._timesExecuted += 1; } this._callback && !this._runForever && this._timesExecuted > this._repeat && this.cancel(); } } }; proto.getCallback = function() { return this._callback; }; proto.trigger = function() { if (this._target && this._callback) { this._lock = true; this._callback.call(this._target, this._elapsed); this._lock = false; } }; proto.cancel = function() { this._scheduler.unschedule(this._callback, this._target); }; var _timers = []; CallbackTimer.get = function() { return _timers.pop() || new CallbackTimer(); }; CallbackTimer.put = function(timer) { if (_timers.length < MAX_POOL_SIZE && !timer._lock) { timer._scheduler = timer._target = timer._callback = null; _timers.push(timer); } }; cc.Scheduler = function() { this._timeScale = 1; this._updatesNegList = []; this._updates0List = []; this._updatesPosList = []; this._hashForUpdates = js.createMap(true); this._hashForTimers = js.createMap(true); this._currentTarget = null; this._currentTargetSalvaged = false; this._updateHashLocked = false; this._arrayForTimers = []; }; cc.Scheduler.prototype = { constructor: cc.Scheduler, _removeHashElement: function _removeHashElement(element) { delete this._hashForTimers[element.target._id]; var arr = this._arrayForTimers; for (var i = 0, l = arr.length; i < l; i++) if (arr[i] === element) { arr.splice(i, 1); break; } HashTimerEntry.put(element); }, _removeUpdateFromHash: function _removeUpdateFromHash(entry) { var targetId = entry.target._id; var self = this, element = self._hashForUpdates[targetId]; if (element) { var list = element.list, listEntry = element.entry; for (var i = 0, l = list.length; i < l; i++) if (list[i] === listEntry) { list.splice(i, 1); break; } delete self._hashForUpdates[targetId]; ListEntry.put(listEntry); HashUpdateEntry.put(element); } }, _priorityIn: function _priorityIn(ppList, listElement, priority) { for (var i = 0; i < ppList.length; i++) if (priority < ppList[i].priority) { ppList.splice(i, 0, listElement); return; } ppList.push(listElement); }, _appendIn: function _appendIn(ppList, listElement) { ppList.push(listElement); }, enableForTarget: function enableForTarget(target) { target._id || (target.__instanceId ? cc.warnID(1513) : target._id = idGenerater.getNewId()); }, setTimeScale: function setTimeScale(timeScale) { this._timeScale = timeScale; }, getTimeScale: function getTimeScale() { return this._timeScale; }, update: function update(dt) { this._updateHashLocked = true; 1 !== this._timeScale && (dt *= this._timeScale); var i, list, len, entry; for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) { entry = list[i]; entry.paused || entry.markedForDeletion || entry.target.update(dt); } for (i = 0, list = this._updates0List, len = list.length; i < len; i++) { entry = list[i]; entry.paused || entry.markedForDeletion || entry.target.update(dt); } for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) { entry = list[i]; entry.paused || entry.markedForDeletion || entry.target.update(dt); } var elt, arr = this._arrayForTimers; for (i = 0; i < arr.length; i++) { elt = arr[i]; this._currentTarget = elt; this._currentTargetSalvaged = false; if (!elt.paused) for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++elt.timerIndex) { elt.currentTimer = elt.timers[elt.timerIndex]; elt.currentTimerSalvaged = false; elt.currentTimer.update(dt); elt.currentTimer = null; } if (this._currentTargetSalvaged && 0 === this._currentTarget.timers.length) { this._removeHashElement(this._currentTarget); --i; } } for (i = 0, list = this._updatesNegList; i < list.length; ) { entry = list[i]; entry.markedForDeletion ? this._removeUpdateFromHash(entry) : i++; } for (i = 0, list = this._updates0List; i < list.length; ) { entry = list[i]; entry.markedForDeletion ? this._removeUpdateFromHash(entry) : i++; } for (i = 0, list = this._updatesPosList; i < list.length; ) { entry = list[i]; entry.markedForDeletion ? this._removeUpdateFromHash(entry) : i++; } this._updateHashLocked = false; this._currentTarget = null; }, schedule: function schedule(callback, target, interval, repeat, delay, paused) { if ("function" !== typeof callback) { var tmp = callback; callback = target; target = tmp; } if (4 === arguments.length || 5 === arguments.length) { paused = !!repeat; repeat = cc.macro.REPEAT_FOREVER; delay = 0; } cc.assertID(target, 1502); var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var element = this._hashForTimers[targetId]; if (element) element.paused !== paused && cc.warnID(1511); else { element = HashTimerEntry.get(null, target, 0, null, null, paused); this._arrayForTimers.push(element); this._hashForTimers[targetId] = element; } var timer, i; if (null == element.timers) element.timers = []; else for (i = 0; i < element.timers.length; ++i) { timer = element.timers[i]; if (timer && callback === timer._callback) { cc.logID(1507, timer.getInterval(), interval); timer._interval = interval; return; } } timer = CallbackTimer.get(); timer.initWithCallback(this, callback, target, interval, repeat, delay); element.timers.push(timer); this._currentTarget === element && this._currentTargetSalvaged && (this._currentTargetSalvaged = false); }, scheduleUpdate: function scheduleUpdate(target, priority, paused) { var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var hashElement = this._hashForUpdates[targetId]; if (hashElement && hashElement.entry) { if (hashElement.entry.priority === priority) { hashElement.entry.markedForDeletion = false; hashElement.entry.paused = paused; return; } if (this._updateHashLocked) { cc.logID(1506); hashElement.entry.markedForDeletion = false; hashElement.entry.paused = paused; return; } this.unscheduleUpdate(target); } var listElement = ListEntry.get(target, priority, paused, false); var ppList; if (0 === priority) { ppList = this._updates0List; this._appendIn(ppList, listElement); } else { ppList = priority < 0 ? this._updatesNegList : this._updatesPosList; this._priorityIn(ppList, listElement, priority); } this._hashForUpdates[targetId] = HashUpdateEntry.get(ppList, listElement, target, null); }, unschedule: function unschedule(callback, target) { if (!target || !callback) return; var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var self = this, element = self._hashForTimers[targetId]; if (element) { var timers = element.timers; for (var i = 0, li = timers.length; i < li; i++) { var timer = timers[i]; if (callback === timer._callback) { timer !== element.currentTimer || element.currentTimerSalvaged || (element.currentTimerSalvaged = true); timers.splice(i, 1); CallbackTimer.put(timer); element.timerIndex >= i && element.timerIndex--; 0 === timers.length && (self._currentTarget === element ? self._currentTargetSalvaged = true : self._removeHashElement(element)); return; } } } }, unscheduleUpdate: function unscheduleUpdate(target) { if (!target) return; var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var element = this._hashForUpdates[targetId]; element && (this._updateHashLocked ? element.entry.markedForDeletion = true : this._removeUpdateFromHash(element.entry)); }, unscheduleAllForTarget: function unscheduleAllForTarget(target) { if (!target) return; var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var element = this._hashForTimers[targetId]; if (element) { var timers = element.timers; timers.indexOf(element.currentTimer) > -1 && !element.currentTimerSalvaged && (element.currentTimerSalvaged = true); for (var i = 0, l = timers.length; i < l; i++) CallbackTimer.put(timers[i]); timers.length = 0; this._currentTarget === element ? this._currentTargetSalvaged = true : this._removeHashElement(element); } this.unscheduleUpdate(target); }, unscheduleAll: function unscheduleAll() { this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, unscheduleAllWithMinPriority: function unscheduleAllWithMinPriority(minPriority) { var i, element, arr = this._arrayForTimers; for (i = arr.length - 1; i >= 0; i--) { element = arr[i]; this.unscheduleAllForTarget(element.target); } var entry; var temp_length = 0; if (minPriority < 0) for (i = 0; i < this._updatesNegList.length; ) { temp_length = this._updatesNegList.length; entry = this._updatesNegList[i]; entry && entry.priority >= minPriority && this.unscheduleUpdate(entry.target); temp_length == this._updatesNegList.length && i++; } if (minPriority <= 0) for (i = 0; i < this._updates0List.length; ) { temp_length = this._updates0List.length; entry = this._updates0List[i]; entry && this.unscheduleUpdate(entry.target); temp_length == this._updates0List.length && i++; } for (i = 0; i < this._updatesPosList.length; ) { temp_length = this._updatesPosList.length; entry = this._updatesPosList[i]; entry && entry.priority >= minPriority && this.unscheduleUpdate(entry.target); temp_length == this._updatesPosList.length && i++; } }, isScheduled: function isScheduled(callback, target) { cc.assertID(callback, 1508); cc.assertID(target, 1509); var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var element = this._hashForTimers[targetId]; if (!element) return false; if (null == element.timers) return false; var timers = element.timers; for (var i = 0; i < timers.length; ++i) { var timer = timers[i]; if (callback === timer._callback) return true; } return false; }, pauseAllTargets: function pauseAllTargets() { return this.pauseAllTargetsWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, pauseAllTargetsWithMinPriority: function pauseAllTargetsWithMinPriority(minPriority) { var idsWithSelectors = []; var self = this, element, locArrayForTimers = self._arrayForTimers; var i, li; for (i = 0, li = locArrayForTimers.length; i < li; i++) { element = locArrayForTimers[i]; if (element) { element.paused = true; idsWithSelectors.push(element.target); } } var entry; if (minPriority < 0) for (i = 0; i < this._updatesNegList.length; i++) { entry = this._updatesNegList[i]; if (entry && entry.priority >= minPriority) { entry.paused = true; idsWithSelectors.push(entry.target); } } if (minPriority <= 0) for (i = 0; i < this._updates0List.length; i++) { entry = this._updates0List[i]; if (entry) { entry.paused = true; idsWithSelectors.push(entry.target); } } for (i = 0; i < this._updatesPosList.length; i++) { entry = this._updatesPosList[i]; if (entry && entry.priority >= minPriority) { entry.paused = true; idsWithSelectors.push(entry.target); } } return idsWithSelectors; }, resumeTargets: function resumeTargets(targetsToResume) { if (!targetsToResume) return; for (var i = 0; i < targetsToResume.length; i++) this.resumeTarget(targetsToResume[i]); }, pauseTarget: function pauseTarget(target) { cc.assertID(target, 1503); var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var self = this, element = self._hashForTimers[targetId]; element && (element.paused = true); var elementUpdate = self._hashForUpdates[targetId]; elementUpdate && (elementUpdate.entry.paused = true); }, resumeTarget: function resumeTarget(target) { cc.assertID(target, 1504); var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var self = this, element = self._hashForTimers[targetId]; element && (element.paused = false); var elementUpdate = self._hashForUpdates[targetId]; elementUpdate && (elementUpdate.entry.paused = false); }, isTargetPaused: function isTargetPaused(target) { cc.assertID(target, 1505); var targetId = target._id; if (!targetId) if (target.__instanceId) { cc.warnID(1513); targetId = target._id = target.__instanceId; } else cc.errorID(1510); var element = this._hashForTimers[targetId]; if (element) return element.paused; var elementUpdate = this._hashForUpdates[targetId]; if (elementUpdate) return elementUpdate.entry.paused; return false; } }; cc.Scheduler.PRIORITY_SYSTEM = 1 << 31; cc.Scheduler.PRIORITY_NON_SYSTEM = cc.Scheduler.PRIORITY_SYSTEM + 1; module.exports = cc.Scheduler; }), { "./platform/id-generater": 146, "./platform/js": 150 } ], 28: [ (function(require, module, exports) { "use strict"; var preprocess = require("./preprocess"); var fetch = require("./fetch"); var Cache = require("./cache"); var helper = require("./helper"); var releaseManager = require("./releaseManager"); var dependUtil = require("./depend-util"); var load = require("./load"); var Pipeline = require("./pipeline"); var Task = require("./task"); var RequestItem = require("./request-item"); var downloader = require("./downloader"); var parser = require("./parser"); var packManager = require("./pack-manager"); var Bundle = require("./bundle"); var builtins = require("./builtins"); var factory = require("./factory"); var _require = require("./urlTransformer"), parse = _require.parse, combine = _require.combine; var _require2 = require("./utilities"), parseParameters = _require2.parseParameters, asyncify = _require2.asyncify; var _require3 = require("./shared"), assets = _require3.assets, files = _require3.files, parsed = _require3.parsed, pipeline = _require3.pipeline, transformPipeline = _require3.transformPipeline, fetchPipeline = _require3.fetchPipeline, RequestType = _require3.RequestType, bundles = _require3.bundles, BuiltinBundleName = _require3.BuiltinBundleName; function AssetManager() { this._preprocessPipe = preprocess; this._fetchPipe = fetch; this._loadPipe = load; this.pipeline = pipeline.append(preprocess).append(load); this.fetchPipeline = fetchPipeline.append(preprocess).append(fetch); this.transformPipeline = transformPipeline.append(parse).append(combine); this.bundles = bundles; this.assets = assets; this._files = files; this._parsed = parsed; this.generalImportBase = ""; this.generalNativeBase = ""; this.dependUtil = dependUtil; this._releaseManager = releaseManager; this.cacheAsset = true; this.force = false; this.utils = helper; this.downloader = downloader; this.parser = parser; this.builtins = builtins; this.packManager = packManager; this.factory = factory; this.cacheManager = null; this.presets = { default: { priority: 0 }, preload: { maxConcurrency: 2, maxRequestsPerFrame: 2, priority: -1 }, scene: { maxConcurrency: 8, maxRequestsPerFrame: 8, priority: 1 }, bundle: { maxConcurrency: 8, maxRequestsPerFrame: 8, priority: 2 }, remote: { maxRetryCount: 4 }, script: { maxConcurrency: 1024, maxRequestsPerFrame: 1024, priority: 2 } }; } AssetManager.Pipeline = Pipeline; AssetManager.Task = Task; AssetManager.Cache = Cache; AssetManager.RequestItem = RequestItem; AssetManager.Bundle = Bundle; AssetManager.BuiltinBundleName = BuiltinBundleName; AssetManager.prototype = { constructor: AssetManager, get main() { return bundles.get(BuiltinBundleName.MAIN); }, get resources() { return bundles.get(BuiltinBundleName.RESOURCES); }, get internal() { return bundles.get(BuiltinBundleName.INTERNAL); }, init: function init(options) { options = options || Object.create(null); this._files.clear(); this._parsed.clear(); this._releaseManager.init(); this.assets.clear(); this.bundles.clear(); this.packManager.init(); this.downloader.init(options.bundleVers, options.server); this.parser.init(); this.dependUtil.init(); this.generalImportBase = options.importBase; this.generalNativeBase = options.nativeBase; }, getBundle: function getBundle(name) { return bundles.get(name); }, removeBundle: function removeBundle(bundle) { bundle._destroy(); bundles.remove(bundle.name); }, loadAny: function loadAny(requests, options, onProgress, onComplete) { var _parseParameters = parseParameters(options, onProgress, onComplete), options = _parseParameters.options, onProgress = _parseParameters.onProgress, onComplete = _parseParameters.onComplete; options.preset = options.preset || "default"; requests = Array.isArray(requests) ? requests.concat() : requests; var task = new Task({ input: requests, onProgress: onProgress, onComplete: asyncify(onComplete), options: options }); pipeline.async(task); }, preloadAny: function preloadAny(requests, options, onProgress, onComplete) { var _parseParameters2 = parseParameters(options, onProgress, onComplete), options = _parseParameters2.options, onProgress = _parseParameters2.onProgress, onComplete = _parseParameters2.onComplete; options.preset = options.preset || "preload"; requests = Array.isArray(requests) ? requests.concat() : requests; var task = new Task({ input: requests, onProgress: onProgress, onComplete: asyncify(onComplete), options: options }); fetchPipeline.async(task); }, postLoadNative: function postLoadNative(asset, options, onComplete) { if (!(asset instanceof cc.Asset)) throw new Error("input is not asset"); var _parseParameters3 = parseParameters(options, void 0, onComplete), options = _parseParameters3.options, onComplete = _parseParameters3.onComplete; if (!asset._native || asset._nativeAsset) return asyncify(onComplete)(null); var depend = dependUtil.getNativeDep(asset._uuid); if (depend) { if (!bundles.has(depend.bundle)) { var bundle = bundles.find((function(bundle) { return bundle.getAssetInfo(asset._uuid); })); bundle && (depend.bundle = bundle.name); } this.loadAny(depend, options, (function(err, _native) { err ? cc.error(err.message, err.stack) : asset.isValid && !asset._nativeAsset && (asset._nativeAsset = _native); onComplete && onComplete(err); })); } }, loadRemote: function loadRemote(url, options, onComplete) { var _parseParameters4 = parseParameters(options, void 0, onComplete), options = _parseParameters4.options, onComplete = _parseParameters4.onComplete; if (this.assets.has(url)) return asyncify(onComplete)(null, this.assets.get(url)); options.__isNative__ = true; options.preset = options.preset || "remote"; this.loadAny({ url: url }, options, null, (function(err, data) { if (err) { cc.error(err.message, err.stack); onComplete && onComplete(err, null); } else factory.create(url, data, options.ext || cc.path.extname(url), options, (function(err, out) { onComplete && onComplete(err, out); })); })); }, loadScript: function loadScript(url, options, onComplete) { var _parseParameters5 = parseParameters(options, void 0, onComplete), options = _parseParameters5.options, onComplete = _parseParameters5.onComplete; options.__requestType__ = RequestType.URL; options.preset = options.preset || "script"; this.loadAny(url, options, onComplete); }, loadBundle: function loadBundle(nameOrUrl, options, onComplete) { var _parseParameters6 = parseParameters(options, void 0, onComplete), options = _parseParameters6.options, onComplete = _parseParameters6.onComplete; var bundleName = cc.path.basename(nameOrUrl); if (this.bundles.has(bundleName)) return asyncify(onComplete)(null, this.getBundle(bundleName)); options.preset = options.preset || "bundle"; options.ext = "bundle"; this.loadRemote(nameOrUrl, options, onComplete); }, releaseAsset: function releaseAsset(asset) { releaseManager.tryRelease(asset, true); }, releaseUnusedAssets: function releaseUnusedAssets() { assets.forEach((function(asset) { releaseManager.tryRelease(asset); })); }, releaseAll: function releaseAll() { assets.forEach((function(asset) { releaseManager.tryRelease(asset, true); })); false; }, _transform: function _transform(input, options) { var subTask = Task.create({ input: input, options: options }); var urls = []; try { var result = transformPipeline.sync(subTask); for (var i = 0, l = result.length; i < l; i++) { var item = result[i]; var url = item.url; item.recycle(); urls.push(url); } } catch (e) { for (var i = 0, l = subTask.output.length; i < l; i++) subTask.output[i].recycle(); cc.error(e.message, e.stack); } subTask.recycle(); return urls.length > 1 ? urls : urls[0]; } }; cc.AssetManager = AssetManager; cc.assetManager = new AssetManager(); Object.defineProperty(cc, "resources", { get: function get() { return bundles.get(BuiltinBundleName.RESOURCES); } }); module.exports = cc.assetManager; }), { "./builtins": 29, "./bundle": 30, "./cache": 31, "./depend-util": 33, "./downloader": 40, "./factory": 41, "./fetch": 42, "./helper": 44, "./load": 46, "./pack-manager": 47, "./parser": 48, "./pipeline": 49, "./preprocess": 50, "./releaseManager": 51, "./request-item": 52, "./shared": 53, "./task": 54, "./urlTransformer": 55, "./utilities": 56 } ], 29: [ (function(require, module, exports) { "use strict"; var Cache = require("./cache"); var releaseManager = require("./releaseManager"); var _require = require("./shared"), BuiltinBundleName = _require.BuiltinBundleName; var builtins = { _assets: new Cache({ material: new Cache(), effect: new Cache() }), _loadBuiltins: function _loadBuiltins(name, cb) { var dirname = name + "s"; var builtin = this._assets.get(name); return cc.assetManager.internal.loadDir(dirname, null, null, (function(err, assets) { if (err) cc.error(err.message, err.stack); else for (var i = 0; i < assets.length; i++) { var asset = assets[i]; builtin.add(asset.name, asset.addRef()); } cb(); })); }, init: function init(cb) { var _this = this; this.clear(); if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS || !cc.assetManager.bundles.has(BuiltinBundleName.INTERNAL)) return cb && cb(); this._loadBuiltins("effect", (function() { _this._loadBuiltins("material", (function() { _this._loadBuiltinsSP(cb); })); })); }, _loadBuiltinsSP: function _loadBuiltinsSP(cb) { cc.sp.MAX_MULTITEXTURE_NUM = 8; this._loadMultiEffect("multi-2d-universal", (function(effect) { cc.sp.multi2dSpriteEffectAsset = effect; effect.addRef(); cc.sp.inited = true; cc.sp.multiBatcher.init(); -1 === cc.dynamicAtlasManager.maxAtlasCount && (cc.dynamicAtlasManager.maxAtlasCount = Math.max(0, cc.sp.MAX_MULTITEXTURE_NUM - cc.sp.charAtlasAutoBatchCount)); cb(); })); }, _loadMultiEffect: function _loadMultiEffect(name, cb) { false; cc.assetManager.loadBundle("sp", (function(err, bundle) { err ? cc.error(err) : bundle.load("effects/" + name, cc.EffectAsset, (function(err, effect) { err ? cc.error(err) : cb(effect); })); })); }, getBuiltin: function getBuiltin(type, name) { return 0 === arguments.length ? this._assets : 1 === arguments.length ? this._assets.get(type) : this._assets.get(type).get(name); }, clear: function clear() { this._assets.forEach((function(assets) { assets.forEach((function(asset) { releaseManager.tryRelease(asset, true); })); assets.clear(); })); } }; module.exports = builtins; }), { "./cache": 31, "./releaseManager": 51, "./shared": 53 } ], 30: [ (function(require, module, exports) { "use strict"; var Config = require("./config"); var releaseManager = require("./releaseManager"); var _require = require("./utilities"), parseParameters = _require.parseParameters, parseLoadResArgs = _require.parseLoadResArgs; var _require2 = require("./shared"), RequestType = _require2.RequestType, assets = _require2.assets, bundles = _require2.bundles; function Bundle() { this._config = new Config(); } Bundle.prototype = { constructor: Bundle, get name() { return this._config.name; }, get deps() { return this._config.deps; }, get base() { return this._config.base; }, getInfoWithPath: function getInfoWithPath(path, type) { return this._config.getInfoWithPath(path, type); }, getDirWithPath: function getDirWithPath(path, type, out) { return this._config.getDirWithPath(path, type, out); }, getAssetInfo: function getAssetInfo(uuid) { return this._config.getAssetInfo(uuid); }, getSceneInfo: function getSceneInfo(name) { return this._config.getSceneInfo(name); }, init: function init(options) { this._config.init(options); bundles.add(options.name, this); }, load: function load(paths, type, onProgress, onComplete) { var _parseLoadResArgs = parseLoadResArgs(type, onProgress, onComplete), type = _parseLoadResArgs.type, onProgress = _parseLoadResArgs.onProgress, onComplete = _parseLoadResArgs.onComplete; cc.assetManager.loadAny(paths, { __requestType__: RequestType.PATH, type: type, bundle: this.name, __outputAsArray__: Array.isArray(paths) }, onProgress, onComplete); }, preload: function preload(paths, type, onProgress, onComplete) { var _parseLoadResArgs2 = parseLoadResArgs(type, onProgress, onComplete), type = _parseLoadResArgs2.type, onProgress = _parseLoadResArgs2.onProgress, onComplete = _parseLoadResArgs2.onComplete; cc.assetManager.preloadAny(paths, { __requestType__: RequestType.PATH, type: type, bundle: this.name }, onProgress, onComplete); }, loadDir: function loadDir(dir, type, onProgress, onComplete) { var _parseLoadResArgs3 = parseLoadResArgs(type, onProgress, onComplete), type = _parseLoadResArgs3.type, onProgress = _parseLoadResArgs3.onProgress, onComplete = _parseLoadResArgs3.onComplete; cc.assetManager.loadAny(dir, { __requestType__: RequestType.DIR, type: type, bundle: this.name, __outputAsArray__: true }, onProgress, onComplete); }, preloadDir: function preloadDir(dir, type, onProgress, onComplete) { var _parseLoadResArgs4 = parseLoadResArgs(type, onProgress, onComplete), type = _parseLoadResArgs4.type, onProgress = _parseLoadResArgs4.onProgress, onComplete = _parseLoadResArgs4.onComplete; cc.assetManager.preloadAny(dir, { __requestType__: RequestType.DIR, type: type, bundle: this.name }, onProgress, onComplete); }, loadScene: function loadScene(sceneName, options, onProgress, onComplete) { var _parseParameters = parseParameters(options, onProgress, onComplete), options = _parseParameters.options, onProgress = _parseParameters.onProgress, onComplete = _parseParameters.onComplete; options.preset = options.preset || "scene"; options.bundle = this.name; cc.assetManager.loadAny({ scene: sceneName }, options, onProgress, (function(err, sceneAsset) { if (err) { cc.error(err.message, err.stack); onComplete && onComplete(err); } else if (sceneAsset instanceof cc.SceneAsset) { var scene = sceneAsset.scene; scene._id = sceneAsset._uuid; scene._name = sceneAsset._name; onComplete && onComplete(null, sceneAsset); } else onComplete && onComplete(new Error("The asset " + sceneAsset._uuid + " is not a scene")); })); }, preloadScene: function preloadScene(sceneName, options, onProgress, onComplete) { var _parseParameters2 = parseParameters(options, onProgress, onComplete), options = _parseParameters2.options, onProgress = _parseParameters2.onProgress, onComplete = _parseParameters2.onComplete; options.bundle = this.name; cc.assetManager.preloadAny({ scene: sceneName }, options, onProgress, (function(err) { err && cc.errorID(1210, sceneName, err.message); onComplete && onComplete(err); })); }, get: function get(path, type) { var info = this.getInfoWithPath(path, type); return assets.get(info && info.uuid); }, release: function release(path, type) { releaseManager.tryRelease(this.get(path, type), true); }, releaseUnusedAssets: function releaseUnusedAssets() { var self = this; assets.forEach((function(asset) { var info = self.getAssetInfo(asset._uuid); info && !info.redirect && releaseManager.tryRelease(asset); })); }, releaseAll: function releaseAll() { var self = this; assets.forEach((function(asset) { var info = self.getAssetInfo(asset._uuid); info && !info.redirect && releaseManager.tryRelease(asset, true); })); }, _destroy: function _destroy() { this._config.destroy(); } }; module.exports = Bundle; }), { "./config": 32, "./releaseManager": 51, "./shared": 53, "./utilities": 56 } ], 31: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); function Cache(map) { if (map) { this._map = map; this._count = Object.keys(map).length; } else { this._map = js.createMap(true); this._count = 0; } } Cache.prototype = { constructor: Cache, add: function add(key, val) { key in this._map || this._count++; return this._map[key] = val; }, get: function get(key) { return this._map[key]; }, has: function has(key) { return key in this._map; }, remove: function remove(key) { var out = this._map[key]; if (key in this._map) { delete this._map[key]; this._count--; } return out; }, clear: function clear() { if (0 !== this._count) { this._map = js.createMap(true); this._count = 0; } }, forEach: function forEach(func) { for (var key in this._map) func(this._map[key], key); }, find: function find(predicate) { for (var key in this._map) if (predicate(this._map[key], key)) return this._map[key]; return null; }, get count() { return this._count; }, destroy: function destroy() { this._map = null; } }; module.exports = Cache; }), { "../platform/js": 150 } ], 32: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); var Cache = require("./cache"); var _require = require("./helper"), normalize = _require.normalize; var _require2 = require("./utilities"), processOptions = _require2.processOptions; function Config() { this.name = ""; this.base = ""; this.importBase = ""; this.nativeBase = ""; this.deps = null; this.assetInfos = new Cache(); this.scenes = new Cache(); this.paths = new Cache(); } Config.prototype = { constructor: Config, init: function init(options) { processOptions(options); this.importBase = options.importBase || ""; this.nativeBase = options.nativeBase || ""; this.base = options.base || ""; this.name = options.name || ""; this.deps = options.deps || []; this._initUuid(options.uuids); this._initPath(options.paths); this._initScene(options.scenes); this._initPackage(options.packs); this._initVersion(options.versions); this._initRedirect(options.redirect); }, _initUuid: function _initUuid(uuidList) { if (!uuidList) return; this.assetInfos.clear(); for (var i = 0, l = uuidList.length; i < l; i++) { var uuid = uuidList[i]; this.assetInfos.add(uuid, { uuid: uuid }); } }, _initPath: function _initPath(pathList) { if (!pathList) return; var paths = this.paths; paths.clear(); for (var uuid in pathList) { var info = pathList[uuid]; var path = info[0]; var type = info[1]; var isSubAsset = 3 === info.length; var assetInfo = this.assetInfos.get(uuid); assetInfo.path = path; assetInfo.ctor = js._getClassById(type); paths.has(path) ? isSubAsset ? paths.get(path).push(assetInfo) : paths.get(path).unshift(assetInfo) : paths.add(path, [ assetInfo ]); } }, _initScene: function _initScene(sceneList) { if (!sceneList) return; var scenes = this.scenes; scenes.clear(); var assetInfos = this.assetInfos; for (var sceneName in sceneList) { var uuid = sceneList[sceneName]; var assetInfo = assetInfos.get(uuid); assetInfo.url = sceneName; scenes.add(sceneName, assetInfo); } }, _initPackage: function _initPackage(packageList) { if (!packageList) return; var assetInfos = this.assetInfos; for (var packUuid in packageList) { var uuids = packageList[packUuid]; var pack = { uuid: packUuid, packs: uuids, ext: ".json" }; assetInfos.add(packUuid, pack); for (var i = 0, l = uuids.length; i < l; i++) { var uuid = uuids[i]; var assetInfo = assetInfos.get(uuid); var assetPacks = assetInfo.packs; assetPacks ? 1 === l ? assetPacks.unshift(pack) : assetPacks.push(pack) : assetInfo.packs = [ pack ]; } } }, _initVersion: function _initVersion(versions) { if (!versions) return; var assetInfos = this.assetInfos; var entries = versions["import"]; if (entries) for (var i = 0, l = entries.length; i < l; i += 2) { var uuid = entries[i]; var assetInfo = assetInfos.get(uuid); assetInfo.ver = entries[i + 1]; } entries = versions["native"]; if (entries) for (var i = 0, l = entries.length; i < l; i += 2) { var uuid = entries[i]; var assetInfo = assetInfos.get(uuid); assetInfo.nativeVer = entries[i + 1]; } }, _initRedirect: function _initRedirect(redirect) { if (!redirect) return; var assetInfos = this.assetInfos; for (var i = 0, l = redirect.length; i < l; i += 2) { var uuid = redirect[i]; var assetInfo = assetInfos.get(uuid); assetInfo.redirect = redirect[i + 1]; } }, getInfoWithPath: function getInfoWithPath(path, type) { if (!path) return null; path = normalize(path); var items = this.paths.get(path); if (items) { if (!type) return items[0]; for (var i = 0, l = items.length; i < l; i++) { var assetInfo = items[i]; if (js.isChildClassOf(assetInfo.ctor, type)) return assetInfo; } } return null; }, getDirWithPath: function getDirWithPath(path, type, out) { path = normalize(path); "/" === path[path.length - 1] && (path = path.slice(0, -1)); var infos = out || []; function isMatchByWord(path, test) { if (path.length > test.length) { var nextAscii = path.charCodeAt(test.length); return 47 === nextAscii; } return true; } this.paths.forEach((function(items, p) { if (p.startsWith(path) && isMatchByWord(p, path) || !path) for (var i = 0, l = items.length; i < l; i++) { var entry = items[i]; type && !js.isChildClassOf(entry.ctor, type) || infos.push(entry); } })); return infos; }, getAssetInfo: function getAssetInfo(uuid) { return this.assetInfos.get(uuid); }, getSceneInfo: function getSceneInfo(name) { name.endsWith(".fire") || (name += ".fire"); "/" === name[0] || name.startsWith("db://") || (name = "/" + name); var info = this.scenes.find((function(val, key) { return key.endsWith(name); })); return info; }, destroy: function destroy() { this.paths.destroy(); this.scenes.destroy(); this.assetInfos.destroy(); } }; false; module.exports = Config; }), { "../platform/js": 150, "./cache": 31, "./helper": 44, "./utilities": 56 } ], 33: [ (function(require, module, exports) { "use strict"; var _deserializeCompiled = _interopRequireWildcard(require("../platform/deserialize-compiled")); function _getRequireWildcardCache(nodeInterop) { if ("function" !== typeof WeakMap) return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (null === obj || "object" !== typeof obj && "function" !== typeof obj) return { default: obj }; var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) return cache.get(obj); var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) if ("default" !== key && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; desc && (desc.get || desc.set) ? Object.defineProperty(newObj, key, desc) : newObj[key] = obj[key]; } newObj["default"] = obj; cache && cache.set(obj, newObj); return newObj; } var Cache = require("./cache"); var deserialize = require("./deserialize"); var _require = require("./shared"), files = _require.files, parsed = _require.parsed; var dependUtil = { _depends: new Cache(), init: function init() { this._depends.clear(); }, getNativeDep: function getNativeDep(uuid) { var depend = this._depends.get(uuid); if (depend) return depend.nativeDep && Object.assign({}, depend.nativeDep); return null; }, getDeps: function getDeps(uuid) { if (this._depends.has(uuid)) return this._depends.get(uuid).deps; return []; }, getDepsRecursively: function getDepsRecursively(uuid) { var exclude = Object.create(null), depends = []; this._descend(uuid, exclude, depends); return depends; }, _descend: function _descend(uuid, exclude, depends) { var deps = this.getDeps(uuid); for (var i = 0; i < deps.length; i++) { var depend = deps[i]; if (!exclude[depend]) { exclude[depend] = true; depends.push(depend); this._descend(depend, exclude, depends); } } }, remove: function remove(uuid) { this._depends.remove(uuid); }, parse: function parse(uuid, json) { var out = null; if (Array.isArray(json) || json.__type__) { if (out = this._depends.get(uuid)) return out; if (Array.isArray(json) && (false, !(0, _deserializeCompiled.hasNativeDep)(json))) out = { deps: this._parseDepsFromJson(json) }; else try { var asset = deserialize(json); out = this._parseDepsFromAsset(asset); out.nativeDep && (out.nativeDep.uuid = uuid); parsed.add(uuid + "@import", asset); } catch (e) { files.remove(uuid + "@import"); out = { deps: [] }; } } else { if ((true, out = this._depends.get(uuid)) && out.parsedFromExistAsset) return out; out = this._parseDepsFromAsset(json); } this._depends.add(uuid, out); return out; }, _parseDepsFromAsset: function _parseDepsFromAsset(asset) { var out = { deps: [], parsedFromExistAsset: true, preventPreloadNativeObject: asset.constructor.preventPreloadNativeObject, preventDeferredLoadDependents: asset.constructor.preventDeferredLoadDependents }; var deps = asset.__depends__; for (var i = 0, l = deps.length; i < l; i++) { var dep = deps[i].uuid; out.deps.push(dep); } asset.__nativeDepend__ && (out.nativeDep = asset._nativeDep); return out; }, _parseDepsFromJson: (false, function(json) { var depends = (0, _deserializeCompiled.getDependUuidList)(json); depends.forEach((function(uuid, index) { return depends[index] = cc.assetManager.utils.decodeUuid(uuid); })); return depends; }) }; module.exports = dependUtil; }), { "../platform/deserialize-compiled": 144, "./cache": 31, "./deserialize": 35, "./shared": 53 } ], 34: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); require("../CCDirector"); var utilities = require("./utilities"); var dependUtil = require("./depend-util"); var releaseManager = require("./releaseManager"); var downloader = require("./downloader"); var factory = require("./factory"); var helper = require("./helper"); var ImageFmts = [ ".png", ".jpg", ".bmp", ".jpeg", ".gif", ".ico", ".tiff", ".webp", ".image", ".pvr", ".pkm" ]; var AudioFmts = [ ".mp3", ".ogg", ".wav", ".m4a" ]; function GetTrue() { return true; } var md5Pipe = { transformURL: function transformURL(url) { var uuid = helper.getUuidFromURL(url); if (!uuid) return url; var bundle = cc.assetManager.bundles.find((function(b) { return !!b.getAssetInfo(uuid); })); if (!bundle) return url; var hashValue = ""; var info = bundle.getAssetInfo(uuid); hashValue = url.startsWith(bundle.base + bundle._config.nativeBase) ? info.nativeVer || "" : info.ver || ""; if (!hashValue || -1 !== url.indexOf(hashValue)) return url; var hashPatchInFolder = false; ".ttf" === cc.path.extname(url) && (hashPatchInFolder = true); if (hashPatchInFolder) { var dirname = cc.path.dirname(url); var basename = cc.path.basename(url); url = dirname + "." + hashValue + "/" + basename; } else url = url.replace(/.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-]{8,})/, (function(match, uuid) { return match + "." + hashValue; })); return url; } }; var loader = { onProgress: null, _autoReleaseSetting: Object.create(null), get _cache() { return cc.assetManager.assets._map; }, load: function load(resources, progressCallback, completeCallback) { if (void 0 === completeCallback && void 0 !== progressCallback) { completeCallback = progressCallback; progressCallback = null; } resources = Array.isArray(resources) ? resources : [ resources ]; for (var i = 0; i < resources.length; i++) { var item = resources[i]; if ("string" === typeof item) resources[i] = { url: item, __isNative__: true }; else { if (item.type) { item.ext = "." + item.type; item.type = void 0; } item.url && (item.__isNative__ = true); } } var images = []; var audios = []; cc.assetManager.loadAny(resources, null, (function(finish, total, item) { item.content && (ImageFmts.includes(item.ext) ? images.push(item.content) : AudioFmts.includes(item.ext) && audios.push(item.content)); progressCallback && progressCallback(finish, total, item); }), (function(err, _native) { var res = null; if (!err) { _native = Array.isArray(_native) ? _native : [ _native ]; for (var i = 0; i < _native.length; i++) { var item = _native[i]; if (!(item instanceof cc.Asset)) { var asset = item; var url = resources[i].url; images.includes(asset) ? factory.create(url, item, ".png", null, (function(err, image) { asset = _native[i] = image; })) : audios.includes(asset) && factory.create(url, item, ".mp3", null, (function(err, audio) { asset = _native[i] = audio; })); cc.assetManager.assets.add(url, asset); } } if (_native.length > 1) { var map = Object.create(null); _native.forEach((function(asset) { map[asset._uuid] = asset; })); res = { isCompleted: GetTrue, _map: map }; } else res = _native[0]; } completeCallback && completeCallback(err, res); })); }, getXMLHttpRequest: function getXMLHttpRequest() { return new XMLHttpRequest(); }, _parseLoadResArgs: utilities.parseLoadResArgs, getItem: function getItem(key) { return cc.assetManager.assets.has(key) ? { content: cc.assetManager.assets.get(key) } : null; }, loadRes: function loadRes(url, type, progressCallback, completeCallback) { var _this$_parseLoadResAr = this._parseLoadResArgs(type, progressCallback, completeCallback), type = _this$_parseLoadResAr.type, onProgress = _this$_parseLoadResAr.onProgress, onComplete = _this$_parseLoadResAr.onComplete; var extname = cc.path.extname(url); extname && (url = url.slice(0, -extname.length)); cc.resources.load(url, type, onProgress, onComplete); }, loadResArray: function loadResArray(urls, type, progressCallback, completeCallback) { var _this$_parseLoadResAr2 = this._parseLoadResArgs(type, progressCallback, completeCallback), type = _this$_parseLoadResAr2.type, onProgress = _this$_parseLoadResAr2.onProgress, onComplete = _this$_parseLoadResAr2.onComplete; urls.forEach((function(url, i) { var extname = cc.path.extname(url); extname && (urls[i] = url.slice(0, -extname.length)); })); cc.resources.load(urls, type, onProgress, onComplete); }, loadResDir: function loadResDir(url, type, progressCallback, completeCallback) { var _this$_parseLoadResAr3 = this._parseLoadResArgs(type, progressCallback, completeCallback), type = _this$_parseLoadResAr3.type, onProgress = _this$_parseLoadResAr3.onProgress, onComplete = _this$_parseLoadResAr3.onComplete; cc.resources.loadDir(url, type, onProgress, (function(err, assets) { var urls = []; if (!err) { var infos = cc.resources.getDirWithPath(url, type); urls = infos.map((function(info) { return info.path; })); } onComplete && onComplete(err, assets, urls); })); }, getRes: function getRes(url, type) { return cc.assetManager.assets.has(url) ? cc.assetManager.assets.get(url) : cc.resources.get(url, type); }, getResCount: function getResCount() { return cc.assetManager.assets.count; }, getDependsRecursively: function getDependsRecursively(owner) { if (!owner) return []; return dependUtil.getDepsRecursively("string" === typeof owner ? owner : owner._uuid).concat([ owner._uuid ]); }, get assetLoader() { true; cc.error("cc.loader.assetLoader was removed, assetLoader and md5Pipe were merged into cc.assetManager.transformPipeline"); }, get md5Pipe() { return md5Pipe; }, get downloader() { return cc.assetManager.downloader; }, get loader() { return cc.assetManager.parser; }, addDownloadHandlers: function addDownloadHandlers(extMap) { true; cc.warn("`cc.loader.addDownloadHandlers` is deprecated, please use `cc.assetManager.downloader.register` instead"); var handler = Object.create(null); for (var type in extMap) { var func = extMap[type]; handler["." + type] = function(url, options, onComplete) { func({ url: url }, onComplete); }; } cc.assetManager.downloader.register(handler); }, addLoadHandlers: function addLoadHandlers(extMap) { true; cc.warn("`cc.loader.addLoadHandlers` is deprecated, please use `cc.assetManager.parser.register` instead"); var handler = Object.create(null); for (var type in extMap) { var func = extMap[type]; handler["." + type] = function(file, options, onComplete) { func({ content: file }, onComplete); }; } cc.assetManager.parser.register(handler); }, flowInDeps: function flowInDeps() { true; cc.error("cc.loader.flowInDeps was removed"); }, release: function release(asset) { if (Array.isArray(asset)) for (var i = 0; i < asset.length; i++) { var key = asset[i]; "string" === typeof key && (key = cc.assetManager.assets.get(key)); var isBuiltin = cc.assetManager.builtins._assets.find((function(assets) { return assets.find((function(builtinAsset) { return builtinAsset === key; })); })); if (isBuiltin) continue; cc.assetManager.releaseAsset(key); } else if (asset) { "string" === typeof asset && (asset = cc.assetManager.assets.get(asset)); var _isBuiltin = cc.assetManager.builtins._assets.find((function(assets) { return assets.find((function(builtinAsset) { return builtinAsset === asset; })); })); if (_isBuiltin) return; cc.assetManager.releaseAsset(asset); } }, releaseAsset: function releaseAsset(asset) { cc.assetManager.releaseAsset(asset); }, releaseRes: function releaseRes(url, type) { cc.resources.release(url, type); }, releaseResDir: function releaseResDir() { true; cc.error("cc.loader.releaseResDir was removed, please use cc.assetManager.releaseAsset instead"); }, releaseAll: function releaseAll() { cc.assetManager.releaseAll(); cc.assetManager.assets.clear(); }, removeItem: function removeItem(key) { cc.assetManager.assets.remove(key); }, setAutoRelease: function setAutoRelease(asset, autoRelease) { "object" === typeof asset && (asset = asset._uuid); this._autoReleaseSetting[asset] = !!autoRelease; }, setAutoReleaseRecursively: function setAutoReleaseRecursively(asset, autoRelease) { "object" === typeof asset && (asset = asset._uuid); autoRelease = !!autoRelease; this._autoReleaseSetting[asset] = autoRelease; var depends = dependUtil.getDepsRecursively(asset); for (var i = 0; i < depends.length; i++) { var depend = depends[i]; this._autoReleaseSetting[depend] = autoRelease; } }, isAutoRelease: function isAutoRelease(asset) { "object" === typeof asset && (asset = asset._uuid); return !!this._autoReleaseSetting[asset]; } }; downloader.loadSubpackage = function(name, completeCallback) { cc.assetManager.loadBundle(name, null, completeCallback); }; var AssetLibrary = { init: function init(options) { options.importBase = options.libraryPath; options.nativeBase = options.rawAssetsBase; cc.assetManager.init(options); if (options.rawAssets) { var resources = new cc.AssetManager.Bundle(); resources.init({ name: cc.AssetManager.BuiltinBundleName.RESOURCES, importBase: options.importBase, nativeBase: options.nativeBase, paths: options.rawAssets.assets, uuids: Object.keys(options.rawAssets.assets) }); } }, loadAsset: function loadAsset(uuid, onComplete) { cc.assetManager.loadAny(uuid, onComplete); }, getLibUrlNoExt: function getLibUrlNoExt() { true; cc.error("cc.AssetLibrary.getLibUrlNoExt was removed, if you want to transform url, please use cc.assetManager.utils.getUrlWithUuid instead"); }, queryAssetInfo: function queryAssetInfo() { true; cc.error("cc.AssetLibrary.queryAssetInfo was removed, only available in the editor by using cc.assetManager.editorExtend.queryAssetInfo"); } }; cc.url = { normalize: function normalize(url) { cc.warnID(1400, "cc.url.normalize", "cc.assetManager.utils.normalize"); return cc.assetManager.utils.normalize(url); }, raw: function raw(url) { cc.warnID(1400, "cc.url.raw", "cc.resources.load"); if (url.startsWith("resources/")) return cc.assetManager._transform({ path: cc.path.changeExtname(url.substr(10)), bundle: cc.AssetManager.BuiltinBundleName.RESOURCES, __isNative__: true, ext: cc.path.extname(url) }); return ""; } }; var onceWarns = { loader: true, assetLibrary: true }; Object.defineProperties(cc, { loader: { get: function get() { true; if (onceWarns.loader) { onceWarns.loader = false; cc.log("cc.loader is deprecated, use cc.assetManager instead please. See https://docs.cocos.com/creator/manual/zh/release-notes/asset-manager-upgrade-guide.html"); } return loader; } }, AssetLibrary: { get: function get() { true; if (onceWarns.assetLibrary) { onceWarns.assetLibrary = false; cc.log("cc.AssetLibrary is deprecated, use cc.assetManager instead please. See https://docs.cocos.com/creator/manual/zh/release-notes/asset-manager-upgrade-guide.html"); } return AssetLibrary; } }, LoadingItems: { get: function get() { cc.warnID(1400, "cc.LoadingItems", "cc.AssetManager.Task"); return cc.AssetManager.Task; } }, Pipeline: { get: function get() { cc.warnID(1400, "cc.Pipeline", "cc.AssetManager.Pipeline"); return cc.AssetManager.Pipeline; } } }); js.obsolete(cc, "cc.RawAsset", "cc.Asset"); js.obsolete(cc.Asset.prototype, "cc.Asset.url", "nativeUrl"); Object.defineProperties(cc.macro, { DOWNLOAD_MAX_CONCURRENT: { get: function get() { return cc.assetManager.downloader.maxConcurrency; }, set: function set(val) { cc.assetManager.downloader.maxConcurrency = val; } } }); Object.assign(cc.director, { _getSceneUuid: function _getSceneUuid(sceneName) { cc.assetManager.main.getSceneInfo(sceneName); } }); Object.defineProperties(cc.game, { _sceneInfos: { get: function get() { var scenes = []; cc.assetManager.main._config.scenes.forEach((function(val) { scenes.push(val); })); return scenes; } } }); var parseParameters = utilities.parseParameters; utilities.parseParameters = function(options, onProgress, onComplete) { var result = parseParameters(options, onProgress, onComplete); result.onProgress = result.onProgress || loader.onProgress; return result; }; var autoRelease = releaseManager._autoRelease; releaseManager._autoRelease = function() { autoRelease.apply(this, arguments); var releaseSettings = loader._autoReleaseSetting; var keys = Object.keys(releaseSettings); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (true === releaseSettings[key]) { var asset = cc.assetManager.assets.get(key); asset && releaseManager.tryRelease(asset); } } }; }), { "../CCDirector": 22, "../platform/js": 150, "./depend-util": 33, "./downloader": 40, "./factory": 41, "./helper": 44, "./releaseManager": 51, "./utilities": 56 } ], 35: [ (function(require, module, exports) { "use strict"; var helper = require("./helper"); var MissingClass = false; require("../platform/deserialize"); function deserialize(json, options) { var classFinder, missingClass; false; classFinder = cc._MissingScript.safeFindClass; var pool = null; var _require, deserializeForCompiled; var deserializeForEditor; true; pool = cc.deserialize.Details.pool; var tdInfo = pool.get(); var asset; try { asset = cc.deserialize(json, tdInfo, { classFinder: classFinder, customEnv: options }); } catch (e) { pool.put(tdInfo); throw e; } false; var uuidList = tdInfo.uuidList; var objList = tdInfo.uuidObjList; var propList = tdInfo.uuidPropList; var depends = []; for (var i = 0; i < uuidList.length; i++) { var dependUuid = uuidList[i]; depends[i] = { uuid: helper.decodeUuid(dependUuid), owner: objList[i], prop: propList[i] }; } asset.__depends__ = depends; asset._native && (asset.__nativeDepend__ = true); pool.put(tdInfo); return asset; } module.exports = deserialize; }), { "../platform/deserialize": 145, "../platform/deserialize-compiled": 144, "../platform/deserialize-editor": void 0, "./helper": 44 } ], 36: [ (function(require, module, exports) { "use strict"; var __audioSupport = cc.sys.__audioSupport; var _require = require("./utilities"), parseParameters = _require.parseParameters; function downloadDomAudio(url, options, onComplete) { var _parseParameters = parseParameters(options, void 0, onComplete), options = _parseParameters.options, onComplete = _parseParameters.onComplete; var dom = document.createElement("audio"); dom.src = url; var clearEvent = function clearEvent() { clearTimeout(timer); dom.removeEventListener("canplaythrough", success, false); dom.removeEventListener("error", failure, false); __audioSupport.USE_LOADER_EVENT && dom.removeEventListener(__audioSupport.USE_LOADER_EVENT, success, false); }; var timer = setTimeout((function() { 0 === dom.readyState ? failure() : success(); }), 8e3); var success = function success() { clearEvent(); onComplete && onComplete(null, dom); }; var failure = function failure() { clearEvent(); var message = "load audio failure - " + url; cc.log(message); onComplete && onComplete(new Error(message)); }; dom.addEventListener("canplaythrough", success, false); dom.addEventListener("error", failure, false); __audioSupport.USE_LOADER_EVENT && dom.addEventListener(__audioSupport.USE_LOADER_EVENT, success, false); return dom; } module.exports = downloadDomAudio; }), { "./utilities": 56 } ], 37: [ (function(require, module, exports) { "use strict"; var _require = require("./utilities"), parseParameters = _require.parseParameters; function downloadDomImage(url, options, onComplete) { var _parseParameters = parseParameters(options, void 0, onComplete), options = _parseParameters.options, onComplete = _parseParameters.onComplete; var img = new Image(); "file:" !== window.location.protocol && (img.crossOrigin = "anonymous"); function loadCallback() { img.removeEventListener("load", loadCallback); img.removeEventListener("error", errorCallback); onComplete && onComplete(null, img); } function errorCallback() { img.removeEventListener("load", loadCallback); img.removeEventListener("error", errorCallback); onComplete && onComplete(new Error(cc.debug.getError(4930, url))); } img.addEventListener("load", loadCallback); img.addEventListener("error", errorCallback); img.src = url; return img; } module.exports = downloadDomImage; }), { "./utilities": 56 } ], 38: [ (function(require, module, exports) { "use strict"; var _require = require("./utilities"), parseParameters = _require.parseParameters; function downloadFile(url, options, onProgress, onComplete) { var _parseParameters = parseParameters(options, onProgress, onComplete), options = _parseParameters.options, onProgress = _parseParameters.onProgress, onComplete = _parseParameters.onComplete; var xhr = new XMLHttpRequest(), errInfo = "download failed: " + url + ", status: "; xhr.open("GET", url, true); void 0 !== options.responseType && (xhr.responseType = options.responseType); void 0 !== options.withCredentials && (xhr.withCredentials = options.withCredentials); void 0 !== options.mimeType && xhr.overrideMimeType && xhr.overrideMimeType(options.mimeType); void 0 !== options.timeout && (xhr.timeout = options.timeout); if (options.header) for (var header in options.header) xhr.setRequestHeader(header, options.header[header]); xhr.onload = function() { 200 === xhr.status || 0 === xhr.status ? onComplete && onComplete(null, xhr.response) : onComplete && onComplete(new Error(errInfo + xhr.status + "(no response)")); }; onProgress && (xhr.onprogress = function(e) { e.lengthComputable && onProgress(e.loaded, e.total); }); xhr.onerror = function() { onComplete && onComplete(new Error(errInfo + xhr.status + "(error)")); }; xhr.ontimeout = function() { onComplete && onComplete(new Error(errInfo + xhr.status + "(time out)")); }; xhr.onabort = function() { onComplete && onComplete(new Error(errInfo + xhr.status + "(abort)")); }; xhr.send(null); return xhr; } module.exports = downloadFile; }), { "./utilities": 56 } ], 39: [ (function(require, module, exports) { "use strict"; var _require = require("./utilities"), parseParameters = _require.parseParameters; var downloaded = {}; function downloadScript(url, options, onComplete) { var _parseParameters = parseParameters(options, void 0, onComplete), options = _parseParameters.options, onComplete = _parseParameters.onComplete; if (downloaded[url]) return onComplete && onComplete(null); var d = document, s = document.createElement("script"); "file:" !== window.location.protocol && (s.crossOrigin = "anonymous"); s.async = options.async; s.src = url; function loadHandler() { s.parentNode.removeChild(s); s.removeEventListener("load", loadHandler, false); s.removeEventListener("error", errorHandler, false); downloaded[url] = true; onComplete && onComplete(null); } function errorHandler() { s.parentNode.removeChild(s); s.removeEventListener("load", loadHandler, false); s.removeEventListener("error", errorHandler, false); onComplete && onComplete(new Error(cc.debug.getError(4928, url))); } s.addEventListener("load", loadHandler, false); s.addEventListener("error", errorHandler, false); d.body.appendChild(s); } module.exports = downloadScript; }), { "./utilities": 56 } ], 40: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); var debug = require("../CCDebug"); var _require = require("./font-loader"), loadFont = _require.loadFont; var callInNextTick = require("../platform/utils").callInNextTick; var downloadDomImage = require("./download-dom-image"); var downloadDomAudio = require("./download-dom-audio"); var downloadFile = require("./download-file"); var downloadScript = require("./download-script.js"); var Cache = require("./cache"); var _require2 = require("./shared"), files = _require2.files; var _require3 = require("../platform/CCSys"), __audioSupport = _require3.__audioSupport, capabilities = _require3.capabilities; var _require4 = require("./utilities"), urlAppendTimestamp = _require4.urlAppendTimestamp, retry = _require4.retry; var REGEX = /^(?:\w+:\/\/|\.+\/).+/; var formatSupport = __audioSupport.format || []; var unsupported = function unsupported(url, options, onComplete) { onComplete(new Error(debug.getError(4927))); }; var downloadAudio = function downloadAudio(url, options, onComplete) { options.audioLoadMode !== cc.AudioClip.LoadMode.DOM_AUDIO ? downloadArrayBuffer(url, options, onComplete) : downloadDomAudio(url, options, onComplete); }; var downloadAudio = 0 === formatSupport.length ? unsupported : __audioSupport.WEB_AUDIO ? downloadAudio : downloadDomAudio; var downloadImage = function downloadImage(url, options, onComplete) { var func = capabilities.imageBitmap && cc.macro.ALLOW_IMAGE_BITMAP ? downloadBlob : downloadDomImage; func.apply(this, arguments); }; var downloadBlob = function downloadBlob(url, options, onComplete) { options.responseType = "blob"; downloadFile(url, options, options.onFileProgress, onComplete); }; var downloadJson = function downloadJson(url, options, onComplete) { options.responseType = "json"; downloadFile(url, options, options.onFileProgress, (function(err, data) { if (!err && "string" === typeof data) try { data = JSON.parse(data); } catch (e) { err = e; } onComplete && onComplete(err, data); })); }; var downloadArrayBuffer = function downloadArrayBuffer(url, options, onComplete) { options.responseType = "arraybuffer"; downloadFile(url, options, options.onFileProgress, onComplete); }; var downloadText = function downloadText(url, options, onComplete) { options.responseType = "text"; downloadFile(url, options, options.onFileProgress, onComplete); }; var downloadVideo = function downloadVideo(url, options, onComplete) { onComplete(null, url); }; var downloadBundle = function downloadBundle(nameOrUrl, options, onComplete) { var bundleName = cc.path.basename(nameOrUrl); var url = nameOrUrl; REGEX.test(url) || (url = "assets/" + bundleName); var version = options.version || downloader.bundleVers[bundleName]; var count = 0; var config = url + "/config." + (version ? version + "." : "") + "json"; var out = null, error = null; downloadJson(config, options, (function(err, response) { err && (error = err); out = response; out && (out.base = url + "/"); count++; 2 === count && onComplete(error, out); })); var js = url + "/index." + (version ? version + "." : "") + "js"; downloadScript(js, options, (function(err) { err && (error = err); count++; 2 === count && onComplete(error, out); })); }; var _downloading = new Cache(); var _queue = []; var _queueDirty = false; var _totalNum = 0; var _totalNumThisPeriod = 0; var _lastDate = -1; var _checkNextPeriod = false; var updateTime = function updateTime() { var now = Date.now(); var interval = cc.director._deltaTime > downloader._maxInterval ? downloader._maxInterval : cc.director._deltaTime; if (now - _lastDate > 1e3 * interval) { _totalNumThisPeriod = 0; _lastDate = now; } }; var handleQueue = function handleQueue(maxConcurrency, maxRequestsPerFrame) { _checkNextPeriod = false; updateTime(); while (_queue.length > 0 && _totalNum < maxConcurrency && _totalNumThisPeriod < maxRequestsPerFrame) { if (_queueDirty) { _queue.sort((function(a, b) { return a.priority - b.priority; })); _queueDirty = false; } var nextOne = _queue.pop(); if (!nextOne) break; _totalNum++; _totalNumThisPeriod++; nextOne.invoke(); } if (_queue.length > 0 && _totalNum < maxConcurrency) { callInNextTick(handleQueue, maxConcurrency, maxRequestsPerFrame); _checkNextPeriod = true; } }; var downloader = { _remoteServerAddress: "", _maxInterval: 1 / 30, get remoteServerAddress() { return this._remoteServerAddress; }, maxConcurrency: 6, maxRequestsPerFrame: 6, maxRetryCount: 3, appendTimeStamp: false, limited: true, retryInterval: 2e3, bundleVers: null, downloadDomImage: downloadDomImage, downloadDomAudio: downloadDomAudio, downloadFile: downloadFile, downloadScript: downloadScript, init: function init(bundleVers, remoteServerAddress) { _downloading.clear(); _queue.length = 0; this._remoteServerAddress = remoteServerAddress || ""; this.bundleVers = bundleVers || Object.create(null); }, register: function register(type, handler) { "object" === typeof type ? js.mixin(downloaders, type) : downloaders[type] = handler; }, download: function download(id, url, type, options, onComplete) { var func = downloaders[type] || downloaders["default"]; var self = this; var file, downloadCallbacks; if (file = files.get(id)) onComplete(null, file); else if (downloadCallbacks = _downloading.get(id)) { downloadCallbacks.push(onComplete); for (var i = 0, l = _queue.length; i < l; i++) { var item = _queue[i]; if (item.id === id) { var priority = options.priority || 0; if (item.priority < priority) { item.priority = priority; _queueDirty = true; } return; } } } else { var process = function process(index, callback) { 0 === index && _downloading.add(id, [ onComplete ]); if (!self.limited) return func(urlAppendTimestamp(url), options, callback); updateTime(); function invoke() { func(urlAppendTimestamp(url), options, (function() { _totalNum--; if (!_checkNextPeriod && _queue.length > 0) { callInNextTick(handleQueue, maxConcurrency, maxRequestsPerFrame); _checkNextPeriod = true; } callback.apply(this, arguments); })); } if (_totalNum < maxConcurrency && _totalNumThisPeriod < maxRequestsPerFrame) { invoke(); _totalNum++; _totalNumThisPeriod++; } else { _queue.push({ id: id, priority: options.priority || 0, invoke: invoke }); _queueDirty = true; if (!_checkNextPeriod && _totalNum < maxConcurrency) { callInNextTick(handleQueue, maxConcurrency, maxRequestsPerFrame); _checkNextPeriod = true; } } }; var finale = function finale(err, result) { err || files.add(id, result); var callbacks = _downloading.remove(id); for (var _i = 0, _l = callbacks.length; _i < _l; _i++) callbacks[_i](err, result); }; var maxRetryCount = "undefined" !== typeof options.maxRetryCount ? options.maxRetryCount : this.maxRetryCount; var maxConcurrency = "undefined" !== typeof options.maxConcurrency ? options.maxConcurrency : this.maxConcurrency; var maxRequestsPerFrame = "undefined" !== typeof options.maxRequestsPerFrame ? options.maxRequestsPerFrame : this.maxRequestsPerFrame; retry(process, maxRetryCount, this.retryInterval, finale); } } }; var downloaders = { ".png": downloadImage, ".jpg": downloadImage, ".bmp": downloadImage, ".jpeg": downloadImage, ".gif": downloadImage, ".ico": downloadImage, ".tiff": downloadImage, ".webp": downloadImage, ".image": downloadImage, ".pvr": downloadArrayBuffer, ".pkm": downloadArrayBuffer, ".mp3": downloadAudio, ".ogg": downloadAudio, ".wav": downloadAudio, ".m4a": downloadAudio, ".txt": downloadText, ".xml": downloadText, ".vsh": downloadText, ".fsh": downloadText, ".atlas": downloadText, ".tmx": downloadText, ".tsx": downloadText, ".json": downloadJson, ".ExportJson": downloadJson, ".plist": downloadText, ".fnt": downloadText, ".font": loadFont, ".eot": loadFont, ".ttf": loadFont, ".woff": loadFont, ".svg": loadFont, ".ttc": loadFont, ".mp4": downloadVideo, ".avi": downloadVideo, ".mov": downloadVideo, ".mpg": downloadVideo, ".mpeg": downloadVideo, ".rm": downloadVideo, ".rmvb": downloadVideo, ".binary": downloadArrayBuffer, ".bin": downloadArrayBuffer, ".dbbin": downloadArrayBuffer, ".skel": downloadArrayBuffer, ".js": downloadScript, bundle: downloadBundle, default: downloadText }; downloader._downloaders = downloaders; module.exports = downloader; }), { "../CCDebug": 21, "../platform/CCSys": 138, "../platform/js": 150, "../platform/utils": 153, "./cache": 31, "./download-dom-audio": 36, "./download-dom-image": 37, "./download-file": 38, "./download-script.js": 39, "./font-loader": 43, "./shared": 53, "./utilities": 56 } ], 41: [ (function(require, module, exports) { "use strict"; var Bundle = require("./bundle"); var Cache = require("./cache"); var _require = require("./shared"), assets = _require.assets, bundles = _require.bundles; var _creating = new Cache(); function createTexture(id, data, options, onComplete) { var out = null, err = null; try { out = new cc.Texture2D(); out._nativeUrl = id; out._nativeAsset = data; } catch (e) { err = e; } onComplete && onComplete(err, out); } function createAudioClip(id, data, options, onComplete) { var out = new cc.AudioClip(); out._nativeUrl = id; out._nativeAsset = data; out.duration = data.duration; onComplete && onComplete(null, out); } function createVideoClip(id, data, options, onComplete) { var out = new cc.VideoClip(); out._nativeUrl = id; out._nativeAsset = data; onComplete && onComplete(null, out); } function createJsonAsset(id, data, options, onComplete) { var out = new cc.JsonAsset(); out.json = data; onComplete && onComplete(null, out); } function createTextAsset(id, data, options, onComplete) { var out = new cc.TextAsset(); out.text = data; onComplete && onComplete(null, out); } function createFont(id, data, options, onComplete) { var out = new cc.TTFFont(); out._nativeUrl = id; out._nativeAsset = data; onComplete && onComplete(null, out); } function createBufferAsset(id, data, options, onComplete) { var out = new cc.BufferAsset(); out._nativeUrl = id; out._nativeAsset = data; onComplete && onComplete(null, out); } function createAsset(id, data, options, onComplete) { var out = new cc.Asset(); out._nativeUrl = id; out._nativeAsset = data; onComplete && onComplete(null, out); } function createBundle(id, data, options, onComplete) { var bundle = bundles.get(data.name); if (!bundle) { bundle = new Bundle(); data.base = data.base || id + "/"; bundle.init(data); } onComplete && onComplete(null, bundle); } var factory = { register: function register(type, handler) { "object" === typeof type ? cc.js.mixin(producers, type) : producers[type] = handler; }, create: function create(id, data, type, options, onComplete) { var func = producers[type] || producers["default"]; var asset, creating; if (asset = assets.get(id)) onComplete(null, asset); else if (creating = _creating.get(id)) creating.push(onComplete); else { _creating.add(id, [ onComplete ]); func(id, data, options, (function(err, data) { if (!err && data instanceof cc.Asset) { data._uuid = id; assets.add(id, data); } var callbacks = _creating.remove(id); for (var i = 0, l = callbacks.length; i < l; i++) callbacks[i](err, data); })); } } }; var producers = { ".png": createTexture, ".jpg": createTexture, ".bmp": createTexture, ".jpeg": createTexture, ".gif": createTexture, ".ico": createTexture, ".tiff": createTexture, ".webp": createTexture, ".image": createTexture, ".pvr": createTexture, ".pkm": createTexture, ".mp3": createAudioClip, ".ogg": createAudioClip, ".wav": createAudioClip, ".m4a": createAudioClip, ".mp4": createVideoClip, ".avi": createVideoClip, ".mov": createVideoClip, ".mpg": createVideoClip, ".mpeg": createVideoClip, ".rm": createVideoClip, ".rmvb": createVideoClip, ".txt": createTextAsset, ".xml": createTextAsset, ".vsh": createTextAsset, ".fsh": createTextAsset, ".atlas": createTextAsset, ".tmx": createTextAsset, ".tsx": createTextAsset, ".fnt": createTextAsset, ".json": createJsonAsset, ".ExportJson": createJsonAsset, ".font": createFont, ".eot": createFont, ".ttf": createFont, ".woff": createFont, ".svg": createFont, ".ttc": createFont, ".binary": createBufferAsset, ".bin": createBufferAsset, ".dbbin": createBufferAsset, ".skel": createBufferAsset, bundle: createBundle, default: createAsset }; module.exports = factory; }), { "./bundle": 30, "./cache": 31, "./shared": 53 } ], 42: [ (function(require, module, exports) { "use strict"; var packManager = require("./pack-manager"); var Task = require("./task"); var _require = require("./utilities"), getDepends = _require.getDepends, clear = _require.clear, forEach = _require.forEach; var _require2 = require("./shared"), assets = _require2.assets, fetchPipeline = _require2.fetchPipeline; function fetch(task, done) { var firstTask = false; if (!task.progress) { task.progress = { finish: 0, total: task.input.length, canInvoke: true }; firstTask = true; } var options = task.options, depends = [], progress = task.progress, total = progress.total; options.__exclude__ = options.__exclude__ || Object.create(null); task.output = []; forEach(task.input, (function(item, cb) { if (!item.isNative && assets.has(item.uuid)) { var asset = assets.get(item.uuid); asset.addRef(); handle(item, task, asset, null, asset.__asyncLoadAssets__, depends, total, done); return cb(); } packManager.load(item, task.options, (function(err, data) { if (err) { if (!task.isFinish) if (!cc.assetManager.force || firstTask) { cc.error(err.message, err.stack); progress.canInvoke = false; done(err); } else handle(item, task, null, null, false, depends, total, done); } else task.isFinish || handle(item, task, null, data, !item.isNative, depends, total, done); cb(); })); }), (function() { if (task.isFinish) { clear(task, true); return task.dispatch("error"); } if (depends.length > 0) { var subTask = Task.create({ name: task.name + " dependencies", input: depends, progress: progress, options: options, onProgress: task.onProgress, onError: Task.prototype.recycle, onComplete: function onComplete(err) { if (!err) { task.output.push.apply(task.output, this.output); subTask.recycle(); } firstTask && decreaseRef(task); done(err); } }); fetchPipeline.async(subTask); return; } firstTask && decreaseRef(task); done(); })); } function decreaseRef(task) { var output = task.output; for (var i = 0, l = output.length; i < l; i++) output[i].content && output[i].content.decRef(false); } function handle(item, task, content, file, loadDepends, depends, last, done) { var exclude = task.options.__exclude__; var progress = task.progress; item.content = content; item.file = file; task.output.push(item); if (loadDepends) { exclude[item.uuid] = true; getDepends(item.uuid, file || content, exclude, depends, true, false, item.config); progress.total = last + depends.length; } progress.canInvoke && task.dispatch("progress", ++progress.finish, progress.total, item); } module.exports = fetch; }), { "./pack-manager": 47, "./shared": 53, "./task": 54, "./utilities": 56 } ], 43: [ (function(require, module, exports) { "use strict"; var textUtils = require("../utils/text-utils"); var _canvasContext = null; var _testString = "BES bswy:->@123\u4e01\u3041\u1101"; var _fontFaces = Object.create(null); var _intervalId = -1; var _loadingFonts = []; var _timeout = 3e3; var useNativeCheck = (function() { var nativeCheck = void 0; return function() { if (void 0 === nativeCheck) if (!window.FontFace) nativeCheck = false; else { var match = /Gecko.*Firefox\/(\d+)/.exec(window.navigator.userAgent); var safari10Match = /OS X.*Version\/10\..*Safari/.exec(window.navigator.userAgent) && /Apple/.exec(window.navigator.vendor); nativeCheck = match ? parseInt(match[1], 10) > 42 : !safari10Match; } return nativeCheck; }; })(); function _checkFontLoaded() { var allFontsLoaded = true; var now = Date.now(); for (var i = _loadingFonts.length - 1; i >= 0; i--) { var fontLoadHandle = _loadingFonts[i]; var fontFamily = fontLoadHandle.fontFamilyName; if (now - fontLoadHandle.startTime > _timeout) { cc.warnID(4933, fontFamily); fontLoadHandle.onComplete(null, fontFamily); _loadingFonts.splice(i, 1); continue; } var oldWidth = fontLoadHandle.refWidth; var fontDesc = "40px " + fontFamily; _canvasContext.font = fontDesc; var newWidth = textUtils.safeMeasureText(_canvasContext, _testString, fontDesc); if (oldWidth !== newWidth) { _loadingFonts.splice(i, 1); fontLoadHandle.onComplete(null, fontFamily); } else allFontsLoaded = false; } if (allFontsLoaded) { clearInterval(_intervalId); _intervalId = -1; } } function nativeCheckFontLoaded(start, font, callback) { var loader = new Promise(function(resolve, reject) { var check = function check() { var now = Date.now(); now - start >= _timeout ? reject() : document.fonts.load("40px " + font).then((function(fonts) { fonts.length >= 1 ? resolve() : setTimeout(check, 100); }), (function() { reject(); })); }; check(); }); var timeoutId = null, timer = new Promise(function(resolve, reject) { timeoutId = setTimeout(reject, _timeout); }); Promise.race([ timer, loader ]).then((function() { if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; } callback(null, font); }), (function() { cc.warnID(4933, font); callback(null, font); })); } var fontLoader = { loadFont: function loadFont(url, options, onComplete) { var fontFamilyName = fontLoader._getFontFamily(url); if (_fontFaces[fontFamilyName]) return onComplete(null, fontFamilyName); if (!_canvasContext) { var labelCanvas = document.createElement("canvas"); labelCanvas.width = 100; labelCanvas.height = 100; _canvasContext = labelCanvas.getContext("2d"); } var fontDesc = "40px " + fontFamilyName; _canvasContext.font = fontDesc; var refWidth = textUtils.safeMeasureText(_canvasContext, _testString, fontDesc); var fontStyle = document.createElement("style"); fontStyle.type = "text/css"; var fontStr = ""; isNaN(fontFamilyName - 0) ? fontStr += "@font-face { font-family:" + fontFamilyName + "; src:" : fontStr += "@font-face { font-family:'" + fontFamilyName + "'; src:"; fontStr += "url('" + url + "');"; fontStyle.textContent = fontStr + "}"; document.body.appendChild(fontStyle); var preloadDiv = document.createElement("div"); var divStyle = preloadDiv.style; divStyle.fontFamily = fontFamilyName; preloadDiv.innerHTML = "."; divStyle.position = "absolute"; divStyle.left = "-100px"; divStyle.top = "-100px"; document.body.appendChild(preloadDiv); if (useNativeCheck()) nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete); else { var fontLoadHandle = { fontFamilyName: fontFamilyName, refWidth: refWidth, onComplete: onComplete, startTime: Date.now() }; _loadingFonts.push(fontLoadHandle); -1 === _intervalId && (_intervalId = setInterval(_checkFontLoaded, 100)); } _fontFaces[fontFamilyName] = fontStyle; }, _getFontFamily: function _getFontFamily(fontHandle) { var ttfIndex = fontHandle.lastIndexOf(".ttf"); if (-1 === ttfIndex) return fontHandle; var slashPos = fontHandle.lastIndexOf("/"); var fontFamilyName; fontFamilyName = -1 === slashPos ? fontHandle.substring(0, ttfIndex) + "_LABEL" : fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL"; -1 !== fontFamilyName.indexOf(" ") && (fontFamilyName = '"' + fontFamilyName + '"'); return fontFamilyName; } }; module.exports = fontLoader; }), { "../utils/text-utils": 224 } ], 44: [ (function(require, module, exports) { "use strict"; var _require = require("./shared"), bundles = _require.bundles; var helper = { decodeUuid: require("../utils/decode-uuid"), getUuidFromURL: (function() { var _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-]{8,})/; return function(url) { var matches = url.match(_uuidRegex); if (matches) return matches[1]; return ""; }; })(), getUrlWithUuid: function getUrlWithUuid(uuid, options) { options = options || Object.create(null); options.__isNative__ = options.isNative; options.ext = options.nativeExt; var bundle = bundles.find((function(bundle) { return bundle.getAssetInfo(uuid); })); bundle && (options.bundle = bundle.name); return cc.assetManager._transform(uuid, options); }, isScene: function isScene(asset) { return asset && (asset.constructor === cc.SceneAsset || asset instanceof cc.Scene); }, normalize: function normalize(url) { url && (46 === url.charCodeAt(0) && 47 === url.charCodeAt(1) ? url = url.slice(2) : 47 === url.charCodeAt(0) && (url = url.slice(1))); return url; } }; module.exports = helper; }), { "../utils/decode-uuid": 212, "./shared": 53 } ], 45: [ (function(require, module, exports) { "use strict"; require("./deprecated"); require("./CCAssetManager"); }), { "./CCAssetManager": 28, "./deprecated": 34 } ], 46: [ (function(require, module, exports) { "use strict"; var packManager = require("./pack-manager"); var Pipeline = require("./pipeline"); var parser = require("./parser"); var _require = require("./utilities"), getDepends = _require.getDepends, cache = _require.cache, gatherAsset = _require.gatherAsset, setProperties = _require.setProperties, forEach = _require.forEach, clear = _require.clear, checkCircleReference = _require.checkCircleReference; var _require2 = require("./shared"), assets = _require2.assets, files = _require2.files, parsed = _require2.parsed, pipeline = _require2.pipeline; var Task = require("./task"); function load(task, done) { var firstTask = false; if (!task.progress) { task.progress = { finish: 0, total: task.input.length, canInvoke: true }; firstTask = true; } var options = task.options, progress = task.progress; options.__exclude__ = options.__exclude__ || Object.create(null); task.output = []; forEach(task.input, (function(item, cb) { var subTask = Task.create({ input: item, onProgress: task.onProgress, options: options, progress: progress, onComplete: function onComplete(err, item) { if (err && !task.isFinish) if (!cc.assetManager.force || firstTask) { true; cc.error(err.message, err.stack); progress.canInvoke = false; done(err); } else progress.canInvoke && task.dispatch("progress", ++progress.finish, progress.total, item); task.output.push(item); subTask.recycle(); cb(); } }); loadOneAssetPipeline.async(subTask); }), (function() { options.__exclude__ = null; if (task.isFinish) { clear(task, true); return task.dispatch("error"); } gatherAsset(task); clear(task, true); done(); })); } var loadOneAssetPipeline = new Pipeline("loadOneAsset", [ function fetch(task, done) { var item = task.output = task.input; var options = item.options, isNative = item.isNative, uuid = item.uuid, file = item.file; var reload = options.reload; if (file || !reload && !isNative && assets.has(uuid)) return done(); packManager.load(item, task.options, (function(err, data) { item.file = data; done(err); })); }, function parse(task, done) { var item = task.output = task.input, progress = task.progress, exclude = task.options.__exclude__; var id = item.id, file = item.file, options = item.options; if (item.isNative) parser.parse(id, file, item.ext, options, (function(err, asset) { if (err) return done(err); item.content = asset; progress.canInvoke && task.dispatch("progress", ++progress.finish, progress.total, item); files.remove(id); parsed.remove(id); done(); })); else { var uuid = item.uuid; if (uuid in exclude) { var _exclude$uuid = exclude[uuid], finish = _exclude$uuid.finish, content = _exclude$uuid.content, err = _exclude$uuid.err, callbacks = _exclude$uuid.callbacks; progress.canInvoke && task.dispatch("progress", ++progress.finish, progress.total, item); if (finish || checkCircleReference(uuid, uuid, exclude)) { content && content.addRef && content.addRef(); item.content = content; done(err); } else callbacks.push({ done: done, item: item }); } else if (!options.reload && assets.has(uuid)) { var asset = assets.get(uuid); if (options.__asyncLoadAssets__ || !asset.__asyncLoadAssets__) { item.content = asset.addRef(); progress.canInvoke && task.dispatch("progress", ++progress.finish, progress.total, item); done(); } else loadDepends(task, asset, done, false); } else parser.parse(id, file, "import", options, (function(err, asset) { if (err) return done(err); asset._uuid = uuid; loadDepends(task, asset, done, true); })); } } ]); function loadDepends(task, asset, done, init) { var item = task.input, progress = task.progress; var uuid = item.uuid, id = item.id, options = item.options, config = item.config; var __asyncLoadAssets__ = options.__asyncLoadAssets__, cacheAsset = options.cacheAsset; var depends = []; asset.addRef && asset.addRef(); getDepends(uuid, asset, Object.create(null), depends, false, __asyncLoadAssets__, config); progress.canInvoke && task.dispatch("progress", ++progress.finish, progress.total += depends.length, item); var repeatItem = task.options.__exclude__[uuid] = { content: asset, finish: false, callbacks: [ { done: done, item: item } ] }; var subTask = Task.create({ input: depends, options: task.options, onProgress: task.onProgress, onError: Task.prototype.recycle, progress: progress, onComplete: function onComplete(err) { asset.decRef && asset.decRef(false); asset.__asyncLoadAssets__ = __asyncLoadAssets__; repeatItem.finish = true; repeatItem.err = err; if (!err) { var assets = Array.isArray(subTask.output) ? subTask.output : [ subTask.output ]; var map = Object.create(null); for (var _i = 0, _l = assets.length; _i < _l; _i++) { var dependAsset = assets[_i]; dependAsset && (map[dependAsset instanceof cc.Asset ? dependAsset._uuid + "@import" : uuid + "@native"] = dependAsset); } if (init) { var missingAsset = setProperties(uuid, asset, map); if (!missingAsset && !asset.__onLoadInvoked__) try { asset.onLoad && asset.onLoad(); asset.__onLoadInvoked__ = true; } catch (e) { cc.error(e.message, e.stack); } files.remove(id); parsed.remove(id); cache(uuid, asset, void 0 !== cacheAsset ? cacheAsset : cc.assetManager.cacheAsset); } else if (asset.__nativeDepend__ && !asset._nativeAsset) { var missingAsset = setProperties(uuid, asset, map); if (!missingAsset && !asset.__onLoadInvoked__) try { asset.onLoad && asset.onLoad(); asset.__onLoadInvoked__ = true; } catch (e) { cc.error(e.message, e.stack); } } subTask.recycle(); } var callbacks = repeatItem.callbacks; for (var i = 0, l = callbacks.length; i < l; i++) { var cb = callbacks[i]; asset.addRef && asset.addRef(); cb.item.content = asset; cb.done(err); } callbacks.length = 0; } }); pipeline.async(subTask); } module.exports = load; }), { "./pack-manager": 47, "./parser": 48, "./pipeline": 49, "./shared": 53, "./task": 54, "./utilities": 56 } ], 47: [ (function(require, module, exports) { "use strict"; var _deserializeCompiled = require("../platform/deserialize-compiled"); var downloader = require("./downloader"); var Cache = require("./cache"); var js = require("../platform/js"); var _require = require("./shared"), files = _require.files; var _loading = new Cache(); function isLoading(val) { return _loading.has(val.uuid); } var packManager = { unpackJson: function unpackJson(pack, json, options, onComplete) { var out = js.createMap(true), err = null; if (Array.isArray(json)) { json = (0, _deserializeCompiled.unpackJSONs)(json); json.length !== pack.length && cc.errorID(4915); for (var i = 0; i < pack.length; i++) { var key = pack[i] + "@import"; out[key] = json[i]; } } else { var textureType = js._getClassId(cc.Texture2D); if (json.type === textureType) { if (json.data) { var datas = json.data.split("|"); datas.length !== pack.length && cc.errorID(4915); for (var _i = 0; _i < pack.length; _i++) out[pack[_i] + "@import"] = (0, _deserializeCompiled.packCustomObjData)(textureType, datas[_i], true); } } else { err = new Error("unmatched type pack!"); out = null; } } onComplete && onComplete(err, out); }, init: function init() { _loading.clear(); }, register: function register(type, handler) { "object" === typeof type ? js.mixin(unpackers, type) : unpackers[type] = handler; }, unpack: function unpack(pack, data, type, options, onComplete) { if (!data) { onComplete && onComplete(new Error("package data is wrong!")); return; } var unpacker = unpackers[type]; unpacker(pack, data, options, onComplete); }, load: function load(item, options, onComplete) { if (item.isNative || !item.info || !item.info.packs) return downloader.download(item.id, item.url, item.ext, item.options, onComplete); if (files.has(item.id)) return onComplete(null, files.get(item.id)); var packs = item.info.packs; var pack = packs.find(isLoading); if (pack) return _loading.get(pack.uuid).push({ onComplete: onComplete, id: item.id }); pack = packs[0]; _loading.add(pack.uuid, [ { onComplete: onComplete, id: item.id } ]); var url = cc.assetManager._transform(pack.uuid, { ext: pack.ext, bundle: item.config.name }); downloader.download(pack.uuid, url, pack.ext, item.options, (function(err, data) { files.remove(pack.uuid); err && cc.error(err.message, err.stack); packManager.unpack(pack.packs, data, pack.ext, item.options, (function(err, result) { if (err) err.message = "unpack " + url + " failed! details: " + err.message; else for (var id in result) files.add(id, result[id]); var callbacks = _loading.remove(pack.uuid); for (var i = 0, l = callbacks.length; i < l; i++) { var cb = callbacks[i]; if (err) { cb.onComplete(err); continue; } var data = result[cb.id]; data ? cb.onComplete(null, data) : cb.onComplete(new Error("can not retrieve data from package")); } })); })); } }; var unpackers = { ".json": packManager.unpackJson }; module.exports = packManager; }), { "../platform/deserialize-compiled": 144, "../platform/js": 150, "./cache": 31, "./downloader": 40, "./shared": 53 } ], 48: [ (function(require, module, exports) { "use strict"; var plistParser = require("../platform/CCSAXParser").plistParser; var js = require("../platform/js"); var deserialize = require("./deserialize"); var Cache = require("./cache"); var _require = require("./helper"), isScene = _require.isScene; var _require2 = require("./shared"), parsed = _require2.parsed, files = _require2.files; var _require3 = require("../platform/CCSys"), __audioSupport = _require3.__audioSupport, capabilities = _require3.capabilities; var _parsing = new Cache(); var parser = { parseImage: function parseImage(file, options, onComplete) { if (capabilities.imageBitmap && file instanceof Blob) { var imageOptions = {}; imageOptions.imageOrientation = options.__flipY__ ? "flipY" : "none"; imageOptions.premultiplyAlpha = options.__premultiplyAlpha__ ? "premultiply" : "none"; createImageBitmap(file, imageOptions).then((function(result) { result.flipY = !!options.__flipY__; result.premultiplyAlpha = !!options.__premultiplyAlpha__; onComplete && onComplete(null, result); }), (function(err) { onComplete && onComplete(err, null); })); } else onComplete && onComplete(null, file); }, parseAudio: function parseAudio(file, options, onComplete) { file instanceof ArrayBuffer ? __audioSupport.context.decodeAudioData(file, (function(buffer) { onComplete && onComplete(null, buffer); }), (function(e) { onComplete && onComplete(e, null); })) : onComplete && onComplete(null, file); }, parsePVRTex: (function() { var PVR_HEADER_LENGTH = 13; var PVR_MAGIC = 55727696; var PVR_HEADER_MAGIC = 0; var PVR_HEADER_FORMAT = 2; var PVR_HEADER_HEIGHT = 6; var PVR_HEADER_WIDTH = 7; var PVR_HEADER_MIPMAPCOUNT = 11; var PVR_HEADER_METADATA = 12; return function(file, options, onComplete) { var err = null, out = null; try { var buffer = file instanceof ArrayBuffer ? file : file.buffer; var header = new Int32Array(buffer, 0, PVR_HEADER_LENGTH); if (header[PVR_HEADER_MAGIC] != PVR_MAGIC) throw new Error("Invalid magic number in PVR header"); var width = header[PVR_HEADER_WIDTH]; var height = header[PVR_HEADER_HEIGHT]; var dataOffset = header[PVR_HEADER_METADATA] + 52; var pvrtcData = new Uint8Array(buffer, dataOffset); out = { _data: pvrtcData, _compressed: true, width: width, height: height }; } catch (e) { err = e; } onComplete && onComplete(err, out); }; })(), parsePKMTex: (function() { var ETC_PKM_HEADER_SIZE = 16; var ETC_PKM_FORMAT_OFFSET = 6; var ETC_PKM_ENCODED_WIDTH_OFFSET = 8; var ETC_PKM_ENCODED_HEIGHT_OFFSET = 10; var ETC_PKM_WIDTH_OFFSET = 12; var ETC_PKM_HEIGHT_OFFSET = 14; var ETC1_RGB_NO_MIPMAPS = 0; var ETC2_RGB_NO_MIPMAPS = 1; var ETC2_RGBA_NO_MIPMAPS = 3; function readBEUint16(header, offset) { return header[offset] << 8 | header[offset + 1]; } return function(file, options, onComplete) { var err = null, out = null; try { var buffer = file instanceof ArrayBuffer ? file : file.buffer; var header = new Uint8Array(buffer); var format = readBEUint16(header, ETC_PKM_FORMAT_OFFSET); if (format !== ETC1_RGB_NO_MIPMAPS && format !== ETC2_RGB_NO_MIPMAPS && format !== ETC2_RGBA_NO_MIPMAPS) return new Error("Invalid magic number in ETC header"); var width = readBEUint16(header, ETC_PKM_WIDTH_OFFSET); var height = readBEUint16(header, ETC_PKM_HEIGHT_OFFSET); var encodedWidth = readBEUint16(header, ETC_PKM_ENCODED_WIDTH_OFFSET); var encodedHeight = readBEUint16(header, ETC_PKM_ENCODED_HEIGHT_OFFSET); var etcData = new Uint8Array(buffer, ETC_PKM_HEADER_SIZE); out = { _data: etcData, _compressed: true, width: width, height: height }; } catch (e) { err = e; } onComplete && onComplete(err, out); }; })(), parsePlist: function parsePlist(file, options, onComplete) { var err = null; var result = plistParser.parse(file); result || (err = new Error("parse failed")); onComplete && onComplete(err, result); }, parseImport: function parseImport(file, options, onComplete) { if (!file) return onComplete && onComplete(new Error("Json is empty")); var result, err = null; try { result = deserialize(file, options); } catch (e) { err = e; } onComplete && onComplete(err, result); }, init: function init() { _parsing.clear(); }, register: function register(type, handler) { "object" === typeof type ? js.mixin(parsers, type) : parsers[type] = handler; }, parse: function parse(id, file, type, options, onComplete) { var parsedAsset, parsing, parseHandler; if (parsedAsset = parsed.get(id)) onComplete(null, parsedAsset); else if (parsing = _parsing.get(id)) parsing.push(onComplete); else if (parseHandler = parsers[type]) { _parsing.add(id, [ onComplete ]); parseHandler(file, options, (function(err, data) { err ? files.remove(id) : isScene(data) || parsed.add(id, data); var callbacks = _parsing.remove(id); for (var i = 0, l = callbacks.length; i < l; i++) callbacks[i](err, data); })); } else onComplete(null, file); } }; var parsers = { ".png": parser.parseImage, ".jpg": parser.parseImage, ".bmp": parser.parseImage, ".jpeg": parser.parseImage, ".gif": parser.parseImage, ".ico": parser.parseImage, ".tiff": parser.parseImage, ".webp": parser.parseImage, ".image": parser.parseImage, ".pvr": parser.parsePVRTex, ".pkm": parser.parsePKMTex, ".mp3": parser.parseAudio, ".ogg": parser.parseAudio, ".wav": parser.parseAudio, ".m4a": parser.parseAudio, ".plist": parser.parsePlist, import: parser.parseImport }; module.exports = parser; }), { "../platform/CCSAXParser": 136, "../platform/CCSys": 138, "../platform/js": 150, "./cache": 31, "./deserialize": 35, "./helper": 44, "./shared": 53 } ], 49: [ (function(require, module, exports) { "use strict"; var Task = require("./task"); var _pipelineId = 0; function Pipeline(name, funcs) { if (!Array.isArray(funcs)) { cc.warn("funcs must be an array"); return; } this.id = _pipelineId++; this.name = name; this.pipes = []; for (var i = 0, l = funcs.length; i < l; i++) "function" === typeof funcs[i] && this.pipes.push(funcs[i]); } Pipeline.prototype = { constructor: Pipeline, insert: function insert(func, index) { if ("function" !== typeof func || index > this.pipes.length) { cc.warnID(4921); return; } this.pipes.splice(index, 0, func); return this; }, append: function append(func) { if ("function" !== typeof func) return; this.pipes.push(func); return this; }, remove: function remove(index) { if ("number" !== typeof index) return; this.pipes.splice(index, 1); return this; }, sync: function sync(task) { var pipes = this.pipes; if (!(task instanceof Task) || 0 === pipes.length) return; if (null != task.output) { task.input = task.output; task.output = null; } task._isFinish = false; for (var i = 0, l = pipes.length; i < l; ) { var pipe = pipes[i]; var result = pipe(task); if (result) { task._isFinish = true; return result; } i++; if (i !== l) { task.input = task.output; task.output = null; } } task._isFinish = true; return task.output; }, async: function async(task) { var pipes = this.pipes; if (!(task instanceof Task) || 0 === pipes.length) return; if (null != task.output) { task.input = task.output; task.output = null; } task._isFinish = false; this._flow(0, task); }, _flow: function _flow(index, task) { var self = this; var pipe = this.pipes[index]; pipe(task, (function(result) { if (result) { task._isFinish = true; task.onComplete && task.onComplete(result); } else { index++; if (index < self.pipes.length) { task.input = task.output; task.output = null; self._flow(index, task); } else { task._isFinish = true; task.onComplete && task.onComplete(result, task.output); } } })); } }; module.exports = Pipeline; }), { "./task": 54 } ], 50: [ (function(require, module, exports) { "use strict"; var Task = require("./task"); var _require = require("./shared"), transformPipeline = _require.transformPipeline, RequestType = _require.RequestType; function preprocess(task, done) { var options = task.options, subOptions = Object.create(null), leftOptions = Object.create(null); for (var op in options) switch (op) { case RequestType.PATH: case RequestType.UUID: case RequestType.DIR: case RequestType.SCENE: case RequestType.URL: break; case "__requestType__": case "__isNative__": case "ext": case "type": case "__nativeName__": case "audioLoadMode": case "bundle": subOptions[op] = options[op]; break; case "__exclude__": case "__outputAsArray__": leftOptions[op] = options[op]; break; default: subOptions[op] = options[op]; leftOptions[op] = options[op]; } task.options = leftOptions; var subTask = Task.create({ input: task.input, options: subOptions }); var err = null; try { task.output = task.source = transformPipeline.sync(subTask); } catch (e) { err = e; for (var i = 0, l = subTask.output.length; i < l; i++) subTask.output[i].recycle(); } subTask.recycle(); done(err); } module.exports = preprocess; }), { "./shared": 53, "./task": 54 } ], 51: [ (function(require, module, exports) { "use strict"; var dependUtil = require("./depend-util"); var Cache = require("./cache"); require("../assets/CCAsset"); var _require = require("./shared"), assets = _require.assets; var _require2 = require("../platform/utils"), callInNextTick = _require2.callInNextTick; function visitAsset(asset, deps) { if (!asset._uuid) return; deps.push(asset._uuid); } function visitComponent(comp, deps) { var props = Object.getOwnPropertyNames(comp); for (var i = 0; i < props.length; i++) { var propName = props[i]; if ("node" === propName || "__eventTargets" === propName) continue; var value = comp[propName]; if ("object" === typeof value && value) if (Array.isArray(value)) for (var j = 0; j < value.length; j++) { var val = value[j]; val instanceof cc.Asset && visitAsset(val, deps); } else if (value.constructor && value.constructor !== Object) value instanceof cc.Asset && visitAsset(value, deps); else { var keys = Object.getOwnPropertyNames(value); for (var _j = 0; _j < keys.length; _j++) { var _val = value[keys[_j]]; _val instanceof cc.Asset && visitAsset(_val, deps); } } } } var _temp = []; function visitNode(node, deps) { for (var i = 0; i < node._components.length; i++) visitComponent(node._components[i], deps); for (var _i = 0; _i < node._children.length; _i++) visitNode(node._children[_i], deps); } function descendOpRef(asset, refs, exclude, op) { exclude.push(asset._uuid); var depends = dependUtil.getDeps(asset._uuid); for (var i = 0, l = depends.length; i < l; i++) { var dependAsset = assets.get(depends[i]); if (dependAsset) { var uuid = dependAsset._uuid; uuid in refs ? refs[uuid] += op : refs[uuid] = dependAsset.refCount + op; if (exclude.includes(uuid)) continue; descendOpRef(dependAsset, refs, exclude, op); } } } function checkCircularReference(asset) { var refs = Object.create(null); refs[asset._uuid] = asset.refCount; descendOpRef(asset, refs, _temp, -1); _temp.length = 0; if (0 !== refs[asset._uuid]) return refs[asset._uuid]; for (var uuid in refs) 0 !== refs[uuid] && descendOpRef(assets.get(uuid), refs, _temp, 1); _temp.length = 0; return refs[asset._uuid]; } var _persistNodeDeps = new Cache(); var _toDelete = new Cache(); var eventListener = false; function freeAssets() { eventListener = false; _toDelete.forEach((function(asset) { releaseManager._free(asset); })); _toDelete.clear(); } var releaseManager = { init: function init() { _persistNodeDeps.clear(); _toDelete.clear(); }, _addPersistNodeRef: function _addPersistNodeRef(node) { var deps = []; visitNode(node, deps); for (var i = 0, l = deps.length; i < l; i++) { var dependAsset = assets.get(deps[i]); dependAsset && dependAsset.addRef(); } _persistNodeDeps.add(node.uuid, deps); }, _removePersistNodeRef: function _removePersistNodeRef(node) { if (_persistNodeDeps.has(node.uuid)) { var deps = _persistNodeDeps.get(node.uuid); for (var i = 0, l = deps.length; i < l; i++) { var dependAsset = assets.get(deps[i]); dependAsset && dependAsset.decRef(); } _persistNodeDeps.remove(node.uuid); } }, _autoRelease: function _autoRelease(oldScene, newScene, persistNodes) { if (oldScene) { var childs = dependUtil.getDeps(oldScene._id); for (var i = 0, l = childs.length; i < l; i++) { var asset = assets.get(childs[i]); asset && asset.decRef((false, oldScene.autoReleaseAssets)); } var dependencies = dependUtil._depends.get(oldScene._id); if (dependencies && dependencies.persistDeps) { var persistDeps = dependencies.persistDeps; for (var _i2 = 0, _l = persistDeps.length; _i2 < _l; _i2++) { var _asset = assets.get(persistDeps[_i2]); _asset && _asset.decRef((false, oldScene.autoReleaseAssets)); } } oldScene._id !== newScene._id && dependUtil.remove(oldScene._id); } var sceneDeps = dependUtil._depends.get(newScene._id); sceneDeps && (sceneDeps.persistDeps = []); for (var key in persistNodes) { var node = persistNodes[key]; var deps = _persistNodeDeps.get(node.uuid); for (var _i3 = 0, _l2 = deps.length; _i3 < _l2; _i3++) { var dependAsset = assets.get(deps[_i3]); dependAsset && dependAsset.addRef(); } sceneDeps && sceneDeps.persistDeps.push.apply(sceneDeps.persistDeps, deps); } }, _free: function _free(asset, force) { _toDelete.remove(asset._uuid); if (!cc.isValid(asset, true)) return; if (!force && asset.refCount > 0 && checkCircularReference(asset) > 0) return; assets.remove(asset._uuid); var depends = dependUtil.getDeps(asset._uuid); for (var i = 0, l = depends.length; i < l; i++) { var dependAsset = assets.get(depends[i]); if (dependAsset) { dependAsset.decRef(false); releaseManager._free(dependAsset, false); } } asset.destroy(); dependUtil.remove(asset._uuid); }, tryRelease: function tryRelease(asset, force) { if (!(asset instanceof cc.Asset)) return; if (force) releaseManager._free(asset, force); else { _toDelete.add(asset._uuid, asset); if (!eventListener) { eventListener = true; callInNextTick(freeAssets); } } } }; module.exports = releaseManager; }), { "../assets/CCAsset": 57, "../platform/utils": 153, "./cache": 31, "./depend-util": 33, "./shared": 53 } ], 52: [ (function(require, module, exports) { "use strict"; var MAX_DEAD_NUM = 500; var _deadPool = []; function RequestItem() { this._id = ""; this.uuid = ""; this.url = ""; this.ext = ".json"; this.content = null; this.file = null; this.info = null; this.config = null; this.isNative = false; this.options = Object.create(null); } RequestItem.prototype = { constructor: RequestItem, get id() { this._id || (this._id = this.uuid + "@" + (this.isNative ? "native" : "import")); return this._id; }, recycle: function recycle() { if (_deadPool.length === MAX_DEAD_NUM) return; this._id = ""; this.uuid = ""; this.url = ""; this.ext = ".json"; this.content = null; this.file = null; this.info = null; this.config = null; this.isNative = false; this.options = Object.create(null); _deadPool.push(this); } }; RequestItem.create = function() { var out = null; out = 0 !== _deadPool.length ? _deadPool.pop() : new RequestItem(); return out; }; module.exports = RequestItem; }), {} ], 53: [ (function(require, module, exports) { "use strict"; var Cache = require("./cache"); var Pipeline = require("./pipeline"); var assets = new Cache(); var files = new Cache(); var parsed = new Cache(); var bundles = new Cache(); var pipeline = new Pipeline("normal load", []); var fetchPipeline = new Pipeline("fetch", []); var transformPipeline = new Pipeline("transform url", []); var RequestType = { UUID: "uuid", PATH: "path", DIR: "dir", URL: "url", SCENE: "scene" }; var BuiltinBundleName = { RESOURCES: "resources", INTERNAL: "internal", MAIN: "main", START_SCENE: "start-scene" }; module.exports = { assets: assets, files: files, parsed: parsed, pipeline: pipeline, fetchPipeline: fetchPipeline, transformPipeline: transformPipeline, RequestType: RequestType, bundles: bundles, BuiltinBundleName: BuiltinBundleName }; }), { "./cache": 31, "./pipeline": 49 } ], 54: [ (function(require, module, exports) { "use strict"; var _taskId = 0; var MAX_DEAD_NUM = 500; var _deadPool = []; function Task(options) { this.id = _taskId++; this._isFinish = true; this.onComplete = null; this.onProgress = null; this.onError = null; this.source = null; this.output = null; this.input = null; this.progress = null; this.options = null; this.set(options); } Task.prototype = { constructor: Task, set: function set(options) { options = options || Object.create(null); this.onComplete = options.onComplete; this.onProgress = options.onProgress; this.onError = options.onError; this.source = this.input = options.input; this.output = null; this.progress = options.progress; this.options = options.options || Object.create(null); }, dispatch: function dispatch(event, param1, param2, param3, param4) { switch (event) { case "complete": this.onComplete && this.onComplete(param1, param2, param3, param4); break; case "progress": this.onProgress && this.onProgress(param1, param2, param3, param4); break; case "error": this.onError && this.onError(param1, param2, param3, param4); break; default: var str = "on" + event[0].toUpperCase() + event.substr(1); "function" === typeof this[str] && this[str](param1, param2, param3, param4); } }, recycle: function recycle() { if (_deadPool.length === MAX_DEAD_NUM) return; this.onComplete = null; this.onProgress = null; this.onError = null; this.source = this.output = this.input = null; this.progress = null; this.options = null; _deadPool.push(this); }, get isFinish() { return this._isFinish; } }; Task.create = function(options) { var out = null; if (0 !== _deadPool.length) { out = _deadPool.pop(); out.set(options); } else out = new Task(options); return out; }; module.exports = Task; }), {} ], 55: [ (function(require, module, exports) { "use strict"; var _require = require("./helper"), decodeUuid = _require.decodeUuid; var RequestItem = require("./request-item"); var _require2 = require("./shared"), RequestType = _require2.RequestType, bundles = _require2.bundles; function parse(task) { var input = task.input, options = task.options; input = Array.isArray(input) ? input : [ input ]; task.output = []; for (var i = 0; i < input.length; i++) { var item = input[i]; var out = RequestItem.create(); if ("string" === typeof item) { item = Object.create(null); item[options.__requestType__ || RequestType.UUID] = input[i]; } if ("object" === typeof item) { cc.js.addon(item, options); item.preset && cc.js.addon(item, cc.assetManager.presets[item.preset]); for (var key in item) { switch (key) { case RequestType.UUID: var uuid = out.uuid = decodeUuid(item.uuid); if (bundles.has(item.bundle)) { var config = bundles.get(item.bundle)._config; var info = config.getAssetInfo(uuid); if (info && info.redirect) { if (!bundles.has(info.redirect)) throw new Error("Please load bundle " + info.redirect + " first"); config = bundles.get(info.redirect)._config; info = config.getAssetInfo(uuid); } out.config = config; out.info = info; } out.ext = item.ext || ".json"; break; case "__requestType__": case "ext": case "bundle": case "preset": case "type": break; case RequestType.DIR: if (bundles.has(item.bundle)) { var infos = []; bundles.get(item.bundle)._config.getDirWithPath(item.dir, item.type, infos); for (var _i = 0, l = infos.length; _i < l; _i++) { var info = infos[_i]; input.push({ uuid: info.uuid, __isNative__: false, ext: ".json", bundle: item.bundle }); } } out.recycle(); out = null; break; case RequestType.PATH: if (bundles.has(item.bundle)) { var config = bundles.get(item.bundle)._config; var info = config.getInfoWithPath(item.path, item.type); if (info && info.redirect) { if (!bundles.has(info.redirect)) throw new Error("you need to load bundle " + info.redirect + " first"); config = bundles.get(info.redirect)._config; info = config.getAssetInfo(info.uuid); } if (!info) { out.recycle(); throw new Error("Bundle " + item.bundle + " doesn't contain " + item.path); } out.config = config; out.uuid = info.uuid; out.info = info; } out.ext = item.ext || ".json"; break; case RequestType.SCENE: if (bundles.has(item.bundle)) { var config = bundles.get(item.bundle)._config; var info = config.getSceneInfo(item.scene); if (info && info.redirect) { if (!bundles.has(info.redirect)) throw new Error("you need to load bundle " + info.redirect + " first"); config = bundles.get(info.redirect)._config; info = config.getAssetInfo(info.uuid); } if (!info) { out.recycle(); throw new Error("Bundle " + config.name + " doesn't contain scene " + item.scene); } out.config = config; out.uuid = info.uuid; out.info = info; } break; case "__isNative__": out.isNative = item.__isNative__; break; case RequestType.URL: out.url = item.url; out.uuid = item.uuid || item.url; out.ext = item.ext || cc.path.extname(item.url); out.isNative = void 0 === item.__isNative__ || item.__isNative__; break; default: out.options[key] = item[key]; } if (!out) break; } } if (!out) continue; task.output.push(out); if (!out.uuid && !out.url) throw new Error("Can not parse this input:" + JSON.stringify(item)); } return null; } function combine(task) { var input = task.output = task.input; for (var i = 0; i < input.length; i++) { var item = input[i]; if (item.url) continue; var url = "", base = ""; var config = item.config; base = item.isNative ? config && config.nativeBase ? config.base + config.nativeBase : cc.assetManager.generalNativeBase : config && config.importBase ? config.base + config.importBase : cc.assetManager.generalImportBase; var uuid = item.uuid; var ver = ""; item.info && (ver = item.isNative ? item.info.nativeVer ? "." + item.info.nativeVer : "" : item.info.ver ? "." + item.info.ver : ""); url = ".ttf" === item.ext ? base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + "/" + item.options.__nativeName__ : base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + item.ext; item.url = url; } return null; } module.exports = { parse: parse, combine: combine }; }), { "./helper": 44, "./request-item": 52, "./shared": 53 } ], 56: [ (function(require, module, exports) { "use strict"; var dependUtil = require("./depend-util"); var _require = require("./helper"), isScene = _require.isScene, decodeUuid = _require.decodeUuid; var _require2 = require("./shared"), assets = _require2.assets; var _require3 = require("../platform/utils"), callInNextTick = _require3.callInNextTick; var MissingObjectReporter = false; require("../assets/CCAsset"); var utils = { processOptions: function processOptions(options) { false; var uuids = options.uuids; var paths = options.paths; var types = options.types; var bundles = options.deps; var realEntries = options.paths = Object.create(null); if (false === options.debug) { for (var i = 0, l = uuids.length; i < l; i++) uuids[i] = decodeUuid(uuids[i]); for (var id in paths) { var entry = paths[id]; var type = entry[1]; entry[1] = types[type]; } } else { var out = Object.create(null); for (var _i = 0, _l = uuids.length; _i < _l; _i++) { var uuid = uuids[_i]; uuids[_i] = out[uuid] = decodeUuid(uuid); } uuids = out; } for (var _id in paths) { var _entry = paths[_id]; realEntries[uuids[_id]] = _entry; } var scenes = options.scenes; for (var name in scenes) { var _uuid = scenes[name]; scenes[name] = uuids[_uuid]; } var packs = options.packs; for (var packId in packs) { var packedIds = packs[packId]; for (var j = 0; j < packedIds.length; ++j) packedIds[j] = uuids[packedIds[j]]; } var versions = options.versions; if (versions) for (var folder in versions) { var entries = versions[folder]; for (var _i2 = 0; _i2 < entries.length; _i2 += 2) { var _uuid2 = entries[_i2]; entries[_i2] = uuids[_uuid2] || _uuid2; } } var redirect = options.redirect; if (redirect) for (var _i3 = 0; _i3 < redirect.length; _i3 += 2) { redirect[_i3] = uuids[redirect[_i3]]; redirect[_i3 + 1] = bundles[redirect[_i3 + 1]]; } }, clear: function clear(task, clearRef) { for (var i = 0, l = task.input.length; i < l; i++) { var item = task.input[i]; clearRef && !item.isNative && item.content && item.content.decRef && item.content.decRef(false); item.recycle(); } task.input = null; }, urlAppendTimestamp: function urlAppendTimestamp(url) { if (cc.assetManager.downloader.appendTimeStamp && "string" === typeof url) return /\?/.test(url) ? url + "&_t=" + (new Date() - 0) : url + "?_t=" + (new Date() - 0); return url; }, retry: function retry(process, times, wait, onComplete, index) { index = index || 0; process(index, (function(err, result) { index++; !err || index > times ? onComplete && onComplete(err, result) : setTimeout((function() { utils.retry(process, times, wait, onComplete, index); }), wait); })); }, getDepends: function getDepends(uuid, data, exclude, depends, preload, asyncLoadAssets, config) { try { var info = dependUtil.parse(uuid, data); var includeNative = true; data instanceof cc.Asset && (!data.__nativeDepend__ || data._nativeAsset) && (includeNative = false); if (preload) { for (var _i4 = 0, _l2 = info.deps.length; _i4 < _l2; _i4++) { var _dep = info.deps[_i4]; if (!(_dep in exclude)) { exclude[_dep] = true; depends.push({ uuid: _dep, bundle: config && config.name }); } } if (includeNative && info.nativeDep) { config && (info.nativeDep.bundle = config.name); depends.push(Object.assign({}, info.nativeDep)); } } else { asyncLoadAssets = (true, !!data.asyncLoadAssets || asyncLoadAssets && !info.preventDeferredLoadDependents); for (var i = 0, l = info.deps.length; i < l; i++) { var dep = info.deps[i]; if (!(dep in exclude)) { exclude[dep] = true; depends.push({ uuid: dep, __asyncLoadAssets__: asyncLoadAssets, bundle: config && config.name }); } } if (includeNative && !asyncLoadAssets && !info.preventPreloadNativeObject && info.nativeDep) { config && (info.nativeDep.bundle = config.name); depends.push(Object.assign({}, info.nativeDep)); } } } catch (e) { cc.error(e.message, e.stack); } }, cache: function cache(id, asset, cacheAsset) { if (!asset) return; var _isScene = isScene(asset); !_isScene && cacheAsset && assets.add(id, asset); _isScene && false; }, setProperties: function setProperties(uuid, asset, assetsMap) { var missingAsset = false; var depends = asset.__depends__; if (depends) { var missingAssetReporter = null; for (var i = 0, l = depends.length; i < l; i++) { var depend = depends[i]; var dependAsset = assetsMap[depend.uuid + "@import"]; if (dependAsset) depend.owner[depend.prop] = dependAsset.addRef(); else { false; cc.error("The asset " + depend.uuid + " is missing!"); missingAsset = true; } } missingAssetReporter && missingAssetReporter.reportByOwner(); asset.__depends__ = void 0; } if (asset.__nativeDepend__) { if (!asset._nativeAsset) if (assetsMap[uuid + "@native"]) asset._nativeAsset = assetsMap[uuid + "@native"]; else { missingAsset = true; false; } asset.__nativeDepend__ = void 0; } return missingAsset; }, gatherAsset: function gatherAsset(task) { var source = task.source; if (task.options.__outputAsArray__ || 1 !== source.length) { var output = task.output = []; for (var i = 0, l = source.length; i < l; i++) output.push(source[i].content); } else task.output = source[0].content; }, forEach: function forEach(array, process, onComplete) { var count = 0; var errs = []; 0 === array.length && onComplete && onComplete(errs); for (var i = 0, l = array.length; i < l; i++) process(array[i], (function(err) { err && errs.push(err); count++; count === l && onComplete && onComplete(errs); })); }, parseParameters: function parseParameters(options, onProgress, onComplete) { if (void 0 === onComplete) { var isCallback = "function" === typeof options; if (onProgress) { onComplete = onProgress; isCallback || (onProgress = null); } else if (void 0 === onProgress && isCallback) { onComplete = options; options = null; onProgress = null; } if (void 0 !== onProgress && isCallback) { onProgress = options; options = null; } } options = options || Object.create(null); return { options: options, onProgress: onProgress, onComplete: onComplete }; }, parseLoadResArgs: function parseLoadResArgs(type, onProgress, onComplete) { if (void 0 === onComplete) { var isValidType = cc.js.isChildClassOf(type, cc.Asset); if (onProgress) { onComplete = onProgress; isValidType && (onProgress = null); } else if (void 0 === onProgress && !isValidType) { onComplete = type; onProgress = null; type = null; } if (void 0 !== onProgress && !isValidType) { onProgress = type; type = null; } } return { type: type, onProgress: onProgress, onComplete: onComplete }; }, checkCircleReference: function checkCircleReference(owner, uuid, map, checked) { checked || (checked = Object.create(null)); var item = map[uuid]; if (!item || checked[uuid]) return false; checked[uuid] = true; var result = false; var deps = dependUtil.getDeps(uuid); if (deps) for (var i = 0, l = deps.length; i < l; i++) { var dep = deps[i]; if (dep === owner || utils.checkCircleReference(owner, dep, map, checked)) { result = true; break; } } return result; }, asyncify: function asyncify(cb) { return function(p1, p2) { if (!cb) return; var refs = []; Array.isArray(p2) ? p2.forEach((function(x) { return x instanceof cc.Asset && refs.push(x.addRef()); })) : p2 instanceof cc.Asset && refs.push(p2.addRef()); callInNextTick((function() { refs.forEach((function(x) { return x.decRef(false); })); cb(p1, p2); })); }; } }; module.exports = utils; }), { "../assets/CCAsset": 57, "../platform/utils": 153, "./depend-util": 33, "./helper": 44, "./shared": 53 } ], 57: [ (function(require, module, exports) { "use strict"; var CCObject = require("../platform/CCObject"); cc.Asset = cc.Class({ name: "cc.Asset", extends: CCObject, ctor: function ctor() { Object.defineProperty(this, "_uuid", { value: "", writable: true }); this.loaded = true; this._nativeUrl = ""; this._ref = 0; }, properties: { nativeUrl: { get: function get() { if (!this._nativeUrl && this._native) { var name = this._native; if (47 === name.charCodeAt(0)) return name.slice(1); 46 === name.charCodeAt(0) ? this._nativeUrl = cc.assetManager.utils.getUrlWithUuid(this._uuid, { nativeExt: name, isNative: true }) : this._nativeUrl = cc.assetManager.utils.getUrlWithUuid(this._uuid, { __nativeName__: name, nativeExt: cc.path.extname(name), isNative: true }); } return this._nativeUrl; }, visible: false }, refCount: { get: function get() { return this._ref; } }, _native: "", _nativeAsset: { get: function get() { return this._$nativeAsset; }, set: function set(obj) { this._$nativeAsset = obj; } }, _nativeDep: { get: function get() { if (this._native) return { __isNative__: true, uuid: this._uuid, ext: this._native }; } } }, statics: { deserialize: false, preventDeferredLoadDependents: false, preventPreloadNativeObject: false }, toString: function toString() { return this.nativeUrl; }, serialize: false, createNode: null, _setRawAsset: function _setRawAsset(filename, inLibrary) { this._native = false !== inLibrary ? filename || void 0 : "/" + filename; }, addRef: function addRef() { this._ref++; return this; }, decRef: function decRef(autoRelease) { this._ref > 0 && this._ref--; false !== autoRelease && cc.assetManager._releaseManager.tryRelease(this); return this; }, destroy: function destroy() { this.loaded = false; return this._super(); } }); module.exports = cc.Asset; }), { "../platform/CCObject": 135 } ], 58: [ (function(require, module, exports) { "use strict"; var Asset = require("./CCAsset"); var EventTarget = require("../event/event-target"); var LoadMode = cc.Enum({ WEB_AUDIO: 0, DOM_AUDIO: 1 }); var AudioClip = cc.Class({ name: "cc.AudioClip", extends: Asset, mixins: [ EventTarget ], ctor: function ctor() { this._loading = false; this.loaded = false; this._audio = null; }, properties: { duration: 0, loadMode: { default: LoadMode.WEB_AUDIO, type: LoadMode }, _nativeAsset: { get: function get() { return this._audio; }, set: function set(value) { value instanceof cc.AudioClip ? this._audio = value._nativeAsset : this._audio = value; if (this._audio) { this.loaded = true; this.emit("load"); } }, override: true }, _nativeDep: { get: function get() { return { uuid: this._uuid, audioLoadMode: this.loadMode, ext: cc.path.extname(this._native), __isNative__: true }; }, override: true } }, statics: { LoadMode: LoadMode, _loadByUrl: function _loadByUrl(url, callback) { var audioClip = cc.assetManager.assets.get(url); audioClip ? callback(null, audioClip) : cc.assetManager.loadRemote(url, (function(error, data) { if (error) return callback(error); callback(null, data); })); } }, _ensureLoaded: function _ensureLoaded(onComplete) { if (!this.isValid) return; if (this.loaded) return onComplete && onComplete(); onComplete && this.once("load", onComplete); if (!this._loading) { this._loading = true; var self = this; cc.assetManager.postLoadNative(this, (function(err) { self._loading = false; })); } }, destroy: function destroy() { cc.audioEngine.uncache(this); this._super(); } }); cc.AudioClip = AudioClip; module.exports = AudioClip; }), { "../event/event-target": 119, "./CCAsset": 57 } ], 59: [ (function(require, module, exports) { "use strict"; var FontLetterDefinition = function FontLetterDefinition() { this.u = 0; this.v = 0; this.w = 0; this.h = 0; this.offsetX = 0; this.offsetY = 0; this.textureID = 0; this.valid = false; this.xAdvance = 0; }; var FontAtlas = function FontAtlas(texture) { this._letterDefinitions = {}; this._texture = texture; }; FontAtlas.prototype = { constructor: FontAtlas, addLetterDefinitions: function addLetterDefinitions(letter, letterDefinition) { this._letterDefinitions[letter] = letterDefinition; }, cloneLetterDefinition: function cloneLetterDefinition() { var copyLetterDefinitions = {}; for (var key in this._letterDefinitions) { var value = new FontLetterDefinition(); cc.js.mixin(value, this._letterDefinitions[key]); copyLetterDefinitions[key] = value; } return copyLetterDefinitions; }, getTexture: function getTexture() { return this._texture; }, getLetter: function getLetter(key) { return this._letterDefinitions[key]; }, getLetterDefinitionForChar: function getLetterDefinitionForChar(_char) { var key = _char.charCodeAt(0); var hasKey = this._letterDefinitions.hasOwnProperty(key); var letter; letter = hasKey ? this._letterDefinitions[key] : null; return letter; }, clear: function clear() { this._letterDefinitions = {}; } }; var BitmapFont = cc.Class({ name: "cc.BitmapFont", extends: cc.Font, properties: { fntDataStr: { default: "" }, spriteFrame: { default: null, type: cc.SpriteFrame }, fontSize: { default: -1 }, _fntConfig: null, _fontDefDictionary: null }, onLoad: function onLoad() { var spriteFrame = this.spriteFrame; if (!this._fontDefDictionary) { this._fontDefDictionary = new FontAtlas(); spriteFrame && (this._fontDefDictionary._texture = spriteFrame._texture); } var fntConfig = this._fntConfig; if (!fntConfig) return; var fontDict = fntConfig.fontDefDictionary; for (var fontDef in fontDict) { var letter = new FontLetterDefinition(); var rect = fontDict[fontDef].rect; letter.offsetX = fontDict[fontDef].xOffset; letter.offsetY = fontDict[fontDef].yOffset; letter.w = rect.width; letter.h = rect.height; letter.u = rect.x; letter.v = rect.y; letter.textureID = 0; letter.valid = true; letter.xAdvance = fontDict[fontDef].xAdvance; this._fontDefDictionary.addLetterDefinitions(fontDef, letter); } } }); cc.BitmapFont = BitmapFont; cc.BitmapFont.FontLetterDefinition = FontLetterDefinition; cc.BitmapFont.FontAtlas = FontAtlas; module.exports = BitmapFont; }), {} ], 60: [ (function(require, module, exports) { "use strict"; var BufferAsset = cc.Class({ name: "cc.BufferAsset", extends: cc.Asset, ctor: function ctor() { this._buffer = null; }, properties: { _nativeAsset: { get: function get() { return this._buffer; }, set: function set(bin) { this._buffer = bin.buffer || bin; }, override: true }, buffer: function buffer() { return this._buffer; } } }); cc.BufferAsset = module.exports = BufferAsset; }), {} ], 61: [ (function(require, module, exports) { "use strict"; var Font = cc.Class({ name: "cc.Font", extends: cc.Asset }); cc.Font = module.exports = Font; }), {} ], 62: [ (function(require, module, exports) { "use strict"; var JsonAsset = cc.Class({ name: "cc.JsonAsset", extends: cc.Asset, properties: { json: null } }); module.exports = cc.JsonAsset = JsonAsset; }), {} ], 63: [ (function(require, module, exports) { "use strict"; var LabelAtlas = cc.Class({ name: "cc.LabelAtlas", extends: cc.BitmapFont, onLoad: function onLoad() { if (!this.spriteFrame) { cc.warnID(9100, this.name); return; } if (!this._fntConfig) { cc.warnID(9101, this.name); return; } this._super(); } }); cc.LabelAtlas = LabelAtlas; module.exports = LabelAtlas; }), {} ], 64: [ (function(require, module, exports) { "use strict"; var OptimizationPolicy = cc.Enum({ AUTO: 0, SINGLE_INSTANCE: 1, MULTI_INSTANCE: 2 }); var Prefab = cc.Class({ name: "cc.Prefab", extends: cc.Asset, ctor: function ctor() { this._createFunction = null; this._instantiatedTimes = 0; }, properties: { data: null, optimizationPolicy: OptimizationPolicy.AUTO, asyncLoadAssets: false, readonly: { default: false, editorOnly: true } }, statics: { OptimizationPolicy: OptimizationPolicy, OptimizationPolicyThreshold: 3 }, createNode: false, compileCreateFunction: function compileCreateFunction() { var jit = require("../platform/instantiate-jit"); this._createFunction = jit.compile(this.data); }, _doInstantiate: function _doInstantiate(rootToRedirect) { this.data._prefab || cc.warnID(3700); this._createFunction || this.compileCreateFunction(); return this._createFunction(rootToRedirect); }, _instantiate: function _instantiate() { var node, useJit = false; true; useJit = this.optimizationPolicy !== OptimizationPolicy.SINGLE_INSTANCE && (this.optimizationPolicy === OptimizationPolicy.MULTI_INSTANCE || this._instantiatedTimes + 1 >= Prefab.OptimizationPolicyThreshold); if (useJit) { node = this._doInstantiate(); this.data._instantiate(node); } else node = this.data._instantiate(); ++this._instantiatedTimes; var PrefabUtils; false, false; return node; }, destroy: function destroy() { this.data && this.data.destroy(); this._super(); } }); cc.Prefab = module.exports = Prefab; cc.js.obsolete(cc, "cc._Prefab", "Prefab"); }), { "../platform/instantiate-jit": 148 } ], 65: [ (function(require, module, exports) { "use strict"; var _gfx = _interopRequireDefault(require("../../renderer/gfx")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var renderer = require("../renderer"); var Texture2D = require("./CCTexture2D"); var DepthStencilFormat = cc.Enum({ RB_FMT_D24S8: _gfx["default"].RB_FMT_D24S8, RB_FMT_S8: _gfx["default"].RB_FMT_S8, RB_FMT_D16: _gfx["default"].RB_FMT_D16 }); var RenderTexture = cc.Class({ name: "cc.RenderTexture", extends: Texture2D, statics: { DepthStencilFormat: DepthStencilFormat }, ctor: function ctor() { this._framebuffer = null; }, initWithSize: function initWithSize(width, height, depthStencilFormat) { this.width = Math.floor(width || cc.visibleRect.width); this.height = Math.floor(height || cc.visibleRect.height); this._resetUnderlyingMipmaps(); var opts = { colors: [ this._texture ] }; this._depthStencilBuffer && this._depthStencilBuffer.destroy(); var depthStencilBuffer; if (depthStencilFormat) { depthStencilBuffer = new _gfx["default"].RenderBuffer(renderer.device, depthStencilFormat, width, height); depthStencilFormat === _gfx["default"].RB_FMT_D24S8 ? opts.depthStencil = depthStencilBuffer : depthStencilFormat === _gfx["default"].RB_FMT_S8 ? opts.stencil = depthStencilBuffer : depthStencilFormat === _gfx["default"].RB_FMT_D16 && (opts.depth = depthStencilBuffer); } this._depthStencilBuffer = depthStencilBuffer; this._framebuffer && this._framebuffer.destroy(); this._framebuffer = new _gfx["default"].FrameBuffer(renderer.device, width, height, opts); this._packable = false; this.loaded = true; this.emit("load"); }, updateSize: function updateSize(width, height) { this.width = Math.floor(width || cc.visibleRect.width); this.height = Math.floor(height || cc.visibleRect.height); this._resetUnderlyingMipmaps(); var rbo = this._depthStencilBuffer; rbo && rbo.update(this.width, this.height); this._framebuffer._width = width; this._framebuffer._height = height; }, drawTextureAt: function drawTextureAt(texture, x, y) { if (!texture._image || 0 === texture._image.width) return; this._texture.updateSubImage({ x: x, y: y, image: texture._image, width: texture.width, height: texture.height, level: 0, flipY: false, premultiplyAlpha: texture._premultiplyAlpha }); }, readPixels: function readPixels(data, x, y, w, h) { if (!this._framebuffer || !this._texture) return data; x = x || 0; y = y || 0; var width = w || this.width; var height = h || this.height; data = data || new Uint8Array(width * height * 4); var gl = cc.game._renderContext; var oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer.getHandle()); gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO); return data; }, destroy: function destroy() { this._super(); if (this._framebuffer) { this._framebuffer.destroy(); this._framebuffer = null; } } }); cc.RenderTexture = module.exports = RenderTexture; }), { "../../renderer/gfx": 259, "../renderer": 160, "./CCTexture2D": 72 } ], 66: [ (function(require, module, exports) { "use strict"; var Scene = cc.Class({ name: "cc.SceneAsset", extends: cc.Asset, properties: { scene: null, asyncLoadAssets: void 0 } }); cc.SceneAsset = Scene; module.exports = Scene; }), {} ], 67: [ (function(require, module, exports) { "use strict"; var Script = cc.Class({ name: "cc.Script", extends: cc.Asset }); cc._Script = Script; var JavaScript = cc.Class({ name: "cc.JavaScript", extends: Script }); cc._JavaScript = JavaScript; var TypeScript = cc.Class({ name: "cc.TypeScript", extends: Script }); cc._TypeScript = TypeScript; }), {} ], 68: [ (function(require, module, exports) { "use strict"; var SpriteAtlas = cc.Class({ name: "cc.SpriteAtlas", extends: cc.Asset, properties: { _spriteFrames: { default: {} } }, getTexture: function getTexture() { var keys = Object.keys(this._spriteFrames); if (keys.length > 0) { var spriteFrame = this._spriteFrames[keys[0]]; return spriteFrame ? spriteFrame.getTexture() : null; } return null; }, getSpriteFrame: function getSpriteFrame(key) { var sf = this._spriteFrames[key]; if (!sf) return null; sf.name || (sf.name = key); return sf; }, getSpriteFrames: function getSpriteFrames() { var frames = []; var spriteFrames = this._spriteFrames; for (var key in spriteFrames) frames.push(this.getSpriteFrame(key)); return frames; } }); cc.SpriteAtlas = SpriteAtlas; module.exports = SpriteAtlas; }), {} ], 69: [ (function(require, module, exports) { "use strict"; var EventTarget = require("../event/event-target"); var INSET_LEFT = 0; var INSET_TOP = 1; var INSET_RIGHT = 2; var INSET_BOTTOM = 3; var temp_uvs = [ { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 } ]; var SpriteFrame = cc.Class({ name: "cc.SpriteFrame", extends: require("../assets/CCAsset"), mixins: [ EventTarget ], properties: { _textureSetter: { set: function set(texture) { if (texture) { false; this._texture !== texture && this._refreshTexture(texture); } } }, insetTop: { get: function get() { return this._capInsets[INSET_TOP]; }, set: function set(value) { this._capInsets[INSET_TOP] = value; this._texture && this._calculateSlicedUV(); } }, insetBottom: { get: function get() { return this._capInsets[INSET_BOTTOM]; }, set: function set(value) { this._capInsets[INSET_BOTTOM] = value; this._texture && this._calculateSlicedUV(); } }, insetLeft: { get: function get() { return this._capInsets[INSET_LEFT]; }, set: function set(value) { this._capInsets[INSET_LEFT] = value; this._texture && this._calculateSlicedUV(); } }, insetRight: { get: function get() { return this._capInsets[INSET_RIGHT]; }, set: function set(value) { this._capInsets[INSET_RIGHT] = value; this._texture && this._calculateSlicedUV(); } } }, ctor: function ctor() { EventTarget.call(this); var filename = arguments[0]; var rect = arguments[1]; var rotated = arguments[2]; var offset = arguments[3]; var originalSize = arguments[4]; this._rect = null; this.uv = []; this._texture = null; this._original = null; this._offset = null; this._originalSize = null; this._rotated = false; this._flipX = false; this._flipY = false; this.vertices = null; this._capInsets = [ 0, 0, 0, 0 ]; this.uvSliced = []; false; void 0 !== filename && this.setTexture(filename, rect, rotated, offset, originalSize); }, textureLoaded: function textureLoaded() { return this._texture && this._texture.loaded; }, onTextureLoaded: function onTextureLoaded(callback, target) { if (!this.textureLoaded()) { this.once("load", callback, target); this.ensureLoadTexture(); return false; } callback.call(target); return true; }, isRotated: function isRotated() { return this._rotated; }, setRotated: function setRotated(bRotated) { this._rotated = bRotated; this._texture && this._calculateUV(); }, isFlipX: function isFlipX() { return this._flipX; }, isFlipY: function isFlipY() { return this._flipY; }, setFlipX: function setFlipX(flipX) { this._flipX = flipX; this._texture && this._calculateUV(); }, setFlipY: function setFlipY(flipY) { this._flipY = flipY; this._texture && this._calculateUV(); }, getRect: function getRect() { return cc.rect(this._rect); }, setRect: function setRect(rect) { this._rect = rect; this._texture && this._calculateUV(); }, getOriginalSize: function getOriginalSize() { return cc.size(this._originalSize); }, setOriginalSize: function setOriginalSize(size) { if (this._originalSize) { this._originalSize.width = size.width; this._originalSize.height = size.height; } else this._originalSize = cc.size(size); }, getTexture: function getTexture() { return this._texture; }, _textureLoadedCallback: function _textureLoadedCallback() { var self = this; var texture = this._texture; if (!texture) return; var w = texture.width, h = texture.height; self._rect ? self._checkRect(self._texture) : self._rect = cc.rect(0, 0, w, h); self._originalSize || self.setOriginalSize(cc.size(w, h)); self._offset || self.setOffset(cc.v2(0, 0)); self._calculateUV(); self.emit("load"); }, _refreshTexture: function _refreshTexture(texture) { this._texture = texture; texture.loaded ? this._textureLoadedCallback() : texture.once("load", this._textureLoadedCallback, this); }, getOffset: function getOffset() { return cc.v2(this._offset); }, setOffset: function setOffset(offsets) { this._offset = cc.v2(offsets); }, clone: function clone() { return new SpriteFrame(this._texture, this.getRect(), this._rotated, this.getOffset(), this.getOriginalSize()); }, setTexture: function setTexture(texture, rect, rotated, offset, originalSize) { if (1 === arguments.length && texture === this._texture) return; this._rect = rect || null; offset ? this.setOffset(offset) : this._offset = null; originalSize ? this.setOriginalSize(originalSize) : this._originalSize = null; this._rotated = rotated || false; if ("string" === typeof texture) { cc.errorID(3401); return; } texture instanceof cc.Texture2D && this._refreshTexture(texture); return true; }, ensureLoadTexture: function ensureLoadTexture() { if (this._texture && !this._texture.loaded) { this._refreshTexture(this._texture); cc.assetManager.postLoadNative(this._texture); } }, _checkRect: function _checkRect(texture) { var rect = this._rect; var maxX = rect.x, maxY = rect.y; if (this._rotated) { maxX += rect.height; maxY += rect.width; } else { maxX += rect.width; maxY += rect.height; } maxX > texture.width && cc.errorID(3300, texture.nativeUrl + "/" + this.name, maxX, texture.width); maxY > texture.height && cc.errorID(3400, texture.nativeUrl + "/" + this.name, maxY, texture.height); }, _flipXY: function _flipXY(uvs) { if (this._flipX) { var tempVal = uvs[0]; uvs[0] = uvs[1]; uvs[1] = tempVal; tempVal = uvs[2]; uvs[2] = uvs[3]; uvs[3] = tempVal; } if (this._flipY) { var _tempVal = uvs[0]; uvs[0] = uvs[2]; uvs[2] = _tempVal; _tempVal = uvs[1]; uvs[1] = uvs[3]; uvs[3] = _tempVal; } }, _calculateSlicedUV: function _calculateSlicedUV() { var rect = this._rect; var atlasWidth = this._texture.width; var atlasHeight = this._texture.height; var leftWidth = this._capInsets[INSET_LEFT]; var rightWidth = this._capInsets[INSET_RIGHT]; var centerWidth = rect.width - leftWidth - rightWidth; var topHeight = this._capInsets[INSET_TOP]; var bottomHeight = this._capInsets[INSET_BOTTOM]; var centerHeight = rect.height - topHeight - bottomHeight; var uvSliced = this.uvSliced; uvSliced.length = 0; if (this._rotated) { temp_uvs[0].u = rect.x / atlasWidth; temp_uvs[1].u = (rect.x + bottomHeight) / atlasWidth; temp_uvs[2].u = (rect.x + bottomHeight + centerHeight) / atlasWidth; temp_uvs[3].u = (rect.x + rect.height) / atlasWidth; temp_uvs[3].v = rect.y / atlasHeight; temp_uvs[2].v = (rect.y + leftWidth) / atlasHeight; temp_uvs[1].v = (rect.y + leftWidth + centerWidth) / atlasHeight; temp_uvs[0].v = (rect.y + rect.width) / atlasHeight; this._flipXY(temp_uvs); for (var row = 0; row < 4; ++row) { var rowD = temp_uvs[row]; for (var col = 0; col < 4; ++col) { var colD = temp_uvs[3 - col]; uvSliced.push({ u: rowD.u, v: colD.v }); } } } else { temp_uvs[0].u = rect.x / atlasWidth; temp_uvs[1].u = (rect.x + leftWidth) / atlasWidth; temp_uvs[2].u = (rect.x + leftWidth + centerWidth) / atlasWidth; temp_uvs[3].u = (rect.x + rect.width) / atlasWidth; temp_uvs[3].v = rect.y / atlasHeight; temp_uvs[2].v = (rect.y + topHeight) / atlasHeight; temp_uvs[1].v = (rect.y + topHeight + centerHeight) / atlasHeight; temp_uvs[0].v = (rect.y + rect.height) / atlasHeight; this._flipXY(temp_uvs); for (var _row = 0; _row < 4; ++_row) { var _rowD = temp_uvs[_row]; for (var _col = 0; _col < 4; ++_col) { var _colD = temp_uvs[_col]; uvSliced.push({ u: _colD.u, v: _rowD.v }); } } } }, _setDynamicAtlasFrame: function _setDynamicAtlasFrame(frame) { if (!frame) return; this._original = { _texture: this._texture, _x: this._rect.x, _y: this._rect.y }; this._texture = frame.texture; this._rect.x = frame.x; this._rect.y = frame.y; this._calculateUV(); }, _resetDynamicAtlasFrame: function _resetDynamicAtlasFrame() { if (!this._original) return; this._rect.x = this._original._x; this._rect.y = this._original._y; this._texture = this._original._texture; this._original = null; this._texture.loaded ? this._calculateUV() : this.ensureLoadTexture(); this.emit("_resetDynamicAtlasFrame"); }, _calculateUV: function _calculateUV() { var rect = this._rect, texture = this._texture, uv = this.uv, texw = texture.width, texh = texture.height; if (this._rotated) { var l = 0 === texw ? 0 : rect.x / texw; var r = 0 === texw ? 0 : (rect.x + rect.height) / texw; var b = 0 === texh ? 0 : (rect.y + rect.width) / texh; var t = 0 === texh ? 0 : rect.y / texh; uv[0] = l; uv[1] = t; uv[2] = l; uv[3] = b; uv[4] = r; uv[5] = t; uv[6] = r; uv[7] = b; } else { var _l = 0 === texw ? 0 : rect.x / texw; var _r = 0 === texw ? 0 : (rect.x + rect.width) / texw; var _b = 0 === texh ? 0 : (rect.y + rect.height) / texh; var _t = 0 === texh ? 0 : rect.y / texh; uv[0] = _l; uv[1] = _b; uv[2] = _r; uv[3] = _b; uv[4] = _l; uv[5] = _t; uv[6] = _r; uv[7] = _t; } if (this._flipX) { var tempVal = uv[0]; uv[0] = uv[2]; uv[2] = tempVal; tempVal = uv[1]; uv[1] = uv[3]; uv[3] = tempVal; tempVal = uv[4]; uv[4] = uv[6]; uv[6] = tempVal; tempVal = uv[5]; uv[5] = uv[7]; uv[7] = tempVal; } if (this._flipY) { var _tempVal2 = uv[0]; uv[0] = uv[4]; uv[4] = _tempVal2; _tempVal2 = uv[1]; uv[1] = uv[5]; uv[5] = _tempVal2; _tempVal2 = uv[2]; uv[2] = uv[6]; uv[6] = _tempVal2; _tempVal2 = uv[3]; uv[3] = uv[7]; uv[7] = _tempVal2; } var vertices = this.vertices; if (vertices) { vertices.nu.length = 0; vertices.nv.length = 0; for (var i = 0; i < vertices.u.length; i++) { vertices.nu[i] = vertices.u[i] / texw; vertices.nv[i] = vertices.v[i] / texh; } } this._calculateSlicedUV(); }, _serialize: (false, false) && function(exporting, ctx) { var rect = this._rect; var offset = this._offset; var size = this._originalSize; var uuid; var texture = this._texture; texture && (uuid = texture._uuid); if (!uuid) { var url = this._textureFilename; url && (uuid = Editor.Utils.UuidCache.urlToUuid(url)); } if (uuid && exporting) { uuid = Editor.Utils.UuidUtils.compressUuid(uuid, true); ctx.dependsOn("_textureSetter", uuid); } var vertices; this.vertices && (vertices = { triangles: this.vertices.triangles, x: this.vertices.x, y: this.vertices.y, u: this.vertices.u, v: this.vertices.v }); return { name: this._name, texture: !exporting && uuid || void 0, atlas: exporting ? void 0 : this._atlasUuid, rect: rect ? [ rect.x, rect.y, rect.width, rect.height ] : void 0, offset: offset ? [ offset.x, offset.y ] : void 0, originalSize: size ? [ size.width, size.height ] : void 0, rotated: this._rotated ? 1 : void 0, capInsets: this._capInsets, vertices: vertices }; }, _deserialize: function _deserialize(data, handle) { var rect = data.rect; rect && (this._rect = new cc.Rect(rect[0], rect[1], rect[2], rect[3])); data.offset && this.setOffset(new cc.Vec2(data.offset[0], data.offset[1])); data.originalSize && this.setOriginalSize(new cc.Size(data.originalSize[0], data.originalSize[1])); this._rotated = 1 === data.rotated; this._name = data.name; var capInsets = data.capInsets; if (capInsets) { this._capInsets[INSET_LEFT] = capInsets[INSET_LEFT]; this._capInsets[INSET_TOP] = capInsets[INSET_TOP]; this._capInsets[INSET_RIGHT] = capInsets[INSET_RIGHT]; this._capInsets[INSET_BOTTOM] = capInsets[INSET_BOTTOM]; } false; this.vertices = data.vertices; if (this.vertices) { this.vertices.nu = []; this.vertices.nv = []; } var textureUuid; false; }, destroy: function destroy() { cc.dynamicAtlasManager && cc.dynamicAtlasManager.deleteSpriteFrame(this); this._super(); } }); var proto = SpriteFrame.prototype; proto.copyWithZone = proto.clone; proto.copy = proto.clone; proto.initWithTexture = proto.setTexture; cc.SpriteFrame = SpriteFrame; module.exports = SpriteFrame; }), { "../assets/CCAsset": 57, "../event/event-target": 119 } ], 70: [ (function(require, module, exports) { "use strict"; var Font = require("./CCFont"); var TTFFont = cc.Class({ name: "cc.TTFFont", extends: Font, properties: { _fontFamily: null, _nativeAsset: { type: cc.String, get: function get() { return this._fontFamily; }, set: function set(value) { this._fontFamily = value || "Arial"; }, override: true }, _nativeDep: { get: function get() { return { uuid: this._uuid, __nativeName__: this._native, ext: cc.path.extname(this._native), __isNative__: true }; }, override: true } } }); cc.TTFFont = module.exports = TTFFont; }), { "./CCFont": 61 } ], 71: [ (function(require, module, exports) { "use strict"; var TextAsset = cc.Class({ name: "cc.TextAsset", extends: cc.Asset, properties: { text: "" }, toString: function toString() { return this.text; } }); module.exports = cc.TextAsset = TextAsset; }), {} ], 72: [ (function(require, module, exports) { "use strict"; var _gfx = _interopRequireDefault(require("../../renderer/gfx")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventTarget = require("../event/event-target"); var renderer = require("../renderer"); require("../platform/CCClass"); var GL_NEAREST = 9728; var GL_LINEAR = 9729; var GL_REPEAT = 10497; var GL_CLAMP_TO_EDGE = 33071; var GL_MIRRORED_REPEAT = 33648; var GL_RGBA = 6408; var CHAR_CODE_0 = 48; var CHAR_CODE_1 = 49; var idGenerater = new (require("../platform/id-generater"))("Tex"); var CUSTOM_PIXEL_FORMAT = 1024; var PixelFormat = cc.Enum({ RGB565: _gfx["default"].TEXTURE_FMT_R5_G6_B5, RGB5A1: _gfx["default"].TEXTURE_FMT_R5_G5_B5_A1, RGBA4444: _gfx["default"].TEXTURE_FMT_R4_G4_B4_A4, RGB888: _gfx["default"].TEXTURE_FMT_RGB8, RGBA8888: _gfx["default"].TEXTURE_FMT_RGBA8, RGBA32F: _gfx["default"].TEXTURE_FMT_RGBA32F, A8: _gfx["default"].TEXTURE_FMT_A8, I8: _gfx["default"].TEXTURE_FMT_L8, AI8: _gfx["default"].TEXTURE_FMT_L8_A8, RGB_PVRTC_2BPPV1: _gfx["default"].TEXTURE_FMT_RGB_PVRTC_2BPPV1, RGBA_PVRTC_2BPPV1: _gfx["default"].TEXTURE_FMT_RGBA_PVRTC_2BPPV1, RGB_A_PVRTC_2BPPV1: CUSTOM_PIXEL_FORMAT++, RGB_PVRTC_4BPPV1: _gfx["default"].TEXTURE_FMT_RGB_PVRTC_4BPPV1, RGBA_PVRTC_4BPPV1: _gfx["default"].TEXTURE_FMT_RGBA_PVRTC_4BPPV1, RGB_A_PVRTC_4BPPV1: CUSTOM_PIXEL_FORMAT++, RGB_ETC1: _gfx["default"].TEXTURE_FMT_RGB_ETC1, RGBA_ETC1: CUSTOM_PIXEL_FORMAT++, RGB_ETC2: _gfx["default"].TEXTURE_FMT_RGB_ETC2, RGBA_ETC2: _gfx["default"].TEXTURE_FMT_RGBA_ETC2 }); var WrapMode = cc.Enum({ REPEAT: GL_REPEAT, CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE, MIRRORED_REPEAT: GL_MIRRORED_REPEAT }); var Filter = cc.Enum({ LINEAR: GL_LINEAR, NEAREST: GL_NEAREST }); var FilterIndex = { 9728: 0, 9729: 1 }; var _images = []; var _sharedOpts = { width: void 0, height: void 0, minFilter: void 0, magFilter: void 0, wrapS: void 0, wrapT: void 0, format: void 0, genMipmaps: void 0, images: void 0, image: void 0, flipY: void 0, premultiplyAlpha: void 0 }; function _getSharedOptions() { for (var key in _sharedOpts) _sharedOpts[key] = void 0; _images.length = 0; _sharedOpts.images = _images; return _sharedOpts; } var Texture2D = cc.Class({ name: "cc.Texture2D", extends: require("../assets/CCAsset"), mixins: [ EventTarget ], properties: { _nativeAsset: { get: function get() { return this._image; }, set: function set(data) { data._compressed && data._data ? this.initWithData(data._data, this._format, data.width, data.height) : this.initWithElement(data); }, override: true }, _format: PixelFormat.RGBA8888, _premultiplyAlpha: false, _flipY: false, _minFilter: Filter.LINEAR, _magFilter: Filter.LINEAR, _mipFilter: Filter.LINEAR, _wrapS: WrapMode.CLAMP_TO_EDGE, _wrapT: WrapMode.CLAMP_TO_EDGE, _isAlphaAtlas: false, _genMipmaps: false, genMipmaps: { get: function get() { return this._genMipmaps; }, set: function set(genMipmaps) { if (this._genMipmaps !== genMipmaps) { var opts = _getSharedOptions(); opts.genMipmaps = genMipmaps; this.update(opts); } } }, _packable: true, packable: { get: function get() { return this._packable; }, set: function set(val) { this._packable = val; } }, _nativeDep: { get: function get() { return { __isNative__: true, uuid: this._uuid, ext: this._native, __flipY__: this._flipY, __premultiplyAlpha__: this._premultiplyAlpha }; }, override: true } }, statics: { PixelFormat: PixelFormat, WrapMode: WrapMode, Filter: Filter, _FilterIndex: FilterIndex, extnames: [ ".png", ".jpg", ".jpeg", ".bmp", ".webp", ".pvr", ".pkm" ], _parseExt: function _parseExt(extIdStr, defaultFormat) { var device = cc.renderer.device; var extIds = extIdStr.split("_"); var defaultExt = ""; var bestExt = ""; var bestIndex = 999; var bestFormat = defaultFormat; var SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS; for (var i = 0; i < extIds.length; i++) { var extFormat = extIds[i].split("@"); var tmpExt = extFormat[0]; tmpExt = Texture2D.extnames[tmpExt.charCodeAt(0) - CHAR_CODE_0] || tmpExt; var index = SupportTextureFormats.indexOf(tmpExt); if (-1 !== index && index < bestIndex) { var tmpFormat = extFormat[1] ? parseInt(extFormat[1]) : defaultFormat; if (".pvr" === tmpExt && !device.ext("WEBGL_compressed_texture_pvrtc")) continue; if (!(tmpFormat !== PixelFormat.RGB_ETC1 && tmpFormat !== PixelFormat.RGBA_ETC1 || device.ext("WEBGL_compressed_texture_etc1"))) continue; if (!(tmpFormat !== PixelFormat.RGB_ETC2 && tmpFormat !== PixelFormat.RGBA_ETC2 || device.ext("WEBGL_compressed_texture_etc"))) continue; if (".webp" === tmpExt && !cc.sys.capabilities.webp) continue; bestIndex = index; bestExt = tmpExt; bestFormat = tmpFormat; } else defaultExt || (defaultExt = tmpExt); } return { bestExt: bestExt, bestFormat: bestFormat, defaultExt: defaultExt }; } }, ctor: function ctor() { this._id = idGenerater.getNewId(); this.loaded = false; this.width = 0; this.height = 0; this._hashDirty = true; this._hash = 0; this._texture = null; false; this._multiMaterial = null; }, getImpl: function getImpl() { this._texture || (this._texture = new renderer.Texture2D(renderer.device, {})); return this._texture; }, getId: function getId() { return this._id; }, toString: function toString() { return this.nativeUrl || ""; }, update: function update(options) { if (options) { var updateImg = false; void 0 !== options.width && (this.width = options.width); void 0 !== options.height && (this.height = options.height); if (void 0 !== options.minFilter) { this._minFilter = options.minFilter; options.minFilter = FilterIndex[options.minFilter]; } if (void 0 !== options.magFilter) { this._magFilter = options.magFilter; options.magFilter = FilterIndex[options.magFilter]; } if (void 0 !== options.mipFilter) { this._mipFilter = options.mipFilter; options.mipFilter = FilterIndex[options.mipFilter]; } void 0 !== options.wrapS && (this._wrapS = options.wrapS); void 0 !== options.wrapT && (this._wrapT = options.wrapT); void 0 !== options.format && (this._format = options.format); if (void 0 !== options.flipY) { this._flipY = options.flipY; updateImg = true; } if (void 0 !== options.premultiplyAlpha) { this._premultiplyAlpha = options.premultiplyAlpha; updateImg = true; } void 0 !== options.genMipmaps && (this._genMipmaps = options.genMipmaps); cc.sys.capabilities.imageBitmap && this._image instanceof ImageBitmap ? this._checkImageBitmap(this._upload.bind(this, options, updateImg)) : this._upload(options, updateImg); } }, _upload: function _upload(options, updateImg) { updateImg && this._image && (options.image = this._image); if (options.images && options.images.length > 0) this._image = options.images[0]; else if (void 0 !== options.image) { this._image = options.image; if (!options.images) { _images.length = 0; options.images = _images; } options.images.push(options.image); } this._texture && this._texture.update(options); this._hashDirty = true; }, initWithElement: function initWithElement(element) { if (!element) return; this._image = element; if (element.complete || element instanceof HTMLCanvasElement) this.handleLoadedTexture(); else if (cc.sys.capabilities.imageBitmap && element instanceof ImageBitmap) this._checkImageBitmap(this.handleLoadedTexture.bind(this)); else { var self = this; element.addEventListener("load", (function() { self.handleLoadedTexture(); })); element.addEventListener("error", (function(err) { cc.warnID(3119, err.message); })); } }, initWithData: function initWithData(data, pixelFormat, pixelsWidth, pixelsHeight) { var opts = _getSharedOptions(); opts.image = data; opts.images = [ opts.image ]; opts.genMipmaps = this._genMipmaps; opts.premultiplyAlpha = this._premultiplyAlpha; opts.flipY = this._flipY; opts.minFilter = FilterIndex[this._minFilter]; opts.magFilter = FilterIndex[this._magFilter]; opts.wrapS = this._wrapS; opts.wrapT = this._wrapT; opts.format = this._getGFXPixelFormat(pixelFormat); opts.width = pixelsWidth; opts.height = pixelsHeight; this._texture ? this._texture.update(opts) : this._texture = new renderer.Texture2D(renderer.device, opts); this.width = pixelsWidth; this.height = pixelsHeight; this._updateFormat(); this._checkPackable(); this.loaded = true; this.emit("load"); return true; }, getHtmlElementObj: function getHtmlElementObj() { return this._image; }, destroy: function destroy() { cc.sys.capabilities.imageBitmap && this._image instanceof ImageBitmap && this._image.close && this._image.close(); this._packable && cc.dynamicAtlasManager && cc.dynamicAtlasManager.deleteAtlasTexture(this); this.unlinkMaterial(); this._image = null; this._texture && this._texture.destroy(); this._super(); }, getPixelFormat: function getPixelFormat() { return this._format; }, hasPremultipliedAlpha: function hasPremultipliedAlpha() { return this._premultiplyAlpha || false; }, isAlphaAtlas: function isAlphaAtlas() { return this._isAlphaAtlas; }, handleLoadedTexture: function handleLoadedTexture() { if (!this._image || !this._image.width || !this._image.height) return; this.width = this._image.width; this.height = this._image.height; var opts = _getSharedOptions(); opts.image = this._image; opts.images = [ opts.image ]; opts.width = this.width; opts.height = this.height; opts.genMipmaps = this._genMipmaps; opts.format = this._getGFXPixelFormat(this._format); opts.premultiplyAlpha = this._premultiplyAlpha; opts.flipY = this._flipY; opts.minFilter = FilterIndex[this._minFilter]; opts.magFilter = FilterIndex[this._magFilter]; opts.wrapS = this._wrapS; opts.wrapT = this._wrapT; this._texture ? this._texture.update(opts) : this._texture = new renderer.Texture2D(renderer.device, opts); this._updateFormat(); this._checkPackable(); this.loaded = true; this.emit("load"); cc.macro.CLEANUP_IMAGE_CACHE && this._cleanupImageCache(); }, _cleanupImageCache: function _cleanupImageCache() { this._image instanceof HTMLImageElement ? this._clearImage() : cc.sys.capabilities.imageBitmap && this._image instanceof ImageBitmap && this._image.close && this._image.close(); }, description: function description() { return ""; }, releaseTexture: function releaseTexture() { this._image = null; this._texture && this._texture.destroy(); }, setWrapMode: function setWrapMode(wrapS, wrapT) { if (this._wrapS !== wrapS || this._wrapT !== wrapT) { var opts = _getSharedOptions(); opts.wrapS = wrapS; opts.wrapT = wrapT; this.update(opts); } }, setFilters: function setFilters(minFilter, magFilter) { if (this._minFilter !== minFilter || this._magFilter !== magFilter) { var opts = _getSharedOptions(); opts.minFilter = minFilter; opts.magFilter = magFilter; this.update(opts); } }, setFlipY: function setFlipY(flipY) { if (this._flipY !== flipY) { var opts = _getSharedOptions(); opts.flipY = flipY; opts.premultiplyAlpha = this._premultiplyAlpha; this.update(opts); } }, setPremultiplyAlpha: function setPremultiplyAlpha(premultiply) { if (this._premultiplyAlpha !== premultiply) { var opts = _getSharedOptions(); opts.flipY = this._flipY; opts.premultiplyAlpha = premultiply; this.update(opts); } }, _updateFormat: function _updateFormat() { this._isAlphaAtlas = this._format === PixelFormat.RGBA_ETC1 || this._format === PixelFormat.RGB_A_PVRTC_4BPPV1 || this._format === PixelFormat.RGB_A_PVRTC_2BPPV1; false; }, _checkPackable: function _checkPackable() { var dynamicAtlas = cc.dynamicAtlasManager; if (!dynamicAtlas) return; if (this._isCompressed()) { this._packable = false; return; } var w = this.width, h = this.height; if (!this._image || w > dynamicAtlas.maxFrameSize || h > dynamicAtlas.maxFrameSize || this._getHash() !== dynamicAtlas.Atlas.DEFAULT_HASH) { this._packable = false; return; } this._image && this._image instanceof HTMLCanvasElement && (this._packable = true); }, _getOpts: function _getOpts() { var opts = _getSharedOptions(); opts.width = this.width; opts.height = this.height; opts.genMipmaps = this._genMipmaps; opts.format = this._format; opts.premultiplyAlpha = this._premultiplyAlpha; opts.anisotropy = this._anisotropy; opts.flipY = this._flipY; opts.minFilter = FilterIndex[this._minFilter]; opts.magFilter = FilterIndex[this._magFilter]; opts.mipFilter = FilterIndex[this._mipFilter]; opts.wrapS = this._wrapS; opts.wrapT = this._wrapT; return opts; }, _getGFXPixelFormat: function _getGFXPixelFormat(format) { format === PixelFormat.RGBA_ETC1 ? format = PixelFormat.RGB_ETC1 : format === PixelFormat.RGB_A_PVRTC_4BPPV1 ? format = PixelFormat.RGB_PVRTC_4BPPV1 : format === PixelFormat.RGB_A_PVRTC_2BPPV1 && (format = PixelFormat.RGB_PVRTC_2BPPV1); return format; }, _resetUnderlyingMipmaps: function _resetUnderlyingMipmaps(mipmapSources) { var opts = this._getOpts(); opts.images = mipmapSources || [ null ]; this._texture ? this._texture.update(opts) : this._texture = new renderer.Texture2D(renderer.device, opts); }, _serialize: (false, false) && function() { var extId = ""; var exportedExts = this._exportedExts; !exportedExts && this._native && (exportedExts = [ this._native ]); if (exportedExts) { var exts = []; for (var i = 0; i < exportedExts.length; i++) { var _extId = ""; var ext = exportedExts[i]; if (ext) { var extFormat = ext.split("@"); _extId = Texture2D.extnames.indexOf(extFormat[0]); _extId < 0 && (_extId = ext); extFormat[1] && (_extId += "@" + extFormat[1]); } exts.push(_extId); } extId = exts.join("_"); } var asset = extId + "," + this._minFilter + "," + this._magFilter + "," + this._wrapS + "," + this._wrapT + "," + (this._premultiplyAlpha ? 1 : 0) + "," + (this._genMipmaps ? 1 : 0) + "," + (this._packable ? 1 : 0); return asset; }, _deserialize: function _deserialize(data) { var fields = data.split(","); var extIdStr = fields[0]; if (extIdStr) { var result = Texture2D._parseExt(extIdStr, this._format); if (result.bestExt) { this._setRawAsset(result.bestExt); this._format = result.bestFormat; } else { if (!result.defaultExt) throw new Error(cc.debug.getError(3121)); this._setRawAsset(result.defaultExt); cc.warnID(3120, result.defaultExt, result.defaultExt); } } if (8 === fields.length) { this._minFilter = parseInt(fields[1]); this._magFilter = parseInt(fields[2]); this._wrapS = parseInt(fields[3]); this._wrapT = parseInt(fields[4]); this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1; this._genMipmaps = fields[6].charCodeAt(0) === CHAR_CODE_1; this._packable = fields[7].charCodeAt(0) === CHAR_CODE_1; } }, _getHash: function _getHash() { if (!this._hashDirty) return this._hash; var genMipmaps = this._genMipmaps ? 1 : 0; var premultiplyAlpha = this._premultiplyAlpha ? 1 : 0; var flipY = this._flipY ? 1 : 0; var minFilter = this._minFilter === Filter.LINEAR ? 1 : 2; var magFilter = this._magFilter === Filter.LINEAR ? 1 : 2; var wrapS = this._wrapS === WrapMode.REPEAT ? 1 : this._wrapS === WrapMode.CLAMP_TO_EDGE ? 2 : 3; var wrapT = this._wrapT === WrapMode.REPEAT ? 1 : this._wrapT === WrapMode.CLAMP_TO_EDGE ? 2 : 3; var pixelFormat = this._format; var image = this._image; false; this._hash = Number("" + minFilter + magFilter + pixelFormat + wrapS + wrapT + genMipmaps + premultiplyAlpha + flipY); this._hashDirty = false; return this._hash; }, _isCompressed: function _isCompressed() { return this._format < PixelFormat.A8 || this._format > PixelFormat.RGBA32F; }, _clearImage: function _clearImage() { this._image.src = ""; }, _checkImageBitmap: function _checkImageBitmap(cb) { var _this = this; var image = this._image; var flipY = this._flipY; var premultiplyAlpha = this._premultiplyAlpha; this._flipY !== image.flipY || this._premultiplyAlpha !== image.premultiplyAlpha ? createImageBitmap(image, { imageOrientation: flipY !== image.flipY ? "flipY" : "none", premultiplyAlpha: premultiplyAlpha ? "premultiply" : "none" }).then((function(result) { image.close && image.close(); result.flipY = flipY; result.premultiplyAlpha = premultiplyAlpha; _this._image = result; cb(); }), (function(err) { cc.error(err.message); })) : cb(); }, linkMaterial: function linkMaterial(material, index) { var handler = material.getMultiHandler(); if (handler) { if (null == index) { if (-1 === handler.autoSetTexture(this)) return false; } else handler.setTexture(index, this); this.unlinkMaterial(); this._multiMaterial = material; return true; } return false; }, unlinkMaterial: function unlinkMaterial() { if (this._multiMaterial) { var handler = this._multiMaterial.getMultiHandler(); var _texture = this.getImpl(); handler.removeTexture(_texture); this._multiMaterial = null; } }, getLinkedMaterial: function getLinkedMaterial() { return this._multiMaterial; }, hasLinkedMaterial: function hasLinkedMaterial() { return !!this._multiMaterial; } }); cc.Texture2D = module.exports = Texture2D; }), { "../../renderer/gfx": 259, "../assets/CCAsset": 57, "../event/event-target": 119, "../platform/CCClass": 129, "../platform/id-generater": 146, "../renderer": 160 } ], 73: [ (function(require, module, exports) { "use strict"; var Asset = require("./CCAsset"); var EventTarget = require("../event/event-target"); var VideoClip = cc.Class({ name: "cc.VideoClip", extends: Asset, mixins: [ EventTarget ] }); cc.VideoClip = VideoClip; module.exports = VideoClip; }), { "../event/event-target": 119, "./CCAsset": 57 } ], 74: [ (function(require, module, exports) { "use strict"; require("./CCAsset"); require("./CCFont"); require("./CCPrefab"); require("./CCAudioClip"); require("./CCVideoClip"); require("./CCScripts"); require("./CCSceneAsset"); require("./CCSpriteFrame"); require("./CCTexture2D"); require("./CCRenderTexture"); require("./CCTTFFont"); require("./CCSpriteAtlas"); require("./CCBitmapFont"); require("./CCLabelAtlas"); require("./CCTextAsset"); require("./CCJsonAsset"); require("./CCBufferAsset"); require("./material"); }), { "./CCAsset": 57, "./CCAudioClip": 58, "./CCBitmapFont": 59, "./CCBufferAsset": 60, "./CCFont": 61, "./CCJsonAsset": 62, "./CCLabelAtlas": 63, "./CCPrefab": 64, "./CCRenderTexture": 65, "./CCSceneAsset": 66, "./CCScripts": 67, "./CCSpriteAtlas": 68, "./CCSpriteFrame": 69, "./CCTTFFont": 70, "./CCTextAsset": 71, "./CCTexture2D": 72, "./CCVideoClip": 73, "./material": 81 } ], 75: [ (function(require, module, exports) { "use strict"; var _CCAsset = _interopRequireDefault(require("../CCAsset")); var _effectParser = require("./effect-parser"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EffectAsset = cc.Class({ name: "cc.EffectAsset", extends: _CCAsset["default"], ctor: function ctor() { this._effect = null; }, properties: { properties: Object, techniques: [], shaders: [] }, onLoad: function onLoad() { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return; var lib = cc.renderer._forward._programLib; for (var i = 0; i < this.shaders.length; i++) lib.define(this.shaders[i]); this._initEffect(); }, _initEffect: function _initEffect() { if (this._effect) return; this._effect = (0, _effectParser.parseEffect)(this); Object.freeze(this._effect); }, getInstantiatedEffect: function getInstantiatedEffect() { this._initEffect(); return this._effect.clone(); }, getEffect: function getEffect() { this._initEffect(); return this._effect; } }); module.exports = cc.EffectAsset = EffectAsset; }), { "../CCAsset": 57, "./effect-parser": 78 } ], 76: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var Asset = require("../CCAsset"); var Texture = require("../CCTexture2D"); var PixelFormat = Texture.PixelFormat; var EffectAsset = require("./CCEffectAsset"); var textureUtil = require("../../utils/texture-util"); var gfx = cc.gfx; var BUILTIN_NAME = cc.Enum({ SPRITE: "2d-sprite", GRAY_SPRITE: "2d-gray-sprite", UNLIT: "unlit" }); var Material = cc.Class({ name: "cc.Material", extends: Asset, ctor: function ctor() { this.loaded = false; this._manualHash = false; this._dirty = true; this._effect = null; this._multiHandler = null; }, properties: { _defines: { default: void 0, type: Object }, _props: { default: void 0, type: Object }, _effectAsset: { type: EffectAsset, default: null }, _techniqueIndex: 0, _techniqueData: Object, effectName: void 0, effectAsset: { get: function get() { return this._effectAsset; }, set: function set(asset) { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return; this._effectAsset = asset; if (!asset) { cc.error("Can not set an empty effect asset."); return; } this._effect = this._effectAsset.getInstantiatedEffect(); this.updateMultiSupport(); } }, effect: { get: function get() { return this._effect; } }, techniqueIndex: { get: function get() { return this._techniqueIndex; }, set: function set(v) { this._techniqueIndex = v; this._effect.switchTechnique(v); this.updateMultiSupport(); } } }, statics: { getBuiltinMaterial: function getBuiltinMaterial(name) { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.Material(); return cc.assetManager.builtins.getBuiltin("material", "builtin-" + name); }, BUILTIN_NAME: BUILTIN_NAME, createWithBuiltin: function createWithBuiltin(effectName, techniqueIndex) { void 0 === techniqueIndex && (techniqueIndex = 0); var effectAsset = cc.assetManager.builtins.getBuiltin("effect", "builtin-" + effectName); return Material.create(effectAsset, techniqueIndex); }, create: function create(effectAsset, techniqueIndex) { void 0 === techniqueIndex && (techniqueIndex = 0); if (!effectAsset) return null; var material = new Material(); material.effectAsset = effectAsset; material.techniqueIndex = techniqueIndex; return material; } }, setProperty: function setProperty(name, val, passIdx, directly) { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return; "string" === typeof passIdx && (passIdx = parseInt(passIdx)); if (val instanceof Texture) { var isAlphaAtlas = val.isAlphaAtlas(); var key = "CC_USE_ALPHA_ATLAS_" + name; var def = this.getDefine(key, passIdx); (isAlphaAtlas || def) && this.define(key, isAlphaAtlas); val.loaded || cc.assetManager.postLoadNative(val); } this._effect.setProperty(name, val, passIdx, directly); }, getProperty: function getProperty(name, passIdx) { "string" === typeof passIdx && (passIdx = parseInt(passIdx)); return this._effect.getProperty(name, passIdx); }, define: function define(name, val, passIdx, force) { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return; "string" === typeof passIdx && (passIdx = parseInt(passIdx)); this._effect.define(name, val, passIdx, force); }, getDefine: function getDefine(name, passIdx) { "string" === typeof passIdx && (passIdx = parseInt(passIdx)); return this._effect.getDefine(name, passIdx); }, setCullMode: function setCullMode(cullMode, passIdx) { void 0 === cullMode && (cullMode = gfx.CULL_BACK); this._effect.setCullMode(cullMode, passIdx); }, setDepth: function setDepth(depthTest, depthWrite, depthFunc, passIdx) { void 0 === depthTest && (depthTest = false); void 0 === depthWrite && (depthWrite = false); void 0 === depthFunc && (depthFunc = gfx.DS_FUNC_LESS); this._effect.setDepth(depthTest, depthWrite, depthFunc, passIdx); }, setBlend: function setBlend(enabled, blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor, passIdx) { void 0 === enabled && (enabled = false); void 0 === blendEq && (blendEq = gfx.BLEND_FUNC_ADD); void 0 === blendSrc && (blendSrc = gfx.BLEND_SRC_ALPHA); void 0 === blendDst && (blendDst = gfx.BLEND_ONE_MINUS_SRC_ALPHA); void 0 === blendAlphaEq && (blendAlphaEq = gfx.BLEND_FUNC_ADD); void 0 === blendSrcAlpha && (blendSrcAlpha = gfx.BLEND_SRC_ALPHA); void 0 === blendDstAlpha && (blendDstAlpha = gfx.BLEND_ONE_MINUS_SRC_ALPHA); void 0 === blendColor && (blendColor = 4294967295); this._effect.setBlend(enabled, blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor, passIdx); }, setStencilEnabled: function setStencilEnabled(stencilTest, passIdx) { void 0 === stencilTest && (stencilTest = gfx.STENCIL_INHERIT); this._effect.setStencilEnabled(stencilTest, passIdx); }, setStencil: function setStencil(stencilTest, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask, passIdx) { void 0 === stencilTest && (stencilTest = gfx.STENCIL_INHERIT); void 0 === stencilFunc && (stencilFunc = gfx.DS_FUNC_ALWAYS); void 0 === stencilRef && (stencilRef = 0); void 0 === stencilMask && (stencilMask = 255); void 0 === stencilFailOp && (stencilFailOp = gfx.STENCIL_OP_KEEP); void 0 === stencilZFailOp && (stencilZFailOp = gfx.STENCIL_OP_KEEP); void 0 === stencilZPassOp && (stencilZPassOp = gfx.STENCIL_OP_KEEP); void 0 === stencilWriteMask && (stencilWriteMask = 255); this._effect.setStencil(stencilTest, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask, passIdx); }, updateHash: function updateHash(hash) { this._manualHash = hash; this._effect && this._effect.updateHash(hash); }, getHash: function getHash() { return this._manualHash || this._effect && this._effect.getHash(); }, onLoad: function onLoad() { this.effectAsset = this._effectAsset; if (!this._effect) return; this._techniqueIndex && this._effect.switchTechnique(this._techniqueIndex); this._techniqueData = this._techniqueData || {}; var passDatas = this._techniqueData; for (var index in passDatas) { index = parseInt(index); var passData = passDatas[index]; if (!passData) continue; for (var def in passData.defines) this.define(def, passData.defines[def], index); for (var prop in passData.props) this.setProperty(prop, passData.props[prop], index); } this.updateMultiSupport(); this._multiHandler && this._multiHandler.syncTextures(); }, updateMultiSupport: function updateMultiSupport() { var passes = this._effect.technique.passes; passes.length > 0 && passes[0].getDefine("USE_MULTI_TEXTURE") ? this.setMultiSupport(true) : this.setMultiSupport(false); }, isMultiSupport: function isMultiSupport() { return !!this._multiHandler; }, setMultiSupport: function setMultiSupport(bool) { bool ? this._multiHandler ? this._multiHandler.syncTextures() : this._multiHandler = new cc.sp.MultiHandler(this) : bool || (this._multiHandler = null); }, getMultiHandler: function getMultiHandler() { return this._multiHandler; } }); var _default = Material; exports["default"] = _default; cc.Material = Material; module.exports = exports["default"]; }), { "../../utils/texture-util": 225, "../CCAsset": 57, "../CCTexture2D": 72, "./CCEffectAsset": 75 } ], 77: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _pass = _interopRequireDefault(require("../../../renderer/core/pass")); var _enums = _interopRequireDefault(require("../../../renderer/enums")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var gfx = cc.gfx; var EffectBase = (function() { function EffectBase() { this._dirty = true; this._name = ""; this._technique = null; } var _proto = EffectBase.prototype; _proto._createPassProp = function _createPassProp(name, pass) { var prop = pass._properties[name]; if (!prop) return; var uniform = Object.create(null); uniform.name = name; uniform.type = prop.type; prop.value instanceof Float32Array ? uniform.value = new Float32Array(prop.value) : prop.value instanceof Float64Array ? uniform.value = new Float64Array(prop.value) : uniform.value = prop.value; pass._properties[name] = uniform; return uniform; }; _proto._setPassProperty = function _setPassProperty(name, value, pass, directly) { var properties = pass._properties; properties.hasOwnProperty(name) || this._createPassProp(name, pass); var prop = properties[name]; var compareValue = value; prop.type === _enums["default"].PARAM_TEXTURE_2D && (compareValue = value && value.getImpl()); if (prop.value === compareValue) return true; this._dirty = true; return _pass["default"].prototype.setProperty.call(pass, name, value, directly); }; _proto.setProperty = function setProperty(name, value, passIdx, directly) { var success = false; var passes = this.passes; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) this._setPassProperty(name, value, passes[i], directly) && (success = true); success || cc.warnID(9103, this.name, name); }; _proto.getProperty = function getProperty(name, passIdx) { var passes = this.passes; if (passIdx >= passes.length) return; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) { var value = passes[i].getProperty(name); if (void 0 !== value) return value; } }; _proto.define = function define(name, value, passIdx, force) { var success = false; var passes = this.passes; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) passes[i].define(name, value, force) && (success = true); success || cc.warnID(9104, this.name, name); }; _proto.getDefine = function getDefine(name, passIdx) { var passes = this.passes; if (passIdx >= passes.length) return; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) { var value = passes[i].getDefine(name); if (void 0 !== value) return value; } }; _proto.setCullMode = function setCullMode(cullMode, passIdx) { void 0 === cullMode && (cullMode = gfx.CULL_BACK); var passes = this.passes; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) passes[i].setCullMode(cullMode); this._dirty = true; }; _proto.setDepth = function setDepth(depthTest, depthWrite, depthFunc, passIdx) { var passes = this.passes; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) passes[i].setDepth(depthTest, depthWrite, depthFunc); this._dirty = true; }; _proto.setBlend = function setBlend(enabled, blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor, passIdx) { var passes = this.passes; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) passes[i].setBlend(enabled, blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor); this._dirty = true; }; _proto.setStencilEnabled = function setStencilEnabled(stencilTest, passIdx) { void 0 === stencilTest && (stencilTest = gfx.STENCIL_INHERIT); var passes = this.passes; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) passes[i].setStencilEnabled(stencilTest); this._dirty = true; }; _proto.setStencil = function setStencil(enabled, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask, passIdx) { var passes = this.passes; var start = 0, end = passes.length; void 0 !== passIdx && (start = passIdx, end = passIdx + 1); for (var i = start; i < end; i++) { var pass = passes[i]; pass.setStencilFront(enabled, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask); pass.setStencilBack(enabled, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask); } this._dirty = true; }; _createClass(EffectBase, [ { key: "name", get: function get() { return this._name; } }, { key: "technique", get: function get() { return this._technique; } }, { key: "passes", get: function get() { return []; } } ]); return EffectBase; })(); exports["default"] = EffectBase; cc.EffectBase = EffectBase; module.exports = exports["default"]; }), { "../../../renderer/core/pass": 250, "../../../renderer/enums": 254 } ], 78: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.parseEffect = parseEffect; var _pass = _interopRequireDefault(require("../../../renderer/core/pass")); var _types = require("../../../renderer/types"); var _enums = _interopRequireDefault(require("../../../renderer/enums")); var _effect = _interopRequireDefault(require("./effect")); var _technique = _interopRequireDefault(require("../../../renderer/core/technique")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getInvolvedProgram(programName) { var lib = cc.renderer._forward._programLib; return lib.getTemplate(programName); } function parseProperties(effectAsset, passJson) { var propertiesJson = passJson.properties || {}; var program = getInvolvedProgram(passJson.program); var _loop = function _loop(prop) { var uniformInfo = program.uniforms.find((function(u) { return u.name === prop; })); if (!uniformInfo) { cc.warnID(9107, effectAsset.name, prop); return "continue"; } }; for (var prop in propertiesJson) { var _ret = _loop(prop); if ("continue" === _ret) continue; } var properties = {}; program.uniforms.forEach((function(u) { var name = u.name, prop = properties[name] = Object.assign({}, u), propInfo = propertiesJson[name]; var value; value = propInfo ? propInfo.type === _enums["default"].PARAM_TEXTURE_2D ? null : propInfo.type === _enums["default"].PARAM_INT || propInfo.type === _enums["default"].PARAM_FLOAT ? Array.isArray(propInfo.value) ? propInfo.value[0] : propInfo.value : new Float32Array(propInfo.value) : _types.enums2default[u.type]; void 0 === value && (value = null); prop.value = value; })); return properties; } function passDefines(pass) { var defines = {}; var program = getInvolvedProgram(pass.program); program.defines.forEach((function(d) { defines[d.name] = _types.enums2default[d.type]; })); return defines; } function parseTechniques(effectAsset) { var techNum = effectAsset.techniques.length; var techniques = new Array(techNum); for (var j = 0; j < techNum; ++j) { var tech = effectAsset.techniques[j]; var techName = tech.name || j; var passNum = tech.passes.length; var passes = new Array(passNum); for (var k = 0; k < passNum; ++k) { var pass = tech.passes[k]; var passName = pass.name || k; var detailName = effectAsset.name + "-" + techName + "-" + passName; var stage = pass.stage || "opaque"; var properties = parseProperties(effectAsset, pass); var defines = passDefines(pass); var newPass = passes[k] = new _pass["default"](passName, detailName, pass.program, stage, properties, defines); pass.rasterizerState && newPass.setCullMode(pass.rasterizerState.cullMode); var blendState = pass.blendState && pass.blendState.targets[0]; blendState && newPass.setBlend(blendState.blend, blendState.blendEq, blendState.blendSrc, blendState.blendDst, blendState.blendAlphaEq, blendState.blendSrcAlpha, blendState.blendDstAlpha, blendState.blendColor); var depthStencilState = pass.depthStencilState; if (depthStencilState) { newPass.setDepth(depthStencilState.depthTest, depthStencilState.depthWrite, depthStencilState.depthFunc); newPass.setStencilFront(depthStencilState.stencilTest, depthStencilState.stencilFuncFront, depthStencilState.stencilRefFront, depthStencilState.stencilMaskFront, depthStencilState.stencilFailOpFront, depthStencilState.stencilZFailOpFront, depthStencilState.stencilZPassOpFront, depthStencilState.stencilWriteMaskFront); newPass.setStencilBack(depthStencilState.stencilTest, depthStencilState.stencilFuncBack, depthStencilState.stencilRefBack, depthStencilState.stencilMaskBack, depthStencilState.stencilFailOpBack, depthStencilState.stencilZFailOpBack, depthStencilState.stencilZPassOpBack, depthStencilState.stencilWriteMaskBack); } } techniques[j] = new _technique["default"](techName, passes); } return techniques; } function parseEffect(effect) { var techniques = parseTechniques(effect); return new _effect["default"](effect.name, techniques, 0, effect); } false; }), { "../../../renderer/core/pass": 250, "../../../renderer/core/technique": 252, "../../../renderer/enums": 254, "../../../renderer/types": 282, "./effect": 80 } ], 79: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _murmurhash2_gc = _interopRequireDefault(require("../../../renderer/murmurhash2_gc")); var _utils = _interopRequireDefault(require("./utils")); var _effectBase = _interopRequireDefault(require("./effect-base")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var gfx = cc.gfx; var EffectVariant = (function(_EffectBase) { _inheritsLoose(EffectVariant, _EffectBase); function EffectVariant(effect) { var _this; _this = _EffectBase.call(this) || this; _this._effect = void 0; _this._passes = []; _this._stagePasses = {}; _this._hash = 0; _this.init(effect); return _this; } var _proto = EffectVariant.prototype; _proto._onEffectChanged = function _onEffectChanged() {}; _proto.init = function init(effect) { effect instanceof EffectVariant && (effect = effect.effect); this._effect = effect; this._dirty = true; if (effect) { var passes = effect.passes; var variantPasses = this._passes; variantPasses.length = 0; var stagePasses = this._stagePasses = {}; for (var i = 0; i < passes.length; i++) { var variant = variantPasses[i] = Object.setPrototypeOf({}, passes[i]); variant._properties = Object.setPrototypeOf({}, passes[i]._properties); variant._defines = Object.setPrototypeOf({}, passes[i]._defines); stagePasses[variant._stage] || (stagePasses[variant._stage] = []); stagePasses[variant._stage].push(variant); } } }; _proto.updateHash = function updateHash(hash) {}; _proto.getHash = function getHash() { if (!this._dirty) return this._hash; this._dirty = false; var hash = ""; hash += _utils["default"].serializePasses(this._passes); var effect = this._effect; effect && (hash += effect._id); this._hash = (0, _murmurhash2_gc["default"])(hash, 666); this.updateHash(this._hash); return this._hash; }; _createClass(EffectVariant, [ { key: "effect", get: function get() { return this._effect; } }, { key: "name", get: function get() { return this._effect && this._effect.name + " (variant)"; } }, { key: "passes", get: function get() { return this._passes; } }, { key: "stagePasses", get: function get() { return this._stagePasses; } } ]); return EffectVariant; })(_effectBase["default"]); exports["default"] = EffectVariant; cc.EffectVariant = EffectVariant; module.exports = exports["default"]; }), { "../../../renderer/murmurhash2_gc": 277, "./effect-base": 77, "./utils": 84 } ], 80: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _effectBase = _interopRequireDefault(require("./effect-base")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Effect = (function(_EffectBase) { _inheritsLoose(Effect, _EffectBase); function Effect(name, techniques, techniqueIndex, asset) { var _this; _this = _EffectBase.call(this) || this; _this._techniques = []; _this._asset = null; _this._id = ""; _this.init(name, techniques, techniqueIndex, asset, true); _this._id = "|" + Effect.id++; return _this; } var _proto = Effect.prototype; _proto.init = function init(name, techniques, techniqueIndex, asset, createNative) { this._name = name; this._techniques = techniques; this._technique = techniques[techniqueIndex]; this._asset = asset; }; _proto.switchTechnique = function switchTechnique(index) { if (index >= this._techniques.length) { cc.warn("Can not switch to technique with index [" + index + "]"); return; } this._technique = this._techniques[index]; }; _proto.clear = function clear() { this._techniques = []; }; _proto.clone = function clone() { var techniques = []; for (var i = 0; i < this._techniques.length; i++) techniques.push(this._techniques[i].clone()); var techniqueIndex = this._techniques.indexOf(this._technique); return new Effect(this._name, techniques, techniqueIndex, this._asset); }; _createClass(Effect, [ { key: "technique", get: function get() { return this._technique; } }, { key: "passes", get: function get() { return this._technique.passes; } } ]); return Effect; })(_effectBase["default"]); exports["default"] = Effect; Effect.id = 0; cc.Effect = Effect; module.exports = exports["default"]; }), { "./effect-base": 77 } ], 81: [ (function(require, module, exports) { "use strict"; require("./CCEffectAsset"); require("./CCMaterial"); require("./material-variant"); }), { "./CCEffectAsset": 75, "./CCMaterial": 76, "./material-variant": 83 } ], 82: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _utils = _interopRequireDefault(require("./utils")); var _pool = _interopRequireDefault(require("../../utils/pool")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MaterialPool = (function(_Pool) { _inheritsLoose(MaterialPool, _Pool); function MaterialPool() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; _this = _Pool.call.apply(_Pool, [ this ].concat(args)) || this; _this.enabled = false; _this._pool = {}; return _this; } var _proto = MaterialPool.prototype; _proto.get = function get(exampleMat, renderComponent) { var pool = this._pool; if (exampleMat instanceof cc.MaterialVariant) { if (!exampleMat._owner) { exampleMat._owner = renderComponent; return exampleMat; } if (exampleMat._owner === renderComponent) return exampleMat; exampleMat = exampleMat.material; } var instance; if (this.enabled) { var uuid = exampleMat.effectAsset._uuid; if (pool[uuid]) { var key = _utils["default"].serializeDefines(exampleMat._effect._defines) + _utils["default"].serializeTechniques(exampleMat._effect._techniques); instance = pool[uuid][key] && pool[uuid][key].pop(); } } if (instance) this.count--; else { instance = new cc.MaterialVariant(exampleMat); instance._name = exampleMat._name + " (Instance)"; instance._uuid = exampleMat._uuid; } instance._owner = renderComponent; return instance; }; _proto.put = function put(mat) { if (!this.enabled || !mat._owner) return; var pool = this._pool; var uuid = mat.effectAsset._uuid; pool[uuid] || (pool[uuid] = {}); var key = _utils["default"].serializeDefines(mat._effect._defines) + _utils["default"].serializeTechniques(mat._effect._techniques); pool[uuid][key] || (pool[uuid][key] = []); if (this.count > this.maxSize) return; this._clean(mat); pool[uuid][key].push(mat); this.count++; }; _proto.clear = function clear() { this._pool = {}; this.count = 0; }; _proto._clean = function _clean(mat) { mat._owner = null; }; return MaterialPool; })(_pool["default"]); var materialPool = new MaterialPool(); _pool["default"].register("material", materialPool); var _default = materialPool; exports["default"] = _default; module.exports = exports["default"]; }), { "../../utils/pool": 219, "./utils": 84 } ], 83: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _CCMaterial = _interopRequireDefault(require("./CCMaterial")); var _effectVariant = _interopRequireDefault(require("./effect-variant")); var _materialPool = _interopRequireDefault(require("./material-pool")); var _dec, _class; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var ccclass = cc._decorator.ccclass; var MaterialVariant = (_dec = ccclass("cc.MaterialVariant"), _dec(_class = (function(_Material) { _inheritsLoose(MaterialVariant, _Material); MaterialVariant.createWithBuiltin = function createWithBuiltin(materialName, owner) { return MaterialVariant.create(_CCMaterial["default"].getBuiltinMaterial(materialName), owner); }; MaterialVariant.create = function create(material, owner) { if (!material) return null; return _materialPool["default"].get(material, owner); }; function MaterialVariant(material) { var _this; _this = _Material.call(this) || this; _this._owner = null; _this._material = null; _this.init(material); return _this; } var _proto = MaterialVariant.prototype; _proto.init = function init(material) { this._effect = new _effectVariant["default"](material.effect); this._effectAsset = material._effectAsset; this._material = material; }; _createClass(MaterialVariant, [ { key: "uuid", get: function get() { return this._material._uuid; } }, { key: "owner", get: function get() { return this._owner; } }, { key: "material", get: function get() { return this._material; } } ]); return MaterialVariant; })(_CCMaterial["default"])) || _class); exports["default"] = MaterialVariant; cc.MaterialVariant = MaterialVariant; module.exports = exports["default"]; }), { "./CCMaterial": 76, "./effect-variant": 79, "./material-pool": 82 } ], 84: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _enums = _interopRequireDefault(require("../../../renderer/enums")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var hashArray = []; function serializeDefines(defines, names) { var i = 0; for (var name in defines) if (Object.hasOwnProperty.call(defines, name)) { hashArray[i] = name + defines[name]; i++; } hashArray.length = i; return hashArray.join(""); } function serializePass(pass, excludeProperties) { var str = pass._programName + pass._cullMode; pass._blend && (str += pass._blendEq + pass._blendAlphaEq + pass._blendSrc + pass._blendDst + pass._blendSrcAlpha + pass._blendDstAlpha + pass._blendColor); pass._depthTest && (str += pass._depthWrite + pass._depthFunc); pass._stencilTest && (str += pass._stencilFuncFront + pass._stencilRefFront + pass._stencilMaskFront + pass._stencilFailOpFront + pass._stencilZFailOpFront + pass._stencilZPassOpFront + pass._stencilWriteMaskFront + pass._stencilFuncBack + pass._stencilRefBack + pass._stencilMaskBack + pass._stencilFailOpBack + pass._stencilZFailOpBack + pass._stencilZPassOpBack + pass._stencilWriteMaskBack); excludeProperties || (str += serializeUniforms(pass._properties, pass._propertyNames)); str += serializeDefines(pass._defines, pass._defineNames); return str; } function serializePasses(passes) { var hashData = ""; for (var i = 0; i < passes.length; i++) hashData += serializePass(passes[i]); return hashData; } function serializeUniforms(uniforms, names) { var index = 0; for (var name in uniforms) if (Object.hasOwnProperty.call(uniforms, name)) { var param = uniforms[name]; var prop = param.value; if (!prop) continue; param.type === _enums["default"].PARAM_TEXTURE_2D || param.type === _enums["default"].PARAM_TEXTURE_CUBE ? hashArray[index] = prop._id : hashArray[index] = prop.toString(); index++; } hashArray.length = index; return hashArray.join(";"); } var _default = { serializeDefines: serializeDefines, serializePasses: serializePasses, serializeUniforms: serializeUniforms }; exports["default"] = _default; module.exports = exports["default"]; }), { "../../../renderer/enums": 254 } ], 85: [ (function(require, module, exports) { "use strict"; var Event; true; Event = require("../CCNode").EventType; var TOP = 1; var MID = 2; var BOT = 4; var LEFT = 8; var CENTER = 16; var RIGHT = 32; var HORIZONTAL = LEFT | CENTER | RIGHT; var VERTICAL = TOP | MID | BOT; var AlignMode = cc.Enum({ ONCE: 0, ON_WINDOW_RESIZE: 1, ALWAYS: 2 }); function getReadonlyNodeSize(parent) { return parent instanceof cc.Scene ? cc.visibleRect : parent._contentSize; } function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseScale) { var scaleX = widgetNode._parent.scaleX; var scaleY = widgetNode._parent.scaleY; var translateX = 0; var translateY = 0; for (var node = widgetNode._parent; ;) { translateX += node.x; translateY += node.y; node = node._parent; if (!node) { out_inverseTranslate.x = out_inverseTranslate.y = 0; out_inverseScale.x = out_inverseScale.y = 1; return; } if (node === target) break; var sx = node.scaleX; var sy = node.scaleY; translateX *= sx; translateY *= sy; scaleX *= sx; scaleY *= sy; } out_inverseScale.x = 0 !== scaleX ? 1 / scaleX : 1; out_inverseScale.y = 0 !== scaleY ? 1 / scaleY : 1; out_inverseTranslate.x = -translateX; out_inverseTranslate.y = -translateY; } var tInverseTranslate = cc.Vec2.ZERO; var tInverseScale = cc.Vec2.ONE; function align(node, widget) { var hasTarget = widget._target; var target; var inverseTranslate, inverseScale; if (hasTarget) { target = hasTarget; inverseTranslate = tInverseTranslate; inverseScale = tInverseScale; computeInverseTransForTarget(node, target, inverseTranslate, inverseScale); } else target = node._parent; var targetSize = getReadonlyNodeSize(target); var targetAnchor = target._anchorPoint; var isRoot = (true, target instanceof cc.Scene); var x = node.x, y = node.y; var anchor = node._anchorPoint; if (widget._alignFlags & HORIZONTAL) { var localLeft, localRight, targetWidth = targetSize.width; if (isRoot) { localLeft = cc.visibleRect.left.x; localRight = cc.visibleRect.right.x; } else { localLeft = -targetAnchor.x * targetWidth; localRight = localLeft + targetWidth; } localLeft += widget._isAbsLeft ? widget._left : widget._left * targetWidth; localRight -= widget._isAbsRight ? widget._right : widget._right * targetWidth; if (hasTarget) { localLeft += inverseTranslate.x; localLeft *= inverseScale.x; localRight += inverseTranslate.x; localRight *= inverseScale.x; } var width, anchorX = anchor.x, scaleX = node.scaleX; if (scaleX < 0) { anchorX = 1 - anchorX; scaleX = -scaleX; } if (widget.isStretchWidth) { width = localRight - localLeft; 0 !== scaleX && (node.width = width / scaleX); x = localLeft + anchorX * width; } else { width = node.width * scaleX; if (widget.isAlignHorizontalCenter) { var localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * targetWidth; var targetCenter = (.5 - targetAnchor.x) * targetSize.width; if (hasTarget) { localHorizontalCenter *= inverseScale.x; targetCenter += inverseTranslate.x; targetCenter *= inverseScale.x; } x = targetCenter + (anchorX - .5) * width + localHorizontalCenter; } else x = widget.isAlignLeft ? localLeft + anchorX * width : localRight + (anchorX - 1) * width; } } if (widget._alignFlags & VERTICAL) { var localTop, localBottom, targetHeight = targetSize.height; if (isRoot) { localBottom = cc.visibleRect.bottom.y; localTop = cc.visibleRect.top.y; } else { localBottom = -targetAnchor.y * targetHeight; localTop = localBottom + targetHeight; } localBottom += widget._isAbsBottom ? widget._bottom : widget._bottom * targetHeight; localTop -= widget._isAbsTop ? widget._top : widget._top * targetHeight; if (hasTarget) { localBottom += inverseTranslate.y; localBottom *= inverseScale.y; localTop += inverseTranslate.y; localTop *= inverseScale.y; } var height, anchorY = anchor.y, scaleY = node.scaleY; if (scaleY < 0) { anchorY = 1 - anchorY; scaleY = -scaleY; } if (widget.isStretchHeight) { height = localTop - localBottom; 0 !== scaleY && (node.height = height / scaleY); y = localBottom + anchorY * height; } else { height = node.height * scaleY; if (widget.isAlignVerticalCenter) { var localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * targetHeight; var targetMiddle = (.5 - targetAnchor.y) * targetSize.height; if (hasTarget) { localVerticalCenter *= inverseScale.y; targetMiddle += inverseTranslate.y; targetMiddle *= inverseScale.y; } y = targetMiddle + (anchorY - .5) * height + localVerticalCenter; } else y = widget.isAlignBottom ? localBottom + anchorY * height : localTop + (anchorY - 1) * height; } } node.setPosition(x, y); } function visitNode(node) { var widget = node._widget; if (widget) { false; align(node, widget); true, widget.alignMode !== AlignMode.ALWAYS ? widgetManager.remove(widget) : activeWidgets.push(widget); } var children = node._children; for (var i = 0; i < children.length; i++) { var child = children[i]; child._active && visitNode(child); } } var animationState; false; function refreshScene() { var AnimUtils; var EditMode; var nowPreviewing; var component; var animation; var _component; var _animation; false; var scene = cc.director.getScene(); if (scene) { widgetManager.isAligning = true; if (widgetManager._nodesOrderDirty) { activeWidgets.length = 0; visitNode(scene); widgetManager._nodesOrderDirty = false; } else { var i, widget, iterator = widgetManager._activeWidgetsIterator; var AnimUtils; var editingNode; var node; false; for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) { widget = activeWidgets[iterator.i]; align(widget.node, widget); } } widgetManager.isAligning = false; } false; } var adjustWidgetToAllowMovingInEditor = false; var adjustWidgetToAllowResizingInEditor = false; var activeWidgets = []; function updateAlignment(node) { var parent = node._parent; cc.Node.isNode(parent) && updateAlignment(parent); var widget = node._widget || node.getComponent(cc.Widget); widget && parent && align(node, widget); } var widgetManager = cc._widgetManager = module.exports = { _AlignFlags: { TOP: TOP, MID: MID, BOT: BOT, LEFT: LEFT, CENTER: CENTER, RIGHT: RIGHT }, isAligning: false, _nodesOrderDirty: false, _activeWidgetsIterator: new cc.js.array.MutableForwardIterator(activeWidgets), init: function init(director) { director.on(cc.Director.EVENT_AFTER_UPDATE, refreshScene); false; var thisOnResized = this.onResized.bind(this); cc.view.on("canvas-resize", thisOnResized); window.addEventListener("orientationchange", thisOnResized); }, add: function add(widget) { widget.node._widget = widget; this._nodesOrderDirty = true; false; }, remove: function remove(widget) { widget.node._widget = null; this._activeWidgetsIterator.remove(widget); false; }, onResized: function onResized() { var scene = cc.director.getScene(); scene && this.refreshWidgetOnResized(scene); }, refreshWidgetOnResized: function refreshWidgetOnResized(node) { var widget = cc.Node.isNode(node) && node.getComponent(cc.Widget); widget && widget.enabled && widget.alignMode === AlignMode.ON_WINDOW_RESIZE && this.add(widget); var children = node._children; for (var i = 0; i < children.length; i++) { var child = children[i]; this.refreshWidgetOnResized(child); } }, updateAlignment: updateAlignment, AlignMode: AlignMode }; false; }), { "../CCNode": 24 } ], 86: [ (function(require, module, exports) { "use strict"; var _valueTypes = require("../value-types"); var _geomUtils = require("../geom-utils"); var AffineTrans = require("../utils/affine-transform"); var renderer = require("../renderer/index"); var RenderFlow = require("../renderer/render-flow"); var game = require("../CCGame"); var RendererCamera = null; false; RendererCamera = require("../../renderer/scene/camera"); var _mat4_temp_1 = cc.mat4(); var _mat4_temp_2 = cc.mat4(); var _v3_temp_1 = cc.v3(); var _v3_temp_2 = cc.v3(); var _v3_temp_3 = cc.v3(); var _cameras = []; function updateMainCamera() { for (var i = 0, minDepth = Number.MAX_VALUE; i < _cameras.length; i++) { var camera = _cameras[i]; if (camera._depth < minDepth) { Camera.main = camera; minDepth = camera._depth; } } } var _debugCamera = null; function repositionDebugCamera() { if (!_debugCamera) return; var node = _debugCamera.getNode(); var canvas = cc.game.canvas; node.z = canvas.height / 1.1566; node.x = canvas.width / 2; node.y = canvas.height / 2; } var ClearFlags = cc.Enum({ COLOR: 1, DEPTH: 2, STENCIL: 4 }); var StageFlags = cc.Enum({ OPAQUE: 1, TRANSPARENT: 2 }); var Camera = cc.Class({ name: "cc.Camera", extends: cc.Component, ctor: function ctor() { if (game.renderType !== game.RENDER_TYPE_CANVAS) { var camera = new RendererCamera(); camera.setStages([ "opaque" ]); camera.dirty = true; this._inited = false; this._camera = camera; } else this._inited = true; }, editor: false, properties: { _cullingMask: 4294967295, _clearFlags: ClearFlags.DEPTH | ClearFlags.STENCIL, _backgroundColor: cc.color(0, 0, 0, 255), _depth: 0, _zoomRatio: 1, _targetTexture: null, _fov: 60, _orthoSize: 10, _nearClip: 1, _farClip: 4096, _ortho: true, _rect: cc.rect(0, 0, 1, 1), _renderStages: 1, _alignWithScreen: true, zoomRatio: { get: function get() { return this._zoomRatio; }, set: function set(value) { this._zoomRatio = value; }, tooltip: false }, fov: { get: function get() { return this._fov; }, set: function set(v) { this._fov = v; }, tooltip: false }, orthoSize: { get: function get() { return this._orthoSize; }, set: function set(v) { this._orthoSize = v; }, tooltip: false }, nearClip: { get: function get() { return this._nearClip; }, set: function set(v) { this._nearClip = v; this._updateClippingpPlanes(); }, tooltip: false }, farClip: { get: function get() { return this._farClip; }, set: function set(v) { this._farClip = v; this._updateClippingpPlanes(); }, tooltip: false }, ortho: { get: function get() { return this._ortho; }, set: function set(v) { this._ortho = v; this._updateProjection(); }, tooltip: false }, rect: { get: function get() { return this._rect; }, set: function set(v) { this._rect = v; this._updateRect(); }, tooltip: false }, cullingMask: { get: function get() { return this._cullingMask; }, set: function set(value) { this._cullingMask = value; this._updateCameraMask(); }, tooltip: false }, clearFlags: { get: function get() { return this._clearFlags; }, set: function set(value) { this._clearFlags = value; this._camera && this._camera.setClearFlags(value); }, tooltip: false }, backgroundColor: { get: function get() { return this._backgroundColor; }, set: function set(value) { if (!this._backgroundColor.equals(value)) { this._backgroundColor.set(value); this._updateBackgroundColor(); } }, tooltip: false }, depth: { get: function get() { return this._depth; }, set: function set(value) { Camera.main === this ? this._depth < value && updateMainCamera() : Camera.main && value < Camera.main._depth && _cameras.includes(this) && (Camera.main = this); this._depth = value; this._camera && this._camera.setPriority(value); }, tooltip: false }, targetTexture: { get: function get() { return this._targetTexture; }, set: function set(value) { this._targetTexture = value; this._updateTargetTexture(); }, tooltip: false }, renderStages: { get: function get() { return this._renderStages; }, set: function set(val) { this._renderStages = val; this._updateStages(); }, tooltip: false }, alignWithScreen: { get: function get() { return this._alignWithScreen; }, set: function set(v) { this._alignWithScreen = v; } }, _is3D: { get: function get() { return this.node && this.node._is3DNode; } } }, statics: { main: null, cameras: _cameras, ClearFlags: ClearFlags, findCamera: function findCamera(node) { for (var i = 0, l = _cameras.length; i < l; i++) { var camera = _cameras[i]; if (camera.containsNode(node)) return camera; } return null; }, _findRendererCamera: function _findRendererCamera(node) { var cameras = renderer.scene._cameras; for (var i = 0; i < cameras._count; i++) if (cameras._data[i]._cullingMask & node._cullingMask) return cameras._data[i]; return null; }, _setupDebugCamera: function _setupDebugCamera() { if (_debugCamera) return; if (game.renderType === game.RENDER_TYPE_CANVAS) return; var camera = new RendererCamera(); _debugCamera = camera; camera.setStages([ "opaque" ]); camera.setFov(60 * Math.PI / 180); camera.setNear(.1); camera.setFar(4096); camera.dirty = true; camera.cullingMask = 1 << cc.Node.BuiltinGroupIndex.DEBUG; camera.setPriority(cc.macro.MAX_ZINDEX); camera.setClearFlags(0); camera.setColor(0, 0, 0, 0); var node = new cc.Node(); camera.setNode(node); repositionDebugCamera(); cc.view.on("design-resolution-changed", repositionDebugCamera); renderer.scene.addCamera(camera); } }, _updateCameraMask: function _updateCameraMask() { if (this._camera) { var mask = this._cullingMask & ~(1 << cc.Node.BuiltinGroupIndex.DEBUG); this._camera.cullingMask = mask; } }, _updateBackgroundColor: function _updateBackgroundColor() { if (!this._camera) return; var color = this._backgroundColor; this._camera.setColor(color.r / 255, color.g / 255, color.b / 255, color.a / 255); }, _updateTargetTexture: function _updateTargetTexture() { if (!this._camera) return; var texture = this._targetTexture; this._camera.setFrameBuffer(texture ? texture._framebuffer : null); }, _updateClippingpPlanes: function _updateClippingpPlanes() { if (!this._camera) return; this._camera.setNear(this._nearClip); this._camera.setFar(this._farClip); }, _updateProjection: function _updateProjection() { if (!this._camera) return; var type = this._ortho ? 1 : 0; this._camera.setType(type); }, _updateRect: function _updateRect() { if (!this._camera) return; var rect = this._rect; this._camera.setRect(rect.x, rect.y, rect.width, rect.height); }, _updateStages: function _updateStages() { var flags = this._renderStages; var stages = []; flags & StageFlags.OPAQUE && stages.push("opaque"); flags & StageFlags.TRANSPARENT && stages.push("transparent"); this._camera.setStages(stages); }, _init: function _init() { if (this._inited) return; this._inited = true; var camera = this._camera; if (!camera) return; camera.setNode(this.node); camera.setClearFlags(this._clearFlags); camera.setPriority(this._depth); this._updateBackgroundColor(); this._updateCameraMask(); this._updateTargetTexture(); this._updateClippingpPlanes(); this._updateProjection(); this._updateStages(); this._updateRect(); true; this.beforeDraw(); }, __preload: function __preload() { this._init(); }, onEnable: function onEnable() { if (true, game.renderType !== game.RENDER_TYPE_CANVAS) { cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); renderer.scene.addCamera(this._camera); } _cameras.push(this); (!Camera.main || this._depth < Camera.main._depth) && (Camera.main = this); }, onDisable: function onDisable() { if (true, game.renderType !== game.RENDER_TYPE_CANVAS) { cc.director.off(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); renderer.scene.removeCamera(this._camera); } cc.js.array.fastRemove(_cameras, this); if (Camera.main === this) { Camera.main = null; updateMainCamera(); } }, getScreenToWorldMatrix2D: function getScreenToWorldMatrix2D(out) { this.getWorldToScreenMatrix2D(out); _valueTypes.Mat4.invert(out, out); return out; }, getWorldToScreenMatrix2D: function getWorldToScreenMatrix2D(out) { this.node.getWorldRT(_mat4_temp_1); var zoomRatio = this.zoomRatio; var _mat4_temp_1m = _mat4_temp_1.m; _mat4_temp_1m[0] *= zoomRatio; _mat4_temp_1m[1] *= zoomRatio; _mat4_temp_1m[4] *= zoomRatio; _mat4_temp_1m[5] *= zoomRatio; var m12 = _mat4_temp_1m[12]; var m13 = _mat4_temp_1m[13]; var center = cc.visibleRect.center; _mat4_temp_1m[12] = center.x - (_mat4_temp_1m[0] * m12 + _mat4_temp_1m[4] * m13); _mat4_temp_1m[13] = center.y - (_mat4_temp_1m[1] * m12 + _mat4_temp_1m[5] * m13); out !== _mat4_temp_1 && _valueTypes.Mat4.copy(out, _mat4_temp_1); return out; }, getScreenToWorldPoint: function getScreenToWorldPoint(screenPosition, out) { if (this.node.is3DNode) { out = out || new cc.Vec3(); this._camera.screenToWorld(out, screenPosition, cc.visibleRect.width, cc.visibleRect.height); } else { out = out || new cc.Vec2(); this.getScreenToWorldMatrix2D(_mat4_temp_1); _valueTypes.Vec2.transformMat4(out, screenPosition, _mat4_temp_1); } return out; }, getWorldToScreenPoint: function getWorldToScreenPoint(worldPosition, out) { if (this.node.is3DNode) { out = out || new cc.Vec3(); this._camera.worldToScreen(out, worldPosition, cc.visibleRect.width, cc.visibleRect.height); } else { out = out || new cc.Vec2(); this.getWorldToScreenMatrix2D(_mat4_temp_1); _valueTypes.Vec2.transformMat4(out, worldPosition, _mat4_temp_1); } return out; }, getRay: function getRay(screenPos) { if (!cc.geomUtils) return screenPos; _valueTypes.Vec3.set(_v3_temp_3, screenPos.x, screenPos.y, 1); this._camera.screenToWorld(_v3_temp_2, _v3_temp_3, cc.visibleRect.width, cc.visibleRect.height); if (this.ortho) { _valueTypes.Vec3.set(_v3_temp_3, screenPos.x, screenPos.y, -1); this._camera.screenToWorld(_v3_temp_1, _v3_temp_3, cc.visibleRect.width, cc.visibleRect.height); } else this.node.getWorldPosition(_v3_temp_1); return _geomUtils.Ray.fromPoints(new _geomUtils.Ray(), _v3_temp_1, _v3_temp_2); }, containsNode: function containsNode(node) { return (node._cullingMask & this.cullingMask) > 0; }, render: function render(rootNode) { rootNode = rootNode || cc.director.getScene(); if (!rootNode) return null; this.node.getWorldMatrix(_mat4_temp_1); this.beforeDraw(); RenderFlow.renderCamera(this._camera, rootNode); }, _onAlignWithScreen: function _onAlignWithScreen() { var height = cc.game.canvas.height / cc.view._scaleY; var targetTexture = this._targetTexture; if (targetTexture) { false; height = cc.visibleRect.height; } var fov = this._fov * cc.macro.RAD; this.node.z = height / (2 * Math.tan(fov / 2)); fov = 2 * Math.atan(Math.tan(fov / 2) / this.zoomRatio); this._camera.setFov(fov); this._camera.setOrthoHeight(height / 2 / this.zoomRatio); this.node.setRotation(0, 0, 0, 1); }, beforeDraw: function beforeDraw() { if (!this._camera) return; if (this._alignWithScreen) this._onAlignWithScreen(); else { var fov = this._fov * cc.macro.RAD; fov = 2 * Math.atan(Math.tan(fov / 2) / this.zoomRatio); this._camera.setFov(fov); this._camera.setOrthoHeight(this._orthoSize / this.zoomRatio); } this._camera.dirty = true; } }); cc.js.mixin(Camera.prototype, { getNodeToCameraTransform: function getNodeToCameraTransform(node) { var out = AffineTrans.identity(); node.getWorldMatrix(_mat4_temp_2); if (this.containsNode(node)) { this.getWorldToCameraMatrix(_mat4_temp_1); _valueTypes.Mat4.mul(_mat4_temp_2, _mat4_temp_2, _mat4_temp_1); } AffineTrans.fromMat4(out, _mat4_temp_2); return out; }, getCameraToWorldPoint: function getCameraToWorldPoint(point, out) { return this.getScreenToWorldPoint(point, out); }, getWorldToCameraPoint: function getWorldToCameraPoint(point, out) { return this.getWorldToScreenPoint(point, out); }, getCameraToWorldMatrix: function getCameraToWorldMatrix(out) { return this.getScreenToWorldMatrix2D(out); }, getWorldToCameraMatrix: function getWorldToCameraMatrix(out) { return this.getWorldToScreenMatrix2D(out); } }); module.exports = cc.Camera = Camera; }), { "../../renderer/scene/camera": 279, "../CCGame": 23, "../geom-utils": void 0, "../renderer/index": 160, "../renderer/render-flow": 161, "../utils/affine-transform": 208, "../value-types": 232 } ], 87: [ (function(require, module, exports) { "use strict"; require("./platform/CCClass"); var Flags = require("./platform/CCObject").Flags; var jsArray = require("./platform/js").array; var IsStartCalled = Flags.IsStartCalled; var IsOnEnableCalled = Flags.IsOnEnableCalled; var IsEditorOnEnableCalled = Flags.IsEditorOnEnableCalled; var callerFunctor = false; var callOnEnableInTryCatch = false; var callOnDisableInTryCatch = false; function sortedIndex(array, comp) { var order = comp.constructor._executionOrder; var id = comp._id; for (var l = 0, h = array.length - 1, m = h >>> 1; l <= h; m = l + h >>> 1) { var test = array[m]; var testOrder = test.constructor._executionOrder; if (testOrder > order) h = m - 1; else if (testOrder < order) l = m + 1; else { var testId = test._id; if (testId > id) h = m - 1; else { if (!(testId < id)) return m; l = m + 1; } } } return ~l; } function stableRemoveInactive(iterator, flagToClear) { var array = iterator.array; var next = iterator.i + 1; while (next < array.length) { var comp = array[next]; if (comp._enabled && comp.node && comp.node._activeInHierarchy) ++next; else { iterator.removeAt(next); flagToClear && (comp._objFlags &= ~flagToClear); } } } var LifeCycleInvoker = cc.Class({ __ctor__: function __ctor__(invokeFunc) { var Iterator = jsArray.MutableForwardIterator; this._zero = new Iterator([]); this._neg = new Iterator([]); this._pos = new Iterator([]); false; this._invoke = invokeFunc; }, statics: { stableRemoveInactive: stableRemoveInactive }, add: null, remove: null, invoke: null }); function compareOrder(a, b) { return a.constructor._executionOrder - b.constructor._executionOrder; } var OneOffInvoker = cc.Class({ extends: LifeCycleInvoker, add: function add(comp) { var order = comp.constructor._executionOrder; (0 === order ? this._zero : order < 0 ? this._neg : this._pos).array.push(comp); }, remove: function remove(comp) { var order = comp.constructor._executionOrder; (0 === order ? this._zero : order < 0 ? this._neg : this._pos).fastRemove(comp); }, cancelInactive: function cancelInactive(flagToClear) { stableRemoveInactive(this._zero, flagToClear); stableRemoveInactive(this._neg, flagToClear); stableRemoveInactive(this._pos, flagToClear); }, invoke: function invoke() { var compsNeg = this._neg; if (compsNeg.array.length > 0) { compsNeg.array.sort(compareOrder); this._invoke(compsNeg); compsNeg.array.length = 0; } this._invoke(this._zero); this._zero.array.length = 0; var compsPos = this._pos; if (compsPos.array.length > 0) { compsPos.array.sort(compareOrder); this._invoke(compsPos); compsPos.array.length = 0; } } }); var ReusableInvoker = cc.Class({ extends: LifeCycleInvoker, add: function add(comp) { var order = comp.constructor._executionOrder; if (0 === order) this._zero.array.push(comp); else { var array = order < 0 ? this._neg.array : this._pos.array; var i = sortedIndex(array, comp); i < 0 && array.splice(~i, 0, comp); } }, remove: function remove(comp) { var order = comp.constructor._executionOrder; if (0 === order) this._zero.fastRemove(comp); else { var iterator = order < 0 ? this._neg : this._pos; var i = sortedIndex(iterator.array, comp); i >= 0 && iterator.removeAt(i); } }, invoke: function invoke(dt) { this._neg.array.length > 0 && this._invoke(this._neg, dt); this._invoke(this._zero, dt); this._pos.array.length > 0 && this._invoke(this._pos, dt); } }); function enableInEditor(comp) { if (!(comp._objFlags & IsEditorOnEnableCalled)) { cc.engine.emit("component-enabled", comp.uuid); comp._objFlags |= IsEditorOnEnableCalled; } } function createInvokeImpl(indiePath, useDt, ensureFlag, fastPath) { true; var body = "var a=it.array;for(it.i=0;it.i= 0) { jsArray.fastRemoveAt(this._deferredComps, index); return; } !comp.start || comp._objFlags & IsStartCalled || this.startInvoker.remove(comp); comp.update && this.updateInvoker.remove(comp); comp.lateUpdate && this.lateUpdateInvoker.remove(comp); }, enableComp: function(comp, invoker) { if (!(comp._objFlags & IsOnEnableCalled)) { if (comp.onEnable) { if (invoker) { invoker.add(comp); return; } comp.onEnable(); var deactivatedDuringOnEnable = !comp.node._activeInHierarchy; if (deactivatedDuringOnEnable) return; } this._onEnabled(comp); } }, disableComp: function(comp) { if (comp._objFlags & IsOnEnableCalled) { comp.onDisable && comp.onDisable(); this._onDisabled(comp); } }, _scheduleImmediate: function _scheduleImmediate(comp) { "function" !== typeof comp.start || comp._objFlags & IsStartCalled || this.startInvoker.add(comp); "function" === typeof comp.update && this.updateInvoker.add(comp); "function" === typeof comp.lateUpdate && this.lateUpdateInvoker.add(comp); }, _deferredSchedule: function _deferredSchedule() { var comps = this._deferredComps; for (var i = 0, len = comps.length; i < len; i++) this._scheduleImmediate(comps[i]); comps.length = 0; }, _startForNewComps: function _startForNewComps() { if (this._deferredComps.length > 0) { this._deferredSchedule(); this.startInvoker.invoke(); } }, startPhase: function startPhase() { this._updating = true; this.startInvoker.invoke(); this._startForNewComps(); }, updatePhase: function updatePhase(dt) { this.updateInvoker.invoke(dt); }, lateUpdatePhase: function lateUpdatePhase(dt) { this.lateUpdateInvoker.invoke(dt); this._updating = false; this._startForNewComps(); } }); module.exports = ComponentScheduler; }), { "./platform/CCClass": 129, "./platform/CCObject": 135, "./platform/js": 150, "./utils/misc": 217 } ], 88: [ (function(require, module, exports) { "use strict"; var AnimationAnimator = require("../../animation/animation-animator"); var AnimationClip = require("../../animation/animation-clip"); var EventTarget = require("../event/event-target"); var js = require("../platform/js"); var equalClips = function(clip1, clip2) { return clip1 === clip2; }; var EventType = cc.Enum({ PLAY: "play", STOP: "stop", PAUSE: "pause", RESUME: "resume", LASTFRAME: "lastframe", FINISHED: "finished" }); var Animation = cc.Class({ name: "cc.Animation", extends: require("./CCComponent"), mixins: [ EventTarget ], editor: false, statics: { EventType: EventType }, ctor: function ctor() { cc.EventTarget.call(this); this._animator = null; this._nameToState = js.createMap(true); this._didInit = false; this._currentClip = null; }, properties: { _defaultClip: { default: null, type: AnimationClip }, defaultClip: { type: AnimationClip, get: function get() { return this._defaultClip; }, set: function set(value) { true; return; var contain; }, tooltip: false }, currentClip: { get: function get() { return this._currentClip; }, set: function set(value) { this._currentClip = value; }, type: AnimationClip, visible: false }, _writableClips: { get: function get() { return this._clips; }, set: function set(val) { this._didInit = false; this._clips = val; this._init(); }, type: [ AnimationClip ] }, _clips: { default: [], type: [ AnimationClip ], tooltip: false, visible: true }, playOnLoad: { default: false, tooltip: false } }, start: function start() { if ((true, this.playOnLoad) && this._defaultClip) { var isPlaying = this._animator && this._animator.isPlaying; if (!isPlaying) { var state = this.getAnimationState(this._defaultClip.name); this._animator.playState(state); } } }, onEnable: function onEnable() { this._animator && this._animator.resume(); }, onDisable: function onDisable() { this._animator && this._animator.pause(); }, onDestroy: function onDestroy() { this.stop(); }, getClips: function getClips() { return this._clips; }, play: function play(name, startTime) { var state = this.playAdditive(name, startTime); this._animator.stopStatesExcept(state); return state; }, playAdditive: function playAdditive(name, startTime) { this._init(); var state = this.getAnimationState(name || this._defaultClip && this._defaultClip.name); if (state) { this.enabled = true; var animator = this._animator; if (animator.isPlaying && state.isPlaying) if (state.isPaused) animator.resumeState(state); else { animator.stopState(state); animator.playState(state, startTime); } else animator.playState(state, startTime); this.enabledInHierarchy || animator.pause(); this.currentClip = state.clip; } return state; }, stop: function stop(name) { if (!this._didInit) return; if (name) { var state = this._nameToState[name]; state && this._animator.stopState(state); } else this._animator.stop(); }, pause: function pause(name) { if (!this._didInit) return; if (name) { var state = this._nameToState[name]; state && this._animator.pauseState(state); } else this.enabled = false; }, resume: function resume(name) { if (!this._didInit) return; if (name) { var state = this.getAnimationState(name); state && this._animator.resumeState(state); } else this.enabled = true; }, setCurrentTime: function setCurrentTime(time, name) { this._init(); if (name) { var state = this.getAnimationState(name); state && this._animator.setStateTime(state, time); } else this._animator.setStateTime(time); }, getAnimationState: function getAnimationState(name) { this._init(); var state = this._nameToState[name]; false; state && !state.curveLoaded && this._animator._reloadClip(state); return state || null; }, hasAnimationState: function hasAnimationState(name) { this._init(); return !!this._nameToState[name]; }, addClip: function addClip(clip, newName) { if (!clip) { cc.warnID(3900); return; } this._init(); cc.js.array.contains(this._clips, clip) || this._clips.push(clip); newName = newName || clip.name; var oldState = this._nameToState[newName]; if (oldState) { if (oldState.clip === clip) return oldState; var index = this._clips.indexOf(oldState.clip); -1 !== index && this._clips.splice(index, 1); } var newState = new cc.AnimationState(clip, newName); this._nameToState[newName] = newState; return newState; }, removeClip: function removeClip(clip, force) { if (!clip) { cc.warnID(3901); return; } this._init(); var state; for (var name in this._nameToState) { state = this._nameToState[name]; if (equalClips(state.clip, clip)) break; } if (clip === this._defaultClip) { if (!force) { true; cc.warnID(3902); return; } this._defaultClip = null; } if (state && state.isPlaying) { if (!force) { true; cc.warnID(3903); return; } this.stop(state.name); } this._clips = this._clips.filter((function(item) { return !equalClips(item, clip); })); state && delete this._nameToState[state.name]; }, sample: function sample(name) { this._init(); if (name) { var state = this.getAnimationState(name); state && state.sample(); } else this._animator.sample(); }, on: function on(type, callback, target, useCapture) { this._init(); var ret = this._EventTargetOn(type, callback, target, useCapture); if ("lastframe" === type) { var states = this._nameToState; for (var name in states) states[name]._lastframeEventOn = true; } return ret; }, off: function off(type, callback, target, useCapture) { this._init(); if ("lastframe" === type) { var states = this._nameToState; for (var name in states) states[name]._lastframeEventOn = false; } this._EventTargetOff(type, callback, target, useCapture); }, _init: function _init() { if (this._didInit) return; this._didInit = true; this._animator = new AnimationAnimator(this.node, this); this._createStates(); }, _createStates: function _createStates() { this._nameToState = js.createMap(true); var state = null; var defaultClipState = false; for (var i = 0; i < this._clips.length; ++i) { var clip = this._clips[i]; if (clip) { state = new cc.AnimationState(clip); false; this._nameToState[state.name] = state; equalClips(this._defaultClip, clip) && (defaultClipState = state); } } if (this._defaultClip && !defaultClipState) { state = new cc.AnimationState(this._defaultClip); false; this._nameToState[state.name] = state; } } }); Animation.prototype._EventTargetOn = EventTarget.prototype.on; Animation.prototype._EventTargetOff = EventTarget.prototype.off; cc.Animation = module.exports = Animation; }), { "../../animation/animation-animator": 10, "../../animation/animation-clip": 11, "../event/event-target": 119, "../platform/js": 150, "./CCComponent": 92 } ], 89: [ (function(require, module, exports) { "use strict"; var BlockEvents = [ "touchstart", "touchmove", "touchend", "mousedown", "mousemove", "mouseup", "mouseenter", "mouseleave", "mousewheel" ]; function stopPropagation(event) { event.stopPropagation(); } var BlockInputEvents = cc.Class({ name: "cc.BlockInputEvents", extends: require("./CCComponent"), editor: { menu: "i18n:MAIN_MENU.component.ui/Block Input Events", inspector: "packages://inspector/inspectors/comps/block-input-events.js", help: "i18n:COMPONENT.help_url.block_input_events" }, onEnable: function onEnable() { for (var i = 0; i < BlockEvents.length; i++) this.node.on(BlockEvents[i], stopPropagation, this); }, onDisable: function onDisable() { for (var i = 0; i < BlockEvents.length; i++) this.node.off(BlockEvents[i], stopPropagation, this); } }); cc.BlockInputEvents = module.exports = BlockInputEvents; }), { "./CCComponent": 92 } ], 90: [ (function(require, module, exports) { "use strict"; var Component = require("./CCComponent"); var GraySpriteState = require("../utils/gray-sprite-state"); var Transition = cc.Enum({ NONE: 0, COLOR: 1, SPRITE: 2, SCALE: 3 }); var State = cc.Enum({ NORMAL: 0, HOVER: 1, PRESSED: 2, DISABLED: 3 }); var Button = cc.Class({ name: "cc.Button", extends: Component, mixins: [ GraySpriteState ], ctor: function ctor() { this._pressed = false; this._hovered = false; this._fromColor = null; this._toColor = null; this._time = 0; this._transitionFinished = true; this._fromScale = cc.Vec2.ZERO; this._toScale = cc.Vec2.ZERO; this._originalScale = null; this._graySpriteMaterial = null; this._spriteMaterial = null; this._sprite = null; }, editor: false, properties: { interactable: { default: true, tooltip: false, notify: function notify() { this._updateState(); this.interactable || this._resetState(); }, animatable: false }, _resizeToTarget: { animatable: false, set: function set(value) { value && this._resizeNodeToTargetNode(); } }, enableAutoGrayEffect: { default: false, tooltip: false, notify: function notify() { this._updateDisabledState(true); } }, transition: { default: Transition.NONE, tooltip: false, type: Transition, animatable: false, notify: function notify(oldValue) { this._updateTransition(oldValue); }, formerlySerializedAs: "transition" }, normalColor: { default: cc.Color.WHITE, displayName: "Normal", tooltip: false, notify: function notify() { this.transition === Transition.Color && this._getButtonState() === State.NORMAL && (this._getTarget().opacity = this.normalColor.a); this._updateState(); } }, pressedColor: { default: cc.color(211, 211, 211), displayName: "Pressed", tooltip: false, notify: function notify() { this.transition === Transition.Color && this._getButtonState() === State.PRESSED && (this._getTarget().opacity = this.pressedColor.a); this._updateState(); }, formerlySerializedAs: "pressedColor" }, hoverColor: { default: cc.Color.WHITE, displayName: "Hover", tooltip: false, notify: function notify() { this.transition === Transition.Color && this._getButtonState() === State.HOVER && (this._getTarget().opacity = this.hoverColor.a); this._updateState(); }, formerlySerializedAs: "hoverColor" }, disabledColor: { default: cc.color(124, 124, 124), displayName: "Disabled", tooltip: false, notify: function notify() { this.transition === Transition.Color && this._getButtonState() === State.DISABLED && (this._getTarget().opacity = this.disabledColor.a); this._updateState(); } }, duration: { default: .1, range: [ 0, 10 ], tooltip: false }, zoomScale: { default: 1.2, tooltip: false }, normalSprite: { default: null, type: cc.SpriteFrame, displayName: "Normal", tooltip: false, notify: function notify() { this._updateState(); } }, pressedSprite: { default: null, type: cc.SpriteFrame, displayName: "Pressed", tooltip: false, formerlySerializedAs: "pressedSprite", notify: function notify() { this._updateState(); } }, hoverSprite: { default: null, type: cc.SpriteFrame, displayName: "Hover", tooltip: false, formerlySerializedAs: "hoverSprite", notify: function notify() { this._updateState(); } }, disabledSprite: { default: null, type: cc.SpriteFrame, displayName: "Disabled", tooltip: false, notify: function notify() { this._updateState(); } }, target: { default: null, type: cc.Node, tooltip: false, notify: function notify(oldValue) { this._applyTarget(); oldValue && this.target !== oldValue && this._unregisterTargetEvent(oldValue); } }, clickEvents: { default: [], type: cc.Component.EventHandler, tooltip: false } }, statics: { Transition: Transition }, __preload: function __preload() { this._applyTarget(); this._resetState(); }, _resetState: function _resetState() { this._pressed = false; this._hovered = false; var target = this._getTarget(); var transition = this.transition; var originalScale = this._originalScale; transition === Transition.COLOR && this.interactable ? this._setTargetColor(this.normalColor) : transition === Transition.SCALE && originalScale && target.setScale(originalScale.x, originalScale.y); this._transitionFinished = true; }, onEnable: function onEnable() { this.normalSprite && this.normalSprite.ensureLoadTexture(); this.hoverSprite && this.hoverSprite.ensureLoadTexture(); this.pressedSprite && this.pressedSprite.ensureLoadTexture(); this.disabledSprite && this.disabledSprite.ensureLoadTexture(); true; this._registerNodeEvent(); this._updateState(); }, onDisable: function onDisable() { this._resetState(); true; this._unregisterNodeEvent(); }, _getTarget: function _getTarget() { return this.target ? this.target : this.node; }, _onTargetSpriteFrameChanged: function _onTargetSpriteFrameChanged(comp) { this.transition === Transition.SPRITE && this._setCurrentStateSprite(comp.spriteFrame); }, _onTargetColorChanged: function _onTargetColorChanged(color) { this.transition === Transition.COLOR && this._setCurrentStateColor(color); }, _onTargetScaleChanged: function _onTargetScaleChanged() { var target = this._getTarget(); if (this._originalScale && (this.transition !== Transition.SCALE || this._transitionFinished)) { this._originalScale.x = target.scaleX; this._originalScale.y = target.scaleY; } }, _setTargetColor: function _setTargetColor(color) { var target = this._getTarget(); var cloneColor = color.clone(); target.opacity = cloneColor.a; cloneColor.a = 255; target.color = cloneColor; }, _getStateColor: function _getStateColor(state) { switch (state) { case State.NORMAL: return this.normalColor; case State.HOVER: return this.hoverColor; case State.PRESSED: return this.pressedColor; case State.DISABLED: return this.disabledColor; } }, _getStateSprite: function _getStateSprite(state) { switch (state) { case State.NORMAL: return this.normalSprite; case State.HOVER: return this.hoverSprite; case State.PRESSED: return this.pressedSprite; case State.DISABLED: return this.disabledSprite; } }, _setCurrentStateColor: function _setCurrentStateColor(color) { switch (this._getButtonState()) { case State.NORMAL: this.normalColor = color; break; case State.HOVER: this.hoverColor = color; break; case State.PRESSED: this.pressedColor = color; break; case State.DISABLED: this.disabledColor = color; } }, _setCurrentStateSprite: function _setCurrentStateSprite(spriteFrame) { switch (this._getButtonState()) { case State.NORMAL: this.normalSprite = spriteFrame; break; case State.HOVER: this.hoverSprite = spriteFrame; break; case State.PRESSED: this.pressedSprite = spriteFrame; break; case State.DISABLED: this.disabledSprite = spriteFrame; } }, update: function update(dt) { var target = this._getTarget(); if (this._transitionFinished) return; if (this.transition !== Transition.COLOR && this.transition !== Transition.SCALE) return; this.time += dt; var ratio = 1; this.duration > 0 && (ratio = this.time / this.duration); ratio >= 1 && (ratio = 1); if (this.transition === Transition.COLOR) { var color = this._fromColor.lerp(this._toColor, ratio); this._setTargetColor(color); } else this.transition === Transition.SCALE && this._originalScale && (target.scale = this._fromScale.lerp(this._toScale, ratio)); 1 === ratio && (this._transitionFinished = true); }, _registerNodeEvent: function _registerNodeEvent() { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this); this.node.on(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); }, _unregisterNodeEvent: function _unregisterNodeEvent() { this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this); this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this); this.node.off(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); this.node.off(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); }, _registerTargetEvent: function _registerTargetEvent(target) { false; target.on(cc.Node.EventType.SCALE_CHANGED, this._onTargetScaleChanged, this); }, _unregisterTargetEvent: function _unregisterTargetEvent(target) { false; target.off(cc.Node.EventType.SCALE_CHANGED, this._onTargetScaleChanged, this); }, _getTargetSprite: function _getTargetSprite(target) { var sprite = null; target && (sprite = target.getComponent(cc.Sprite)); return sprite; }, _applyTarget: function _applyTarget() { var target = this._getTarget(); this._sprite = this._getTargetSprite(target); this._originalScale || (this._originalScale = cc.Vec2.ZERO); this._originalScale.x = target.scaleX; this._originalScale.y = target.scaleY; this._registerTargetEvent(target); }, _onTouchBegan: function _onTouchBegan(event) { if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = true; this._updateState(); event.stopPropagation(); }, _onTouchMove: function _onTouchMove(event) { if (!this.interactable || !this.enabledInHierarchy || !this._pressed) return; var touch = event.touch; var hit = this.node._hitTest(touch.getLocation()); var target = this._getTarget(); var originalScale = this._originalScale; if (this.transition === Transition.SCALE && originalScale) if (hit) { this._fromScale.x = originalScale.x; this._fromScale.y = originalScale.y; this._toScale.x = originalScale.x * this.zoomScale; this._toScale.y = originalScale.y * this.zoomScale; this._transitionFinished = false; } else { this.time = 0; this._transitionFinished = true; target.setScale(originalScale.x, originalScale.y); } else { var state; state = hit ? State.PRESSED : State.NORMAL; this._applyTransition(state); } event.stopPropagation(); }, _onTouchEnded: function _onTouchEnded(event) { if (!this.interactable || !this.enabledInHierarchy) return; if (this._pressed) { cc.Component.EventHandler.emitEvents(this.clickEvents, event); this.node.emit("click", this); } this._pressed = false; this._updateState(); event.stopPropagation(); }, _onTouchCancel: function _onTouchCancel() { if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = false; this._updateState(); }, _onMouseMoveIn: function _onMouseMoveIn() { if (this._pressed || !this.interactable || !this.enabledInHierarchy) return; if (this.transition === Transition.SPRITE && !this.hoverSprite) return; if (!this._hovered) { this._hovered = true; this._updateState(); } }, _onMouseMoveOut: function _onMouseMoveOut() { if (this._hovered) { this._hovered = false; this._updateState(); } }, _updateState: function _updateState() { var state = this._getButtonState(); this._applyTransition(state); this._updateDisabledState(); }, _getButtonState: function _getButtonState() { var state; state = this.interactable ? this._pressed ? State.PRESSED : this._hovered ? State.HOVER : State.NORMAL : State.DISABLED; return state; }, _updateColorTransitionImmediately: function _updateColorTransitionImmediately(state) { var color = this._getStateColor(state); this._setTargetColor(color); this._fromColor = color.clone(); this._toColor = color; }, _updateColorTransition: function _updateColorTransition(state) { if (false, state === State.DISABLED) this._updateColorTransitionImmediately(state); else { var target = this._getTarget(); var color = this._getStateColor(state); this._fromColor = target.color.clone(); this._toColor = color; this.time = 0; this._transitionFinished = false; } }, _updateSpriteTransition: function _updateSpriteTransition(state) { var sprite = this._getStateSprite(state); this._sprite && sprite && (this._sprite.spriteFrame = sprite); }, _updateScaleTransition: function _updateScaleTransition(state) { state === State.PRESSED ? this._zoomUp() : this._zoomBack(); }, _zoomUp: function _zoomUp() { if (!this._originalScale) return; this._fromScale.x = this._originalScale.x; this._fromScale.y = this._originalScale.y; this._toScale.x = this._originalScale.x * this.zoomScale; this._toScale.y = this._originalScale.y * this.zoomScale; this.time = 0; this._transitionFinished = false; }, _zoomBack: function _zoomBack() { if (!this._originalScale) return; var target = this._getTarget(); this._fromScale.x = target.scaleX; this._fromScale.y = target.scaleY; this._toScale.x = this._originalScale.x; this._toScale.y = this._originalScale.y; this.time = 0; this._transitionFinished = false; }, _updateTransition: function _updateTransition(oldTransition) { oldTransition === Transition.COLOR ? this._updateColorTransitionImmediately(State.NORMAL) : oldTransition === Transition.SPRITE && this._updateSpriteTransition(State.NORMAL); this._updateState(); }, _applyTransition: function _applyTransition(state) { var transition = this.transition; transition === Transition.COLOR ? this._updateColorTransition(state) : transition === Transition.SPRITE ? this._updateSpriteTransition(state) : transition === Transition.SCALE && this._updateScaleTransition(state); }, _resizeNodeToTargetNode: false, _updateDisabledState: function _updateDisabledState(force) { if (!this._sprite) return; if (this.enableAutoGrayEffect || force) { var useGrayMaterial = false; this.transition === Transition.SPRITE && this.disabledSprite || (useGrayMaterial = this.enableAutoGrayEffect && !this.interactable); this._switchGrayMaterial(useGrayMaterial, this._sprite); } } }); cc.Button = module.exports = Button; }), { "../utils/gray-sprite-state": 214, "./CCComponent": 92 } ], 91: [ (function(require, module, exports) { "use strict"; var Camera = require("../camera/CCCamera"); var Component = require("./CCComponent"); function resetWidgetComponent(canvas) { var widget = canvas.node.getComponent(cc.Widget); widget || (widget = canvas.node.addComponent(cc.Widget)); widget.isAlignTop = true; widget.isAlignBottom = true; widget.isAlignLeft = true; widget.isAlignRight = true; widget.top = 0; widget.bottom = 0; widget.left = 0; widget.right = 0; } var Canvas = cc.Class({ name: "cc.Canvas", extends: Component, editor: false, resetInEditor: false, statics: { instance: null }, properties: { _designResolution: cc.size(960, 640), designResolution: { get: function get() { return cc.size(this._designResolution); }, set: function set(value) { this._designResolution.width = value.width; this._designResolution.height = value.height; this.applySettings(); }, tooltip: false }, _fitWidth: false, _fitHeight: true, fitHeight: { get: function get() { return this._fitHeight; }, set: function set(value) { if (this._fitHeight !== value) { this._fitHeight = value; this.applySettings(); } }, tooltip: false }, fitWidth: { get: function get() { return this._fitWidth; }, set: function set(value) { if (this._fitWidth !== value) { this._fitWidth = value; this.applySettings(); } }, tooltip: false } }, _fitDesignResolution: false, __preload: function __preload() { var Flags; false; if (Canvas.instance) return cc.warnID(6700, this.node.name, Canvas.instance.node.name); Canvas.instance = this; this.applySettings(); var widget = this.getComponent(cc.Widget); !!widget && widget.updateAlignment(); false; }, start: function start() { if (!Camera.main && cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { var cameraNode = new cc.Node("Main Camera"); cameraNode.parent = this.node; cameraNode.setSiblingIndex(0); var camera = cameraNode.addComponent(Camera); var ClearFlags = Camera.ClearFlags; camera.clearFlags = ClearFlags.COLOR | ClearFlags.DEPTH | ClearFlags.STENCIL; camera.depth = -1; } }, onDestroy: function onDestroy() { false; Canvas.instance === this && (Canvas.instance = null); }, applySettings: function applySettings() { var ResolutionPolicy = cc.ResolutionPolicy; var policy; policy = this.fitHeight && this.fitWidth ? ResolutionPolicy.SHOW_ALL : this.fitHeight || this.fitWidth ? this.fitWidth ? ResolutionPolicy.FIXED_WIDTH : ResolutionPolicy.FIXED_HEIGHT : ResolutionPolicy.NO_BORDER; var designRes = this._designResolution; false; cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy); } }); cc.Canvas = module.exports = Canvas; }), { "../camera/CCCamera": 86, "./CCComponent": 92 } ], 92: [ (function(require, module, exports) { "use strict"; var CCObject = require("../platform/CCObject"); var js = require("../platform/js"); var idGenerater = new (require("../platform/id-generater"))("Comp"); var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; var IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled; var ActionManagerExist = !!cc.ActionManager; var Component = cc.Class({ name: "cc.Component", extends: CCObject, ctor: function() { this._id = idGenerater.getNewId(); this.__eventTargets = []; }, properties: { node: { default: null, visible: false }, name: { get: function get() { if (this._name) return this._name; var className = cc.js.getClassName(this); var trimLeft = className.lastIndexOf("."); trimLeft >= 0 && (className = className.slice(trimLeft + 1)); return this.node.name + "<" + className + ">"; }, set: function set(value) { this._name = value; }, visible: false }, uuid: { get: function get() { return this._id; }, visible: false }, __scriptAsset: false, _enabled: true, enabled: { get: function get() { return this._enabled; }, set: function set(value) { if (this._enabled !== value) { this._enabled = value; if (this.node._activeInHierarchy) { var compScheduler = cc.director._compScheduler; value ? compScheduler.enableComp(this) : compScheduler.disableComp(this); } } }, visible: false, animatable: true }, enabledInHierarchy: { get: function get() { var _this$node, _this$node2, _this$node2$_parent; false; return this._enabled && this.node && this.node._activeInHierarchy; }, visible: false }, _isOnLoadCalled: { get: function get() { return this._objFlags & IsOnLoadCalled; } } }, update: null, lateUpdate: null, __preload: null, onLoad: null, start: null, onEnable: null, onDisable: null, onDestroy: null, onFocusInEditor: null, onLostFocusInEditor: null, resetInEditor: null, addComponent: function addComponent(typeOrClassName) { return this.node.addComponent(typeOrClassName); }, getComponent: function getComponent(typeOrClassName) { return this.node.getComponent(typeOrClassName); }, getComponents: function getComponents(typeOrClassName) { return this.node.getComponents(typeOrClassName); }, getComponentInChildren: function getComponentInChildren(typeOrClassName) { return this.node.getComponentInChildren(typeOrClassName); }, getComponentsInChildren: function getComponentsInChildren(typeOrClassName) { return this.node.getComponentsInChildren(typeOrClassName); }, _getLocalBounds: null, onRestore: null, destroy: function destroy() { var depend; false; this._super() && this._enabled && this.node._activeInHierarchy && cc.director._compScheduler.disableComp(this); }, _onPreDestroy: function _onPreDestroy() { ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this); this.unscheduleAllCallbacks(); var eventTargets = this.__eventTargets; for (var i = eventTargets.length - 1; i >= 0; --i) { var target = eventTargets[i]; target && target.targetOff(this); } eventTargets.length = 0; false; cc.director._nodeActivator.destroyComp(this); this.node._removeComponent(this); }, _instantiate: function _instantiate(cloned) { cloned || (cloned = cc.instantiate._clone(this, this)); cloned.node = null; return cloned; }, schedule: function schedule(callback, interval, repeat, delay) { cc.assertID(callback, 1619); interval = interval || 0; cc.assertID(interval >= 0, 1620); repeat = isNaN(repeat) ? cc.macro.REPEAT_FOREVER : repeat; delay = delay || 0; var scheduler = cc.director.getScheduler(); var paused = scheduler.isTargetPaused(this); scheduler.schedule(callback, this, interval, repeat, delay, paused); }, scheduleOnce: function scheduleOnce(callback, delay) { this.schedule(callback, 0, 0, delay); }, unschedule: function unschedule(callback_fn) { if (!callback_fn) return; cc.director.getScheduler().unschedule(callback_fn, this); }, unscheduleAllCallbacks: function unscheduleAllCallbacks() { cc.director.getScheduler().unscheduleAllForTarget(this); } }); Component._requireComponent = null; Component._executionOrder = 0; false; false, false; js.value(Component, "_registerEditorProps", (function(cls, props) { var reqComp = props.requireComponent; reqComp && (cls._requireComponent = reqComp); var order = props.executionOrder; order && "number" === typeof order && (cls._executionOrder = order); (false, false) && "disallowMultiple" in props && (cls._disallowMultiple = cls); var name; var key; var val; var willExecuteInEditMode; false, false; })); Component.prototype.__scriptUuid = ""; cc.Component = module.exports = Component; }), { "../platform/CCObject": 135, "../platform/id-generater": 146, "../platform/js": 150 } ], 93: [ (function(require, module, exports) { "use strict"; cc.Component.EventHandler = cc.Class({ name: "cc.ClickEvent", properties: { target: { default: null, type: cc.Node }, component: "", _componentId: "", _componentName: { get: function get() { this._genCompIdIfNeeded(); return this._compId2Name(this._componentId); }, set: function set(value) { this._componentId = this._compName2Id(value); } }, handler: { default: "" }, customEventData: { default: "" } }, statics: { emitEvents: function emitEvents(events) { var args; if (arguments.length > 0) { args = new Array(arguments.length - 1); for (var i = 0, l = args.length; i < l; i++) args[i] = arguments[i + 1]; } for (var _i = 0, _l = events.length; _i < _l; _i++) { var event = events[_i]; if (!(event instanceof cc.Component.EventHandler)) continue; event.emit(args); } } }, emit: function emit(params) { var target = this.target; if (!cc.isValid(target)) return; this._genCompIdIfNeeded(); var compType = cc.js._getClassById(this._componentId); var comp = target.getComponent(compType); if (!cc.isValid(comp)) return; var handler = comp[this.handler]; if ("function" !== typeof handler) return; if (null != this.customEventData && "" !== this.customEventData) { params = params.slice(); params.push(this.customEventData); } handler.apply(comp, params); }, _compName2Id: function _compName2Id(compName) { var comp = cc.js.getClassByName(compName); return cc.js._getClassId(comp); }, _compId2Name: function _compId2Name(compId) { var comp = cc.js._getClassById(compId); return cc.js.getClassName(comp); }, _genCompIdIfNeeded: function _genCompIdIfNeeded() { if (!this._componentId) { this._componentName = this.component; this.component = ""; } } }); }), {} ], 94: [ (function(require, module, exports) { "use strict"; var macro = require("../platform/CCMacro"); var RenderComponent = require("./CCRenderComponent"); var Material = require("../assets/material/CCMaterial"); var LabelFrame = require("../renderer/utils/label/label-frame"); var BlendFunc = require("../utils/blend-func"); var deleteFromDynamicAtlas = require("../renderer/utils/utils").deleteFromDynamicAtlas; var HorizontalAlign = macro.TextAlignment; var VerticalAlign = macro.VerticalTextAlignment; var Overflow = cc.Enum({ NONE: 0, CLAMP: 1, SHRINK: 2, RESIZE_HEIGHT: 3 }); var CacheMode = cc.Enum({ NONE: 0, BITMAP: 1, CHAR: 2 }); var BOLD_FLAG = 1; var ITALIC_FLAG = 2; var UNDERLINE_FLAG = 4; var Label = cc.Class({ name: "cc.Label", extends: RenderComponent, mixins: [ BlendFunc ], ctor: function ctor() { false; this._actualFontSize = 0; this._assemblerData = null; this._frame = null; this._ttfTexture = null; this._letterTexture = null; cc.game.renderType === cc.game.RENDER_TYPE_CANVAS ? this._updateMaterial = this._updateMaterialCanvas : this._updateMaterial = this._updateMaterialWebgl; }, editor: false, properties: { _string: { default: "", formerlySerializedAs: "_N$string" }, string: { get: function get() { return this._string; }, set: function set(value) { var oldValue = this._string; this._string = "" + value; this.string !== oldValue && this.setVertsDirty(); this._checkStringEmpty(); }, multiline: true, tooltip: false }, horizontalAlign: { default: HorizontalAlign.LEFT, type: HorizontalAlign, tooltip: false, notify: function notify(oldValue) { if (this.horizontalAlign === oldValue) return; this.setVertsDirty(); }, animatable: false }, verticalAlign: { default: VerticalAlign.TOP, type: VerticalAlign, tooltip: false, notify: function notify(oldValue) { if (this.verticalAlign === oldValue) return; this.setVertsDirty(); }, animatable: false }, actualFontSize: { displayName: "Actual Font Size", animatable: false, readonly: true, get: function get() { return this._actualFontSize; }, tooltip: false }, _fontSize: 40, fontSize: { get: function get() { return this._fontSize; }, set: function set(value) { if (this._fontSize === value) return; this._fontSize = value; this.setVertsDirty(); }, range: [ 0, 512 ], tooltip: false }, fontFamily: { default: "Arial", tooltip: false, notify: function notify(oldValue) { if (this.fontFamily === oldValue) return; this.setVertsDirty(); }, animatable: false }, _lineHeight: 40, lineHeight: { get: function get() { return this._lineHeight; }, set: function set(value) { if (this._lineHeight === value) return; this._lineHeight = value; this.setVertsDirty(); }, tooltip: false }, overflow: { default: Overflow.NONE, type: Overflow, tooltip: false, notify: function notify(oldValue) { if (this.overflow === oldValue) return; this.setVertsDirty(); }, animatable: false }, _enableWrapText: true, enableWrapText: { get: function get() { return this._enableWrapText; }, set: function set(value) { if (this._enableWrapText === value) return; this._enableWrapText = value; this.setVertsDirty(); }, animatable: false, tooltip: false }, _N$file: null, font: { get: function get() { return this._N$file; }, set: function set(value) { if (this.font === value) return; value || (this._isSystemFontUsed = true); false; this._N$file = value; value && this._isSystemFontUsed && (this._isSystemFontUsed = false); if (!this.enabledInHierarchy) return; this._forceUpdateRenderData(); }, type: cc.Font, tooltip: false, animatable: false }, _isSystemFontUsed: true, useSystemFont: { get: function get() { return this._isSystemFontUsed; }, set: function set(value) { if (this._isSystemFontUsed === value) return; this._isSystemFontUsed = !!value; false; if (value) { this.font = null; if (!this.enabledInHierarchy) return; this._forceUpdateRenderData(); } this.markForValidate(); }, animatable: false, tooltip: false }, _bmFontOriginalSize: { displayName: "BMFont Original Size", get: function get() { return this._N$file instanceof cc.BitmapFont ? this._N$file.fontSize : -1; }, visible: true, animatable: false }, _spacingX: 0, spacingX: { get: function get() { return this._spacingX; }, set: function set(value) { this._spacingX = value; this.setVertsDirty(); }, tooltip: false }, _batchAsBitmap: false, cacheMode: { default: CacheMode.NONE, type: CacheMode, tooltip: false, notify: function notify(oldValue) { if (this.cacheMode === oldValue) return; oldValue !== CacheMode.BITMAP || this.font instanceof cc.BitmapFont || deleteFromDynamicAtlas(this, this._frame); if (oldValue === CacheMode.CHAR) { this._ttfTexture = null; var material = this._materials[0]; material && material.material && cc.Label._shareAtlas.material === material.material && this.setMaterial(0, this._getDefaultMaterial()); } if (!this.enabledInHierarchy) return; this._forceUpdateRenderData(); }, animatable: false }, _styleFlags: 0, enableBold: { get: function get() { return !!(this._styleFlags & BOLD_FLAG); }, set: function set(value) { value ? this._styleFlags |= BOLD_FLAG : this._styleFlags &= ~BOLD_FLAG; this.setVertsDirty(); }, animatable: false, tooltip: false }, enableItalic: { get: function get() { return !!(this._styleFlags & ITALIC_FLAG); }, set: function set(value) { value ? this._styleFlags |= ITALIC_FLAG : this._styleFlags &= ~ITALIC_FLAG; this.setVertsDirty(); }, animatable: false, tooltip: false }, enableUnderline: { get: function get() { return !!(this._styleFlags & UNDERLINE_FLAG); }, set: function set(value) { value ? this._styleFlags |= UNDERLINE_FLAG : this._styleFlags &= ~UNDERLINE_FLAG; this.setVertsDirty(); }, animatable: false, tooltip: false }, _underlineHeight: 0, underlineHeight: { get: function get() { return this._underlineHeight; }, set: function set(value) { if (this._underlineHeight === value) return; this._underlineHeight = value; this.setVertsDirty(); }, tooltip: false }, autoSwitchMaterial: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.autoSwitchMaterial === oldValue) return; this.setVertsDirty(); } }, allowDynamicAtlas: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.allowDynamicAtlas === oldValue) return; this.setVertsDirty(); } }, enableRetina: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.enableRetina === oldValue) return; this.setVertsDirty(); } } }, statics: { HorizontalAlign: HorizontalAlign, VerticalAlign: VerticalAlign, Overflow: Overflow, CacheMode: CacheMode, _shareAtlas: null, clearCharCache: function clearCharCache() { Label._shareAtlas && Label._shareAtlas.clearAllCache(); } }, onLoad: function onLoad() { if (this._batchAsBitmap && this.cacheMode === CacheMode.NONE) { this.cacheMode = CacheMode.BITMAP; this._batchAsBitmap = false; } cc.game.renderType === cc.game.RENDER_TYPE_CANVAS && (this.cacheMode = CacheMode.NONE); }, onEnable: function onEnable() { this._super(); this.node.on(cc.Node.EventType.SIZE_CHANGED, this._nodeSizeChanged, this); this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this.setVertsDirty, this); this.node.on(cc.Node.EventType.COLOR_CHANGED, this._nodeColorChanged, this); this._forceUpdateRenderData(); }, onDisable: function onDisable() { this._super(); this.node.off(cc.Node.EventType.SIZE_CHANGED, this._nodeSizeChanged, this); this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this.setVertsDirty, this); this.node.off(cc.Node.EventType.COLOR_CHANGED, this._nodeColorChanged, this); }, onDestroy: function onDestroy() { this._assembler && this._assembler._resetAssemblerData && this._assembler._resetAssemblerData(this._assemblerData); this._assemblerData = null; this._letterTexture = null; if (this._ttfTexture) { this._ttfTexture._packable = false; this._ttfTexture.destroy(); this._ttfTexture = null; } this._resetFrame(); this._super(); }, _nodeSizeChanged: function _nodeSizeChanged() { (false, this.overflow !== Overflow.NONE) && this.setVertsDirty(); }, _nodeColorChanged: function _nodeColorChanged() { this.font instanceof cc.BitmapFont || this.setVertsDirty(); }, setVertsDirty: function setVertsDirty() { false; this._super(); }, _updateColor: function _updateColor() { this.font instanceof cc.BitmapFont || this._srcBlendFactor === cc.macro.BlendFactor.SRC_ALPHA && this.node._renderFlag & cc.RenderFlow.FLAG_OPACITY || this.setVertsDirty(); RenderComponent.prototype._updateColor.call(this); }, _validateRender: function _validateRender() { if (!this.string) { this.disableRender(); return; } if (this._materials[0]) { var font = this.font; if (!(font instanceof cc.BitmapFont)) return; var spriteFrame = font.spriteFrame; if (spriteFrame && spriteFrame.textureLoaded() && font._fntConfig) return; } this.disableRender(); }, _resetAssembler: function _resetAssembler() { this._resetFrame(); RenderComponent.prototype._resetAssembler.call(this); }, _resetFrame: function _resetFrame() { if (this._frame && !(this.font instanceof cc.BitmapFont)) { deleteFromDynamicAtlas(this, this._frame); this._frame = null; } }, _checkStringEmpty: function _checkStringEmpty() { this.markForRender(!!this.string); }, _on3DNodeChanged: function _on3DNodeChanged() { this._resetAssembler(); this._applyFontTexture(); }, _onBMFontTextureLoaded: function _onBMFontTextureLoaded() { this._frame._texture = this.font.spriteFrame._texture; this.markForRender(true); this._updateMaterial(); this._assembler && this._assembler.updateRenderData(this); }, _onBlendChanged: function _onBlendChanged() { if (!this.useSystemFont || !this.enabledInHierarchy) return; this._forceUpdateRenderData(); }, _applyFontTexture: function _applyFontTexture() { var font = this.font; if (font instanceof cc.BitmapFont) { var spriteFrame = font.spriteFrame; this._frame = spriteFrame; spriteFrame && spriteFrame.onTextureLoaded(this._onBMFontTextureLoaded, this); } else { if (!this._nativeTTF()) { this._frame || (this._frame = new LabelFrame()); if (this.cacheMode === CacheMode.CHAR) { this._letterTexture = this._assembler._getAssemblerData(); this._frame._refreshTexture(this._letterTexture); } else if (!this._ttfTexture) { this._ttfTexture = new cc.Texture2D(); this._assemblerData = this._assembler._getAssemblerData(); this._ttfTexture.initWithElement(this._assemblerData.canvas); } if (this.cacheMode !== CacheMode.CHAR) { deleteFromDynamicAtlas(this, this._frame); this._frame._refreshTexture(this._ttfTexture); this._srcBlendFactor === cc.macro.BlendFactor.ONE && true && this._ttfTexture.setPremultiplyAlpha(true); } this._updateMaterial(); } this._assembler && this._assembler.updateRenderData(this); } this.markForValidate(); }, _updateMaterialCanvas: function _updateMaterialCanvas() { if (!this._frame) return; this._frame._texture._nativeUrl = this.uuid + "_texture"; }, _updateMaterialWebgl: function _updateMaterialWebgl() { var material = this.getMaterial(0); if (this._nativeTTF()) { material && this._assembler._updateTTFMaterial(this); return; } if (!this._frame) return; if (material) { var isMultiMaterial = material.material.isMultiSupport(); isMultiMaterial ? this._texIdDirty = true : material.setProperty("texture", this._frame._texture); this._assembler && (isMultiMaterial && !this._assembler.isMulti || !isMultiMaterial && this._assembler.isMulti) && RenderComponent.prototype._resetAssembler.call(this); } BlendFunc.prototype._updateMaterial.call(this); }, _forceUseCanvas: false, _useNativeTTF: function _useNativeTTF() { return cc.macro.ENABLE_NATIVE_TTF_RENDERER && !this._forceUseCanvas; }, _nativeTTF: function _nativeTTF() { return this._useNativeTTF() && !!this._assembler && !!this._assembler._updateTTFMaterial; }, _forceUpdateRenderData: function _forceUpdateRenderData() { this.setVertsDirty(); this._resetAssembler(); this._applyFontTexture(); }, _enableBold: function _enableBold(enabled) { true; cc.warn("`label._enableBold` is deprecated, use `label.enableBold = true` instead please"); this.enableBold = !!enabled; }, _enableItalics: function _enableItalics(enabled) { true; cc.warn("`label._enableItalics` is deprecated, use `label.enableItalics = true` instead please"); this.enableItalic = !!enabled; }, _enableUnderline: function _enableUnderline(enabled) { true; cc.warn("`label._enableUnderline` is deprecated, use `label.enableUnderline = true` instead please"); this.enableUnderline = !!enabled; } }); cc.Label = module.exports = Label; }), { "../assets/material/CCMaterial": 76, "../platform/CCMacro": 134, "../renderer/utils/label/label-frame": 165, "../renderer/utils/utils": 168, "../utils/blend-func": 211, "./CCRenderComponent": 100 } ], 95: [ (function(require, module, exports) { "use strict"; var LabelOutline = cc.Class({ name: "cc.LabelOutline", extends: require("./CCComponent"), editor: false, properties: { _color: cc.Color.WHITE, _width: 1, color: { tooltip: false, get: function get() { return this._color.clone(); }, set: function set(value) { this._color.equals(value) || this._color.set(value); this._updateRenderData(); } }, width: { tooltip: false, get: function get() { return this._width; }, set: function set(value) { if (this._width === value) return; this._width = value; this._updateRenderData(); }, range: [ 0, 512 ] } }, onEnable: function onEnable() { this._updateRenderData(); }, onDisable: function onDisable() { this._updateRenderData(); }, _updateRenderData: function _updateRenderData() { var label = this.node.getComponent(cc.Label); label && label.setVertsDirty(); } }); cc.LabelOutline = module.exports = LabelOutline; }), { "./CCComponent": 92 } ], 96: [ (function(require, module, exports) { "use strict"; var LabelShadow = cc.Class({ name: "cc.LabelShadow", extends: require("./CCComponent"), editor: false, properties: { _color: cc.Color.WHITE, _offset: cc.v2(2, 2), _blur: 2, color: { tooltip: false, get: function get() { return this._color.clone(); }, set: function set(value) { this._color.equals(value) || this._color.set(value); this._updateRenderData(); } }, offset: { tooltip: false, get: function get() { return this._offset; }, set: function set(value) { this._offset = value; this._updateRenderData(); } }, blur: { tooltip: false, get: function get() { return this._blur; }, set: function set(value) { this._blur = value; this._updateRenderData(); }, range: [ 0, 1024 ] } }, onEnable: function onEnable() { this._updateRenderData(); }, onDisable: function onDisable() { this._updateRenderData(); }, _updateRenderData: function _updateRenderData() { var label = this.node.getComponent(cc.Label); label && label.setVertsDirty(); } }); cc.LabelShadow = module.exports = LabelShadow; }), { "./CCComponent": 92 } ], 97: [ (function(require, module, exports) { "use strict"; var NodeEvent = require("../CCNode").EventType; var Type = cc.Enum({ NONE: 0, HORIZONTAL: 1, VERTICAL: 2, GRID: 3 }); var ResizeMode = cc.Enum({ NONE: 0, CONTAINER: 1, CHILDREN: 2 }); var AxisDirection = cc.Enum({ HORIZONTAL: 0, VERTICAL: 1 }); var VerticalDirection = cc.Enum({ BOTTOM_TO_TOP: 0, TOP_TO_BOTTOM: 1 }); var HorizontalDirection = cc.Enum({ LEFT_TO_RIGHT: 0, RIGHT_TO_LEFT: 1 }); var Layout = cc.Class({ name: "cc.Layout", extends: require("./CCComponent"), editor: false, properties: { _layoutSize: cc.size(300, 200), _layoutDirty: { default: true, serializable: false }, _resize: ResizeMode.NONE, _N$layoutType: Type.NONE, type: { type: Type, get: function get() { return this._N$layoutType; }, set: function set(value) { this._N$layoutType = value; var reLayouted; false; this._doLayoutDirty(); }, tooltip: false, animatable: false }, resizeMode: { type: ResizeMode, tooltip: false, animatable: false, get: function get() { return this._resize; }, set: function set(value) { if (this.type === Type.NONE && value === ResizeMode.CHILDREN) return; this._resize = value; var reLayouted; false; this._doLayoutDirty(); } }, cellSize: { default: cc.size(40, 40), tooltip: false, type: cc.Size, notify: function notify() { this._doLayoutDirty(); } }, startAxis: { default: AxisDirection.HORIZONTAL, tooltip: false, type: AxisDirection, notify: function notify() { var reLayouted; false; this._doLayoutDirty(); }, animatable: false }, paddingLeft: { default: 0, tooltip: false, notify: function notify() { this._doLayoutDirty(); } }, paddingRight: { default: 0, tooltip: false, notify: function notify() { this._doLayoutDirty(); } }, paddingTop: { default: 0, tooltip: false, notify: function notify() { this._doLayoutDirty(); } }, paddingBottom: { default: 0, tooltip: false, notify: function notify() { this._doLayoutDirty(); } }, spacingX: { default: 0, notify: function notify() { this._doLayoutDirty(); }, tooltip: false }, spacingY: { default: 0, notify: function notify() { this._doLayoutDirty(); }, tooltip: false }, verticalDirection: { default: VerticalDirection.TOP_TO_BOTTOM, type: VerticalDirection, notify: function notify() { this._doLayoutDirty(); }, tooltip: false, animatable: false }, horizontalDirection: { default: HorizontalDirection.LEFT_TO_RIGHT, type: HorizontalDirection, notify: function notify() { this._doLayoutDirty(); }, tooltip: false, animatable: false }, affectedByScale: { default: false, notify: function notify() { this._doLayoutDirty(); }, animatable: false, tooltip: false } }, statics: { Type: Type, VerticalDirection: VerticalDirection, HorizontalDirection: HorizontalDirection, ResizeMode: ResizeMode, AxisDirection: AxisDirection }, onEnable: function onEnable() { this._addEventListeners(); this.node.getContentSize().equals(cc.size(0, 0)) && this.node.setContentSize(this._layoutSize); this._doLayoutDirty(); }, onDisable: function onDisable() { this._removeEventListeners(); }, _doLayoutDirty: function _doLayoutDirty() { this._layoutDirty = true; }, _doScaleDirty: function _doScaleDirty() { this._layoutDirty = this._layoutDirty || this.affectedByScale; }, _addEventListeners: function _addEventListeners() { cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.on(NodeEvent.CHILD_ADDED, this._childAdded, this); this.node.on(NodeEvent.CHILD_REMOVED, this._childRemoved, this); this.node.on(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._addChildrenEventListeners(); }, _removeEventListeners: function _removeEventListeners() { cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.off(NodeEvent.CHILD_ADDED, this._childAdded, this); this.node.off(NodeEvent.CHILD_REMOVED, this._childRemoved, this); this.node.off(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._removeChildrenEventListeners(); }, _addChildrenEventListeners: function _addChildrenEventListeners() { var children = this.node.children; for (var i = 0; i < children.length; ++i) { var child = children[i]; child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on("active-in-hierarchy-changed", this._doLayoutDirty, this); } }, _removeChildrenEventListeners: function _removeChildrenEventListeners() { var children = this.node.children; for (var i = 0; i < children.length; ++i) { var child = children[i]; child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off("active-in-hierarchy-changed", this._doLayoutDirty, this); } }, _childAdded: function _childAdded(child) { child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on("active-in-hierarchy-changed", this._doLayoutDirty, this); this._doLayoutDirty(); }, _childRemoved: function _childRemoved(child) { child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off("active-in-hierarchy-changed", this._doLayoutDirty, this); this._doLayoutDirty(); }, _resized: function _resized() { this._layoutSize = this.node.getContentSize(); this._doLayoutDirty(); }, _doLayoutHorizontally: function _doLayoutHorizontally(baseWidth, rowBreak, fnPositionY, applyChildren) { var layoutAnchor = this.node.getAnchorPoint(); var children = this.node.children; var sign = 1; var paddingX = this.paddingLeft; var leftBoundaryOfLayout = -layoutAnchor.x * baseWidth; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * baseWidth; paddingX = this.paddingRight; } var nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX; var rowMaxHeight = 0; var tempMaxHeight = 0; var secondMaxHeight = 0; var row = 0; var containerResizeBoundary = 0; var maxHeightChildAnchorY = 0; var activeChildCount = 0; for (var i = 0; i < children.length; ++i) { var child = children[i]; child.activeInHierarchy && activeChildCount++; } var newChildWidth = this.cellSize.width; this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN && (newChildWidth = (baseWidth - (this.paddingLeft + this.paddingRight) - (activeChildCount - 1) * this.spacingX) / activeChildCount); for (var i = 0; i < children.length; ++i) { var child = children[i]; var childScaleX = this._getUsedScaleValue(child.scaleX); var childScaleY = this._getUsedScaleValue(child.scaleY); if (!child.activeInHierarchy) continue; if (this._resize === ResizeMode.CHILDREN) { child.width = newChildWidth / childScaleX; this.type === Type.GRID && (child.height = this.cellSize.height / childScaleY); } var anchorX = child.anchorX; var childBoundingBoxWidth = child.width * childScaleX; var childBoundingBoxHeight = child.height * childScaleY; secondMaxHeight > tempMaxHeight && (tempMaxHeight = secondMaxHeight); if (childBoundingBoxHeight >= tempMaxHeight) { secondMaxHeight = tempMaxHeight; tempMaxHeight = childBoundingBoxHeight; maxHeightChildAnchorY = child.getAnchorPoint().y; } this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && (anchorX = 1 - child.anchorX); nextX = nextX + sign * anchorX * childBoundingBoxWidth + sign * this.spacingX; var rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth; if (rowBreak) { var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft); var leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth; var rightToLeftRowBreak = this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth; if (leftToRightRowBreak || rightToLeftRowBreak) { if (childBoundingBoxHeight >= tempMaxHeight) { 0 === secondMaxHeight && (secondMaxHeight = tempMaxHeight); rowMaxHeight += secondMaxHeight; secondMaxHeight = tempMaxHeight; } else { rowMaxHeight += tempMaxHeight; secondMaxHeight = childBoundingBoxHeight; tempMaxHeight = 0; } nextX = leftBoundaryOfLayout + sign * (paddingX + anchorX * childBoundingBoxWidth); row++; } } var finalPositionY = fnPositionY(child, rowMaxHeight, row); baseWidth >= childBoundingBoxWidth + this.paddingLeft + this.paddingRight && applyChildren && child.setPosition(cc.v2(nextX, finalPositionY)); var signX = 1; var tempFinalPositionY; var topMarign = 0 === tempMaxHeight ? childBoundingBoxHeight : tempMaxHeight; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { containerResizeBoundary = containerResizeBoundary || this.node._contentSize.height; signX = -1; tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingBottom); tempFinalPositionY < containerResizeBoundary && (containerResizeBoundary = tempFinalPositionY); } else { containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.height; tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingTop); tempFinalPositionY > containerResizeBoundary && (containerResizeBoundary = tempFinalPositionY); } nextX += rightBoundaryOfChild; } return containerResizeBoundary; }, _getVerticalBaseHeight: function _getVerticalBaseHeight(children) { var newHeight = 0; var activeChildCount = 0; if (this.resizeMode === ResizeMode.CONTAINER) { for (var i = 0; i < children.length; ++i) { var child = children[i]; if (child.activeInHierarchy) { activeChildCount++; newHeight += child.height * this._getUsedScaleValue(child.scaleY); } } newHeight += (activeChildCount - 1) * this.spacingY + this.paddingBottom + this.paddingTop; } else newHeight = this.node.getContentSize().height; return newHeight; }, _doLayoutVertically: function _doLayoutVertically(baseHeight, columnBreak, fnPositionX, applyChildren) { var layoutAnchor = this.node.getAnchorPoint(); var children = this.node.children; var sign = 1; var paddingY = this.paddingBottom; var bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * baseHeight; paddingY = this.paddingTop; } var nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY; var columnMaxWidth = 0; var tempMaxWidth = 0; var secondMaxWidth = 0; var column = 0; var containerResizeBoundary = 0; var maxWidthChildAnchorX = 0; var activeChildCount = 0; for (var i = 0; i < children.length; ++i) { var child = children[i]; child.activeInHierarchy && activeChildCount++; } var newChildHeight = this.cellSize.height; this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN && (newChildHeight = (baseHeight - (this.paddingTop + this.paddingBottom) - (activeChildCount - 1) * this.spacingY) / activeChildCount); for (var i = 0; i < children.length; ++i) { var child = children[i]; var childScaleX = this._getUsedScaleValue(child.scaleX); var childScaleY = this._getUsedScaleValue(child.scaleY); if (!child.activeInHierarchy) continue; if (this.resizeMode === ResizeMode.CHILDREN) { child.height = newChildHeight / childScaleY; this.type === Type.GRID && (child.width = this.cellSize.width / childScaleX); } var anchorY = child.anchorY; var childBoundingBoxWidth = child.width * childScaleX; var childBoundingBoxHeight = child.height * childScaleY; secondMaxWidth > tempMaxWidth && (tempMaxWidth = secondMaxWidth); if (childBoundingBoxWidth >= tempMaxWidth) { secondMaxWidth = tempMaxWidth; tempMaxWidth = childBoundingBoxWidth; maxWidthChildAnchorX = child.getAnchorPoint().x; } this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && (anchorY = 1 - child.anchorY); nextY = nextY + sign * anchorY * childBoundingBoxHeight + sign * this.spacingY; var topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight; if (columnBreak) { var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom); var bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight; var topToBottomColumnBreak = this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight; if (bottomToTopColumnBreak || topToBottomColumnBreak) { if (childBoundingBoxWidth >= tempMaxWidth) { 0 === secondMaxWidth && (secondMaxWidth = tempMaxWidth); columnMaxWidth += secondMaxWidth; secondMaxWidth = tempMaxWidth; } else { columnMaxWidth += tempMaxWidth; secondMaxWidth = childBoundingBoxWidth; tempMaxWidth = 0; } nextY = bottomBoundaryOfLayout + sign * (paddingY + anchorY * childBoundingBoxHeight); column++; } } var finalPositionX = fnPositionX(child, columnMaxWidth, column); baseHeight >= childBoundingBoxHeight + (this.paddingTop + this.paddingBottom) && applyChildren && child.setPosition(cc.v2(finalPositionX, nextY)); var signX = 1; var tempFinalPositionX; var rightMarign = 0 === tempMaxWidth ? childBoundingBoxWidth : tempMaxWidth; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { signX = -1; containerResizeBoundary = containerResizeBoundary || this.node._contentSize.width; tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingLeft); tempFinalPositionX < containerResizeBoundary && (containerResizeBoundary = tempFinalPositionX); } else { containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.width; tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingRight); tempFinalPositionX > containerResizeBoundary && (containerResizeBoundary = tempFinalPositionX); } nextY += topBoundaryOfChild; } return containerResizeBoundary; }, _doLayoutBasic: function _doLayoutBasic() { var children = this.node.children; var allChildrenBoundingBox = null; for (var i = 0; i < children.length; ++i) { var child = children[i]; child.activeInHierarchy && (allChildrenBoundingBox ? allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld()) : allChildrenBoundingBox = child.getBoundingBoxToWorld()); } if (allChildrenBoundingBox) { var leftBottomSpace = this.node.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); leftBottomSpace = cc.v2(leftBottomSpace.x - this.paddingLeft, leftBottomSpace.y - this.paddingBottom); var rightTopSpace = this.node.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.xMax, allChildrenBoundingBox.yMax)); rightTopSpace = cc.v2(rightTopSpace.x + this.paddingRight, rightTopSpace.y + this.paddingTop); var newSize = rightTopSpace.sub(leftBottomSpace); newSize = cc.size(parseFloat(newSize.x.toFixed(2)), parseFloat(newSize.y.toFixed(2))); if (0 !== newSize.width) { var newAnchorX = -leftBottomSpace.x / newSize.width; this.node.anchorX = parseFloat(newAnchorX.toFixed(2)); } if (0 !== newSize.height) { var newAnchorY = -leftBottomSpace.y / newSize.height; this.node.anchorY = parseFloat(newAnchorY.toFixed(2)); } this.node.setContentSize(newSize); } }, _doLayoutGridAxisHorizontal: function _doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) { var baseWidth = layoutSize.width; var sign = 1; var bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height; var paddingY = this.paddingBottom; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height; paddingY = this.paddingTop; } var fnPositionY = function(child, topOffset, row) { return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * this._getUsedScaleValue(child.scaleY) + paddingY + row * this.spacingY); }.bind(this); var newHeight = 0; if (this.resizeMode === ResizeMode.CONTAINER) { var boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false); newHeight = bottomBoundaryOfLayout - boundary; newHeight < 0 && (newHeight *= -1); bottomBoundaryOfLayout = -layoutAnchor.y * newHeight; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight; } } this._doLayoutHorizontally(baseWidth, true, fnPositionY, true); this.resizeMode === ResizeMode.CONTAINER && this.node.setContentSize(baseWidth, newHeight); }, _doLayoutGridAxisVertical: function _doLayoutGridAxisVertical(layoutAnchor, layoutSize) { var baseHeight = layoutSize.height; var sign = 1; var leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width; var paddingX = this.paddingLeft; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width; paddingX = this.paddingRight; } var fnPositionX = function(child, leftOffset, column) { return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * this._getUsedScaleValue(child.scaleX) + paddingX + column * this.spacingX); }.bind(this); var newWidth = 0; if (this.resizeMode === ResizeMode.CONTAINER) { var boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false); newWidth = leftBoundaryOfLayout - boundary; newWidth < 0 && (newWidth *= -1); leftBoundaryOfLayout = -layoutAnchor.x * newWidth; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth; } } this._doLayoutVertically(baseHeight, true, fnPositionX, true); this.resizeMode === ResizeMode.CONTAINER && this.node.setContentSize(newWidth, baseHeight); }, _doLayoutGrid: function _doLayoutGrid() { var layoutAnchor = this.node.getAnchorPoint(); var layoutSize = this.node.getContentSize(); this.startAxis === AxisDirection.HORIZONTAL ? this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) : this.startAxis === AxisDirection.VERTICAL && this._doLayoutGridAxisVertical(layoutAnchor, layoutSize); }, _getHorizontalBaseWidth: function _getHorizontalBaseWidth(children) { var newWidth = 0; var activeChildCount = 0; if (this.resizeMode === ResizeMode.CONTAINER) { for (var i = 0; i < children.length; ++i) { var child = children[i]; if (child.activeInHierarchy) { activeChildCount++; newWidth += child.width * this._getUsedScaleValue(child.scaleX); } } newWidth += (activeChildCount - 1) * this.spacingX + this.paddingLeft + this.paddingRight; } else newWidth = this.node.getContentSize().width; return newWidth; }, _doLayout: function _doLayout() { if (this.type === Type.HORIZONTAL) { var newWidth = this._getHorizontalBaseWidth(this.node.children); var fnPositionY = function fnPositionY(child) { return child.y; }; this._doLayoutHorizontally(newWidth, false, fnPositionY, true); this.node.width = newWidth; } else if (this.type === Type.VERTICAL) { var newHeight = this._getVerticalBaseHeight(this.node.children); var fnPositionX = function fnPositionX(child) { return child.x; }; this._doLayoutVertically(newHeight, false, fnPositionX, true); this.node.height = newHeight; } else this.type === Type.NONE ? this.resizeMode === ResizeMode.CONTAINER && this._doLayoutBasic() : this.type === Type.GRID && this._doLayoutGrid(); }, _getUsedScaleValue: function _getUsedScaleValue(value) { return this.affectedByScale ? Math.abs(value) : 1; }, updateLayout: function updateLayout() { if (this._layoutDirty && this.node.children.length > 0) { var activeChild = this.node.children.find((function(node) { return node.activeInHierarchy; })); if (activeChild) { this._doLayout(); this._layoutDirty = false; } } } }); cc.Layout = module.exports = Layout; }), { "../CCNode": 24, "./CCComponent": 92 } ], 98: [ (function(require, module, exports) { "use strict"; var _gfx = _interopRequireDefault(require("../../renderer/gfx")); var _mat = _interopRequireDefault(require("../value-types/mat4")); var _vec = _interopRequireDefault(require("../value-types/vec2")); var _materialVariant = _interopRequireDefault(require("../assets/material/material-variant")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var misc = require("../utils/misc"); var RenderComponent = require("./CCRenderComponent"); var RenderFlow = require("../renderer/render-flow"); var Graphics = require("../graphics/graphics"); var _vec2_temp = new _vec["default"](); var _mat4_temp = new _mat["default"](); var _circlepoints = []; function _calculateCircle(center, radius, segements) { _circlepoints.length = 0; var anglePerStep = 2 * Math.PI / segements; for (var step = 0; step < segements; ++step) _circlepoints.push(cc.v2(radius.x * Math.cos(anglePerStep * step) + center.x, radius.y * Math.sin(anglePerStep * step) + center.y)); return _circlepoints; } var MaskType = cc.Enum({ RECT: 0, ELLIPSE: 1, IMAGE_STENCIL: 2 }); var SEGEMENTS_MIN = 3; var SEGEMENTS_MAX = 1e4; var Mask = cc.Class({ name: "cc.Mask", extends: RenderComponent, editor: false, ctor: function ctor() { this._graphics = null; this._enableMaterial = null; this._exitMaterial = null; this._clearMaterial = null; }, properties: { _spriteFrame: { default: null, type: cc.SpriteFrame }, _type: MaskType.RECT, type: { get: function get() { return this._type; }, set: function set(value) { this._type !== value && this._resetAssembler(); this._type = value; if (this._type !== MaskType.IMAGE_STENCIL) { this.spriteFrame = null; this.alphaThreshold = 0; this._updateGraphics(); } this._activateMaterial(); }, type: MaskType, tooltip: false }, spriteFrame: { type: cc.SpriteFrame, tooltip: false, get: function get() { return this._spriteFrame; }, set: function set(value) { var lastSprite = this._spriteFrame; false; if (lastSprite === value) return; lastSprite && lastSprite.off("load", this.setVertsDirty, this); this._spriteFrame = value; this.setVertsDirty(); this._updateMaterial(); } }, alphaThreshold: { default: .1, type: cc.Float, range: [ 0, 1, .1 ], slide: true, tooltip: false, notify: function notify() { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { cc.warnID(4201); return; } this._updateMaterial(); } }, inverted: { default: false, type: cc.Boolean, tooltip: false, notify: function notify() { cc.game.renderType === cc.game.RENDER_TYPE_CANVAS && cc.warnID(4202); } }, _segments: 64, segements: { get: function get() { return this._segments; }, set: function set(value) { this._segments = misc.clampf(value, SEGEMENTS_MIN, SEGEMENTS_MAX); this._updateGraphics(); }, type: cc.Integer, tooltip: false }, _resizeToTarget: { animatable: false, set: function set(value) { value && this._resizeNodeToTargetNode(); } } }, statics: { Type: MaskType }, onRestore: function onRestore() { this._activateMaterial(); }, onEnable: function onEnable() { this._super(); this._type !== MaskType.IMAGE_STENCIL ? this._updateGraphics() : this._spriteFrame && this._spriteFrame.once("load", this.setVertsDirty, this); this.node.on(cc.Node.EventType.POSITION_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.SCALE_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); }, onDisable: function onDisable() { this._super(); this.node.off(cc.Node.EventType.POSITION_CHANGED, this._updateGraphics, this); this.node.off(cc.Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); this.node.off(cc.Node.EventType.SCALE_CHANGED, this._updateGraphics, this); this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateGraphics, this); this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); this.node._renderFlag &= ~RenderFlow.FLAG_POST_RENDER; }, onDestroy: function onDestroy() { this._super(); this._removeGraphics(); this._spriteFrame && this._spriteFrame.off("load", this.setVertsDirty, this); }, _resizeNodeToTargetNode: false, _validateRender: function _validateRender() { if (this._type !== MaskType.IMAGE_STENCIL) return; var spriteFrame = this._spriteFrame; if (spriteFrame && spriteFrame.textureLoaded()) return; this.disableRender(); }, _activateMaterial: function _activateMaterial() { this._createGraphics(); var material = this._materials[0]; material = material ? _materialVariant["default"].create(material, this) : _materialVariant["default"].createWithBuiltin("2d-sprite", this); material.define("USE_ALPHA_TEST", true); if (this._type === MaskType.IMAGE_STENCIL) { material.define("CC_USE_MODEL", false); material.define("USE_TEXTURE", true); } else { material.define("CC_USE_MODEL", true); material.define("USE_TEXTURE", false); } this._enableMaterial || (this._enableMaterial = _materialVariant["default"].createWithBuiltin("2d-sprite", this)); if (!this._exitMaterial) { this._exitMaterial = _materialVariant["default"].createWithBuiltin("2d-sprite", this); this._exitMaterial.setStencilEnabled(_gfx["default"].STENCIL_DISABLE); } this._clearMaterial || (this._clearMaterial = _materialVariant["default"].createWithBuiltin("clear-stencil", this)); this.setMaterial(0, material); this._graphics._materials[0] = material; this._updateMaterial(); }, _updateMaterial: function _updateMaterial() { var material = this._materials[0]; if (!material) return; if (this._type === MaskType.IMAGE_STENCIL && this.spriteFrame) { var texture = this.spriteFrame.getTexture(); material.setProperty("texture", texture); } material.setProperty("alphaThreshold", this.alphaThreshold); }, _createGraphics: function _createGraphics() { if (!this._graphics) { this._graphics = new Graphics(); cc.Assembler.init(this._graphics); this._graphics.node = this.node; this._graphics.lineWidth = 0; this._graphics.strokeColor = cc.color(0, 0, 0, 0); } }, _updateGraphics: function _updateGraphics() { if (!this.enabledInHierarchy) return; var node = this.node; var graphics = this._graphics; graphics.clear(false); var width = node._contentSize.width; var height = node._contentSize.height; var x = -width * node._anchorPoint.x; var y = -height * node._anchorPoint.y; if (this._type === MaskType.RECT) graphics.rect(x, y, width, height); else if (this._type === MaskType.ELLIPSE) { var center = cc.v2(x + width / 2, y + height / 2); var radius = { x: width / 2, y: height / 2 }; var points = _calculateCircle(center, radius, this._segments); for (var i = 0; i < points.length; ++i) { var point = points[i]; 0 === i ? graphics.moveTo(point.x, point.y) : graphics.lineTo(point.x, point.y); } graphics.close(); } cc.game.renderType === cc.game.RENDER_TYPE_CANVAS ? graphics.stroke() : graphics.fill(); this.setVertsDirty(); }, _removeGraphics: function _removeGraphics() { if (this._graphics) { this._graphics.destroy(); this._graphics._destroyImmediate(); this._graphics = null; } }, _hitTest: function _hitTest(cameraPt) { var node = this.node; var size = node.getContentSize(), w = size.width, h = size.height, testPt = _vec2_temp; node._updateWorldMatrix(); if (!_mat["default"].invert(_mat4_temp, node._worldMatrix)) return false; _vec["default"].transformMat4(testPt, cameraPt, _mat4_temp); testPt.x += node._anchorPoint.x * w; testPt.y += node._anchorPoint.y * h; var result = false; if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h; else if (this.type === MaskType.ELLIPSE) { var rx = w / 2, ry = h / 2; var px = testPt.x - .5 * w, py = testPt.y - .5 * h; result = px * px / (rx * rx) + py * py / (ry * ry) < 1; } this.inverted && (result = !result); return result; }, markForRender: function markForRender(enable) { var flag = RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_POST_RENDER; if (enable) { this.node._renderFlag |= flag; this.markForValidate(); } else enable || (this.node._renderFlag &= ~flag); }, disableRender: function disableRender() { this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_POST_RENDER); } }); cc.Mask = module.exports = Mask; }), { "../../renderer/gfx": 259, "../assets/material/material-variant": 83, "../graphics/graphics": 123, "../renderer/render-flow": 161, "../utils/misc": 217, "../value-types/mat4": 234, "../value-types/vec2": 241, "./CCRenderComponent": 100 } ], 99: [ (function(require, module, exports) { "use strict"; var RenderComponent = require("../components/CCRenderComponent"); var BlendFunc = require("../../core/utils/blend-func"); var MotionStreak = cc.Class({ name: "cc.MotionStreak", extends: RenderComponent, mixins: [ BlendFunc ], editor: false, ctor: function ctor() { this._points = []; this._lastWPos = new cc.Vec2(); }, properties: { preview: { default: false, editorOnly: true, notify: false, animatable: false }, _fadeTime: 1, fadeTime: { get: function get() { return this._fadeTime; }, set: function set(value) { this._fadeTime = value; this.reset(); }, animatable: false, tooltip: false }, _minSeg: 1, minSeg: { get: function get() { return this._minSeg; }, set: function set(value) { this._minSeg = value; }, animatable: false, tooltip: false }, _stroke: 64, stroke: { get: function get() { return this._stroke; }, set: function set(value) { this._stroke = value; }, animatable: false, tooltip: false }, _texture: { default: null, type: cc.Texture2D }, texture: { get: function get() { return this._texture; }, set: function set(value) { if (this._texture === value) return; this._texture = value; this._checkSwitchMaterial(); this._updateMaterial(); }, type: cc.Texture2D, animatable: false, tooltip: false }, _color: cc.Color.WHITE, color: { get: function get() { return this._color.clone(); }, set: function set(value) { this._color.equals(value) || this._color.set(value); }, type: cc.Color, tooltip: false }, _fastMode: false, fastMode: { get: function get() { return this._fastMode; }, set: function set(value) { this._fastMode = value; }, animatable: false, tooltip: false }, autoSwitchMaterial: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.autoSwitchMaterial === oldValue) return; this.setVertsDirty(); } } }, setVertsDirty: function setVertsDirty() { this._checkSwitchMaterial(); this._updateMaterial(); this._super(); }, __preload: function __preload() { this._super(); this._checkSwitchMaterial(); }, _checkSwitchMaterial: function _checkSwitchMaterial() { if (this._assembler) { var material = this._materials[0]; if (!material) return; if (!this._texture) return; this._assembler.checkAndSwitchMaterial(this, this._texture, material); } }, onEnable: function onEnable() { this._super(); this.reset(); }, _updateMaterial: function _updateMaterial() { var material = this.getMaterial(0); var isMultiMaterial = material.material.isMultiSupport(); if (isMultiMaterial) { if (!this._texture) return; this._updateMultiTexId(material, this._texture); } else { var textureImpl = this._texture && this._texture.getImpl(); material.getProperty("texture") !== textureImpl && material.setProperty("texture", this._texture); } this._assembler && (isMultiMaterial && !this._assembler.isMulti || !isMultiMaterial && this._assembler.isMulti) && this._resetAssembler(); if (isMultiMaterial && this._texIdDirty && this._assembler) { if (!this._texture) return; this._assembler.updateTexId(this); this._texIdDirty = false; } BlendFunc.prototype._updateMaterial.call(this); }, onFocusInEditor: false, onLostFocusInEditor: false, reset: function reset() { this._points.length = 0; this._assembler && this._assembler._renderData.clear(); this._lastWPos.x = 0; this._lastWPos.y = 0; false; }, lateUpdate: function lateUpdate(dt) { this._assembler && this._assembler.update(this, dt); } }); cc.MotionStreak = module.exports = MotionStreak; }), { "../../core/utils/blend-func": 211, "../components/CCRenderComponent": 100 } ], 100: [ (function(require, module, exports) { "use strict"; var _assembler = _interopRequireDefault(require("../renderer/assembler")); var _materialVariant = _interopRequireDefault(require("../assets/material/material-variant")); var _valueTypes = require("../value-types"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Component = require("./CCComponent"); var RenderFlow = require("../renderer/render-flow"); var Material = require("../assets/material/CCMaterial"); var _temp_color = new _valueTypes.Color(); var EnableType = cc.Enum({ GLOBAL: 0, ENABLE: 1, DISABLE: 2 }); var RenderComponent = cc.Class({ name: "RenderComponent", extends: Component, editor: false, statics: { EnableType: EnableType }, properties: { _materials: { default: [], type: Material }, materials: { get: function get() { return this._materials; }, set: function set(val) { this._materials = val; this._activateMaterial(); }, type: [ Material ], displayName: "Materials", animatable: false } }, ctor: function ctor() { this._vertsDirty = true; this._texIdDirty = true; this._texId = 0; this._assembler = null; }, _resetAssembler: function _resetAssembler() { _assembler["default"].init(this); this._updateColor(); this._texId = 0; this.setVertsDirty(); }, __preload: function __preload() { this._resetAssembler(); this._activateMaterial(); }, onEnable: function onEnable() { this.node._renderComponent && (this.node._renderComponent.enabled = false); this.node._renderComponent = this; this.node._renderFlag |= RenderFlow.FLAG_OPACITY_COLOR; this.setVertsDirty(); }, onDisable: function onDisable() { this.node._renderComponent = null; this.disableRender(); }, onDestroy: function onDestroy() { var materials = this._materials; for (var i = 0; i < materials.length; i++) cc.pool.material.put(materials[i]); materials.length = 0; cc.pool.assembler.put(this._assembler); this.disableRender(); }, setVertsDirty: function setVertsDirty() { this._vertsDirty = true; this.markForRender(true); }, _on3DNodeChanged: function _on3DNodeChanged() { this._resetAssembler(); }, _validateRender: function _validateRender() {}, markForValidate: function markForValidate() { cc.RenderFlow.registerValidate(this); }, markForRender: function markForRender(enable) { var flag = RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA; if (enable) { this.node._renderFlag |= flag; this.markForValidate(); } else this.node._renderFlag &= ~flag; }, disableRender: function disableRender() { this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA); }, getMaterial: function getMaterial(index) { if (index < 0 || index >= this._materials.length) return null; var material = this._materials[index]; if (!material) return null; var instantiated = _materialVariant["default"].create(material, this); instantiated !== material && this.setMaterial(index, instantiated); return instantiated; }, getMaterials: function getMaterials() { var materials = this._materials; for (var i = 0; i < materials.length; i++) materials[i] = _materialVariant["default"].create(materials[i], this); return materials; }, setMaterial: function setMaterial(index, material) { if (material !== this._materials[index]) { material = _materialVariant["default"].create(material, this); this._materials[index] = material; } this._updateMaterial(); this.markForRender(true); return material; }, _getDefaultMaterial: function _getDefaultMaterial() { return Material.getBuiltinMaterial("2d-sprite"); }, _activateMaterial: function _activateMaterial() { var materials = this._materials; if (!materials[0]) { var material = this._getDefaultMaterial(); materials[0] = material; } for (var i = 0; i < materials.length; i++) materials[i] = _materialVariant["default"].create(materials[i], this); this._updateMaterial(); }, _updateMaterial: function _updateMaterial() {}, _updateColor: function _updateColor() { if (this._assembler.updateColor) { var premultiply = this.srcBlendFactor === cc.macro.BlendFactor.ONE; premultiply && _valueTypes.Color.premultiplyAlpha(_temp_color, this.node._color); var color = premultiply ? _temp_color._val : null; this._assembler.updateColor(this, color); } }, _checkBacth: function _checkBacth(renderer, cullingMask) { var material = this._materials[0]; if (material && material.getHash() !== renderer.material.getHash() || renderer.cullingMask !== cullingMask) { renderer._flush(); renderer.node = material.getDefine("CC_USE_MODEL") ? this.node : renderer._dummyNode; renderer.material = material; renderer.cullingMask = cullingMask; } }, _updateMultiTexId: function _updateMultiTexId(material, texture) { var multi = material.material.getMultiHandler(); var spTexture = texture; var nSpTexture = spTexture.getImpl(); var same = 0 === this._texId ? material.getProperty("texture") !== nSpTexture : multi.getTexture(this._texId) !== nSpTexture; if (same) { var isChanged = Object.prototype.hasOwnProperty.call(material._effect._passes["0"]._properties, "texture"); var texId = isChanged ? -1 : multi.getIndex(nSpTexture); if (-1 !== texId) { this._texId = texId; this._texIdDirty = true; } else { material.setProperty("texture", spTexture); if (0 !== this._texId) { this._texId = 0; this._texIdDirty = true; } } } else this._texIdDirty = false; } }); cc.RenderComponent = module.exports = RenderComponent; }), { "../assets/material/CCMaterial": 76, "../assets/material/material-variant": 83, "../renderer/assembler": 157, "../renderer/render-flow": 161, "../value-types": 232, "./CCComponent": 92 } ], 101: [ (function(require, module, exports) { "use strict"; var _materialVariant = _interopRequireDefault(require("../assets/material/material-variant")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var js = require("../platform/js"); var macro = require("../platform/CCMacro"); var textUtils = require("../utils/text-utils"); var HtmlTextParser = require("../utils/html-text-parser"); var _htmlTextParser = new HtmlTextParser(); var HorizontalAlign = macro.TextAlignment; var VerticalAlign = macro.VerticalTextAlignment; var RichTextChildName = "RICHTEXT_CHILD"; var RichTextChildImageName = "RICHTEXT_Image_CHILD"; var CacheMode = cc.Label.CacheMode; var RenderComponent = require("./CCRenderComponent"); function debounce(func, wait, immediate) { var timeout; return function() { var context = this; var later = function later() { timeout = null; immediate || func.apply(context, arguments); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); callNow && func.apply(context, arguments); }; } var pool = new js.Pool(function(node) { false; false; if (!cc.isValid(node)) return false; var outline = node.getComponent(cc.LabelOutline); outline && (outline.width = 0); return true; }, 20); pool.get = function(string, richtext) { var labelNode = this._get(); if (!labelNode) { labelNode = new cc.PrivateNode(RichTextChildName); labelNode._objFlags |= cc.Object.Flags.DontSave; } labelNode.setPosition(0, 0); labelNode.setAnchorPoint(.5, .5); labelNode.skewX = 0; var labelComponent = labelNode.getComponent(cc.Label); labelComponent || (labelComponent = labelNode.addComponent(cc.Label)); labelComponent.string = ""; labelComponent.horizontalAlign = HorizontalAlign.LEFT; labelComponent.verticalAlign = VerticalAlign.CENTER; labelComponent._forceUseCanvas = true; return labelNode; }; var RichText = cc.Class({ name: "cc.RichText", extends: cc.Component, ctor: function ctor() { this._textArray = null; this._labelSegments = []; this._labelSegmentsCache = []; this._linesWidth = []; false; this._updateRichTextStatus = this._updateRichText; }, editor: false, properties: { string: { default: "RichText", multiline: true, tooltip: false, notify: function notify() { this._updateRichTextStatus(); } }, horizontalAlign: { default: HorizontalAlign.LEFT, type: HorizontalAlign, tooltip: false, animatable: false, notify: function notify(oldValue) { if (this.horizontalAlign === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, fontSize: { default: 40, tooltip: false, notify: function notify(oldValue) { if (this.fontSize === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, _fontFamily: "Arial", fontFamily: { tooltip: false, get: function get() { return this._fontFamily; }, set: function set(value) { if (this._fontFamily === value) return; this._fontFamily = value; this._layoutDirty = true; this._updateRichTextStatus(); }, animatable: false }, font: { default: null, type: cc.TTFFont, tooltip: false, notify: function notify(oldValue) { if (this.font === oldValue) return; this._layoutDirty = true; if (this.font) { false; this.useSystemFont = false; this._onTTFLoaded(); } else this.useSystemFont = true; this._updateRichTextStatus(); } }, _isSystemFontUsed: true, useSystemFont: { get: function get() { return this._isSystemFontUsed; }, set: function set(value) { if (this._isSystemFontUsed === value) return; this._isSystemFontUsed = value; false; this._layoutDirty = true; this._updateRichTextStatus(); }, animatable: false, tooltip: false }, cacheMode: { default: CacheMode.NONE, type: CacheMode, tooltip: false, notify: function notify(oldValue) { if (this.cacheMode === oldValue) return; this._updateRichTextStatus(); }, animatable: false }, maxWidth: { default: 0, tooltip: false, notify: function notify(oldValue) { if (this.maxWidth === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, lineHeight: { default: 40, tooltip: false, notify: function notify(oldValue) { if (this.lineHeight === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, imageAtlas: { default: null, type: cc.SpriteAtlas, tooltip: false, notify: function notify(oldValue) { if (this.imageAtlas === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, handleTouchEvent: { default: true, tooltip: false, notify: function notify(oldValue) { if (this.handleTouchEvent === oldValue) return; this.enabledInHierarchy && (this.handleTouchEvent ? this._addEventListeners() : this._removeEventListeners()); } }, customMaterial: { default: null, type: cc.Material, notify: function notify(oldValue) { if (this.customMaterial === oldValue) return; var material = null == this.customMaterial ? this._getDefaultMaterial() : this.customMaterial; for (var i = 0; i < this._labelSegments.length; i++) { var labelComponent = this._labelSegments[i].getComponent(cc.Label); labelComponent && (0 === labelComponent._materials.length ? labelComponent._materials[0] = _materialVariant["default"].create(material, labelComponent) : labelComponent.setMaterial(0, material)); var spriteComponent = this._labelSegments[i].getComponent(cc.Sprite); spriteComponent && (0 === spriteComponent._materials.length ? spriteComponent._materials[0] = _materialVariant["default"].create(material, spriteComponent) : spriteComponent.setMaterial(0, material)); } for (var _i = 0; _i < this._labelSegmentsCache.length; _i++) { var _labelComponent = this._labelSegmentsCache[_i].getComponent(cc.Label); _labelComponent && (0 === _labelComponent._materials.length ? _labelComponent._materials[0] = _materialVariant["default"].create(material, _labelComponent) : _labelComponent.setMaterial(0, material)); } } }, autoSwitchMaterial: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.autoSwitchMaterial === oldValue) return; for (var i = 0; i < this._labelSegments.length; i++) { var labelComponent = this._labelSegments[i].getComponent(cc.Label); labelComponent && (labelComponent.autoSwitchMaterial = this.autoSwitchMaterial); var spriteComponent = this._labelSegments[i].getComponent(cc.Sprite); spriteComponent && (spriteComponent.autoSwitchMaterial = this.autoSwitchMaterial); } for (var _i2 = 0; _i2 < this._labelSegmentsCache.length; _i2++) { var _labelComponent2 = this._labelSegmentsCache[_i2].getComponent(cc.Label); _labelComponent2 && (_labelComponent2.autoSwitchMaterial = this.autoSwitchMaterial); } } }, allowDynamicAtlas: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.allowDynamicAtlas === oldValue) return; for (var i = 0; i < this._labelSegments.length; i++) { var labelComponent = this._labelSegments[i].getComponent(cc.Label); labelComponent && (labelComponent.allowDynamicAtlas = this.allowDynamicAtlas); var spriteComponent = this._labelSegments[i].getComponent(cc.Sprite); spriteComponent && (spriteComponent.allowDynamicAtlas = this.allowDynamicAtlas); } for (var _i3 = 0; _i3 < this._labelSegmentsCache.length; _i3++) { var _labelComponent3 = this._labelSegmentsCache[_i3].getComponent(cc.Label); _labelComponent3 && (_labelComponent3.allowDynamicAtlas = this.allowDynamicAtlas); } } }, enableRetina: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.enableRetina === oldValue) return; for (var i = 0; i < this._labelSegments.length; i++) { var labelComponent = this._labelSegments[i].getComponent(cc.Label); labelComponent && (labelComponent.enableRetina = this.enableRetina); } for (var _i4 = 0; _i4 < this._labelSegmentsCache.length; _i4++) { var _labelComponent4 = this._labelSegmentsCache[_i4].getComponent(cc.Label); _labelComponent4 && (_labelComponent4.enableRetina = this.enableRetina); } } } }, statics: { HorizontalAlign: HorizontalAlign, VerticalAlign: VerticalAlign }, onEnable: function onEnable() { this.handleTouchEvent && this._addEventListeners(); this._onTTFLoaded(); this._activateChildren(true); }, onDisable: function onDisable() { this.handleTouchEvent && this._removeEventListeners(); this._activateChildren(false); }, _onColorChanged: function _onColorChanged(parentColor) { var children = this.node.children; children.forEach((function(childNode) { childNode.color = parentColor; })); }, _addEventListeners: function _addEventListeners() { this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.on(cc.Node.EventType.COLOR_CHANGED, this._onColorChanged, this); }, _removeEventListeners: function _removeEventListeners() { this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.off(cc.Node.EventType.COLOR_CHANGED, this._onColorChanged, this); }, _updateLabelSegmentTextAttributes: function _updateLabelSegmentTextAttributes() { this._labelSegments.forEach(function(item) { this._applyTextAttribute(item, null, true); }.bind(this)); }, _createFontLabel: function _createFontLabel(string) { return pool.get(string, this); }, _onTTFLoaded: function _onTTFLoaded() { if (this.font instanceof cc.TTFFont) if (this.font._nativeAsset) { this._layoutDirty = true; this._updateRichTextStatus(); } else { var self = this; cc.assetManager.postLoadNative(this.font, (function(err) { self._layoutDirty = true; self._updateRichTextStatus(); })); } else { this._layoutDirty = true; this._updateRichTextStatus(); } }, _measureText: function _measureText(styleIndex, string) { var self = this; var func = function func(string) { var label; if (0 === self._labelSegmentsCache.length) { label = self._createFontLabel(string); self._labelSegmentsCache.push(label); } else label = self._labelSegmentsCache[0]; label._styleIndex = styleIndex; self._applyTextAttribute(label, string, true); var labelSize = label.getContentSize(); return labelSize.width; }; return string ? func(string) : func; }, _onTouchEnded: function _onTouchEnded(event) { var _this = this; var components = this.node.getComponents(cc.Component); var _loop = function _loop(i) { var labelSegment = _this._labelSegments[i]; var clickHandler = labelSegment._clickHandler; var clickParam = labelSegment._clickParam; if (clickHandler && _this._containsTouchLocation(labelSegment, event.touch.getLocation())) { components.forEach((function(component) { component.enabledInHierarchy && component[clickHandler] && component[clickHandler](event, clickParam); })); event.stopPropagation(); } }; for (var i = 0; i < this._labelSegments.length; ++i) _loop(i); }, _containsTouchLocation: function _containsTouchLocation(label, point) { var myRect = label.getBoundingBoxToWorld(); return myRect.contains(point); }, _resetState: function _resetState() { var children = this.node.children; for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; if (child.name === RichTextChildName || child.name === RichTextChildImageName) { child.parent === this.node ? child.parent = null : children.splice(i, 1); child.name === RichTextChildName && pool.put(child); } } this._labelSegments.length = 0; this._labelSegmentsCache.length = 0; this._linesWidth.length = 0; this._lineOffsetX = 0; this._lineCount = 1; this._labelWidth = 0; this._labelHeight = 0; this._layoutDirty = true; }, onRestore: false, _activateChildren: function _activateChildren(active) { for (var i = this.node.children.length - 1; i >= 0; i--) { var child = this.node.children[i]; child.name !== RichTextChildName && child.name !== RichTextChildImageName || (child.active = active); } }, _addLabelSegment: function _addLabelSegment(stringToken, styleIndex) { var labelSegment; labelSegment = 0 === this._labelSegmentsCache.length ? this._createFontLabel(stringToken) : this._labelSegmentsCache.pop(); labelSegment._styleIndex = styleIndex; labelSegment._lineCount = this._lineCount; labelSegment.active = this.node.active; labelSegment.setAnchorPoint(0, 0); this._applyTextAttribute(labelSegment, stringToken, false); this.node.addChild(labelSegment); this._labelSegments.push(labelSegment); return labelSegment; }, _updateRichTextWithMaxWidth: function _updateRichTextWithMaxWidth(labelString, labelWidth, styleIndex) { var fragmentWidth = labelWidth; var labelSegment; if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this.maxWidth) { var checkStartIndex = 0; while (this._lineOffsetX <= this.maxWidth) { var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length); var checkString = labelString.substr(checkStartIndex, checkEndIndex); var checkStringWidth = this._measureText(styleIndex, checkString); if (!(this._lineOffsetX + checkStringWidth <= this.maxWidth)) { if (checkStartIndex > 0) { var remainingString = labelString.substr(0, checkStartIndex); this._addLabelSegment(remainingString, styleIndex); labelString = labelString.substr(checkStartIndex, labelString.length); fragmentWidth = this._measureText(styleIndex, labelString); } this._updateLineInfo(); break; } this._lineOffsetX += checkStringWidth; checkStartIndex += checkEndIndex; } } if (fragmentWidth > this.maxWidth) { var fragments = textUtils.fragmentText(labelString, fragmentWidth, this.maxWidth, this._measureText(styleIndex)); for (var k = 0; k < fragments.length; ++k) { var splitString = fragments[k]; labelSegment = this._addLabelSegment(splitString, styleIndex); var labelSize = labelSegment.getContentSize(); this._lineOffsetX += labelSize.width; fragments.length > 1 && k < fragments.length - 1 && this._updateLineInfo(); } } else { this._lineOffsetX += fragmentWidth; this._addLabelSegment(labelString, styleIndex); } }, _isLastComponentCR: function _isLastComponentCR(stringToken) { return stringToken.length - 1 === stringToken.lastIndexOf("\n"); }, _updateLineInfo: function _updateLineInfo() { this._linesWidth.push(this._lineOffsetX); this._lineOffsetX = 0; this._lineCount++; }, _needsUpdateTextLayout: function _needsUpdateTextLayout(newTextArray) { if (this._layoutDirty || !this._textArray || !newTextArray) return true; if (this._textArray.length !== newTextArray.length) return true; for (var i = 0; i < this._textArray.length; ++i) { var oldItem = this._textArray[i]; var newItem = newTextArray[i]; if (oldItem.text !== newItem.text) return true; var oldStyle = oldItem.style, newStyle = newItem.style; if (oldStyle) { if (newStyle) { if (!oldStyle.outline !== !newStyle.outline) return true; if (oldStyle.size !== newStyle.size || !oldStyle.italic !== !newStyle.italic || oldStyle.isImage !== newStyle.isImage) return true; if (oldStyle.src !== newStyle.src || oldStyle.imageAlign !== newStyle.imageAlign || oldStyle.imageHeight !== newStyle.imageHeight || oldStyle.imageWidth !== newStyle.imageWidth || oldStyle.imageOffset !== newStyle.imageOffset) return true; } else if (oldStyle.size || oldStyle.italic || oldStyle.isImage || oldStyle.outline) return true; } else if (newStyle && (newStyle.size || newStyle.italic || newStyle.isImage || newStyle.outline)) return true; } return false; }, _addRichTextImageElement: function _addRichTextImageElement(richTextElement) { var spriteFrameName = richTextElement.style.src; var spriteFrame = this.imageAtlas.getSpriteFrame(spriteFrameName); if (spriteFrame) { var spriteNode = new cc.PrivateNode(RichTextChildImageName); spriteNode._objFlags |= cc.Object.Flags.DontSave; var spriteComponent = spriteNode.addComponent(cc.Sprite); spriteComponent.autoSwitchMaterial = this.autoSwitchMaterial; spriteComponent.allowDynamicAtlas = this.allowDynamicAtlas; this.customMaterial && (0 === spriteComponent._materials.length ? spriteComponent._materials[0] = _materialVariant["default"].create(this.customMaterial, spriteComponent) : spriteComponent._materials[0].material !== this.customMaterial && spriteComponent.setMaterial(0, this.customMaterial)); switch (richTextElement.style.imageAlign) { case "top": spriteNode.setAnchorPoint(0, 1); break; case "center": spriteNode.setAnchorPoint(0, .5); break; default: spriteNode.setAnchorPoint(0, 0); } richTextElement.style.imageOffset && (spriteNode._imageOffset = richTextElement.style.imageOffset); spriteComponent.type = cc.Sprite.Type.SLICED; spriteComponent.sizeMode = cc.Sprite.SizeMode.CUSTOM; this.node.addChild(spriteNode); this._labelSegments.push(spriteNode); var spriteRect = spriteFrame.getRect(); var scaleFactor = 1; var spriteWidth = spriteRect.width; var spriteHeight = spriteRect.height; var expectWidth = richTextElement.style.imageWidth; var expectHeight = richTextElement.style.imageHeight; if (expectHeight > 0) { scaleFactor = expectHeight / spriteHeight; spriteWidth *= scaleFactor; spriteHeight *= scaleFactor; } else { scaleFactor = this.lineHeight / spriteHeight; spriteWidth *= scaleFactor; spriteHeight *= scaleFactor; } expectWidth > 0 && (spriteWidth = expectWidth); if (this.maxWidth > 0) { this._lineOffsetX + spriteWidth > this.maxWidth && this._updateLineInfo(); this._lineOffsetX += spriteWidth; } else { this._lineOffsetX += spriteWidth; this._lineOffsetX > this._labelWidth && (this._labelWidth = this._lineOffsetX); } spriteComponent.spriteFrame = spriteFrame; spriteNode.setContentSize(spriteWidth, spriteHeight); spriteNode._lineCount = this._lineCount; if (richTextElement.style.event) { richTextElement.style.event.click && (spriteNode._clickHandler = richTextElement.style.event.click); richTextElement.style.event.param ? spriteNode._clickParam = richTextElement.style.event.param : spriteNode._clickParam = ""; } else spriteNode._clickHandler = null; } else cc.warnID(4400); }, _updateRichText: function _updateRichText() { if (!this.enabledInHierarchy) return; var newTextArray = _htmlTextParser.parse(this.string); if (!this._needsUpdateTextLayout(newTextArray)) { this._textArray = newTextArray; this._updateLabelSegmentTextAttributes(); return; } this._textArray = newTextArray; this._resetState(); var lastEmptyLine = false; var label; var labelSize; for (var i = 0; i < this._textArray.length; ++i) { var richTextElement = this._textArray[i]; var text = richTextElement.text; if ("" === text) { if (richTextElement.style && richTextElement.style.newline) { this._updateLineInfo(); continue; } if (richTextElement.style && richTextElement.style.isImage && this.imageAtlas) { this._addRichTextImageElement(richTextElement); continue; } } var multilineTexts = text.split("\n"); for (var j = 0; j < multilineTexts.length; ++j) { var labelString = multilineTexts[j]; if ("" === labelString) { if (this._isLastComponentCR(text) && j === multilineTexts.length - 1) continue; this._updateLineInfo(); lastEmptyLine = true; continue; } lastEmptyLine = false; if (this.maxWidth > 0) { var labelWidth = this._measureText(i, labelString); this._updateRichTextWithMaxWidth(labelString, labelWidth, i); multilineTexts.length > 1 && j < multilineTexts.length - 1 && this._updateLineInfo(); } else { label = this._addLabelSegment(labelString, i); labelSize = label.getContentSize(); this._lineOffsetX += labelSize.width; this._lineOffsetX > this._labelWidth && (this._labelWidth = this._lineOffsetX); multilineTexts.length > 1 && j < multilineTexts.length - 1 && this._updateLineInfo(); } } } lastEmptyLine || this._linesWidth.push(this._lineOffsetX); this.maxWidth > 0 && (this._labelWidth = this.maxWidth); this._labelHeight = (this._lineCount + textUtils.BASELINE_RATIO) * this.lineHeight; this.node.setContentSize(this._labelWidth, this._labelHeight); this._updateRichTextPosition(); this._layoutDirty = false; }, _getFirstWordLen: function _getFirstWordLen(text, startIndex, textLen) { var character = text.charAt(startIndex); if (textUtils.isUnicodeCJK(character) || textUtils.isUnicodeSpace(character)) return 1; var len = 1; for (var index = startIndex + 1; index < textLen; ++index) { character = text.charAt(index); if (textUtils.isUnicodeSpace(character) || textUtils.isUnicodeCJK(character)) break; len++; } return len; }, _updateRichTextPosition: function _updateRichTextPosition() { var nextTokenX = 0; var nextLineIndex = 1; var totalLineCount = this._lineCount; for (var i = 0; i < this._labelSegments.length; ++i) { var label = this._labelSegments[i]; var lineCount = label._lineCount; if (lineCount > nextLineIndex) { nextTokenX = 0; nextLineIndex = lineCount; } var lineOffsetX = 0; switch (this.horizontalAlign) { case HorizontalAlign.LEFT: lineOffsetX = -this._labelWidth / 2; break; case HorizontalAlign.CENTER: lineOffsetX = -this._linesWidth[lineCount - 1] / 2; break; case HorizontalAlign.RIGHT: lineOffsetX = this._labelWidth / 2 - this._linesWidth[lineCount - 1]; } label.x = nextTokenX + lineOffsetX; var labelSize = label.getContentSize(); label.y = this.lineHeight * (totalLineCount - lineCount) - this._labelHeight / 2; lineCount === nextLineIndex && (nextTokenX += labelSize.width); var sprite = label.getComponent(cc.Sprite); if (sprite) { var lineHeightSet = this.lineHeight; var lineHeightReal = this.lineHeight * (1 + textUtils.BASELINE_RATIO); switch (label.anchorY) { case 1: label.y += lineHeightSet + (lineHeightReal - lineHeightSet) / 2; break; case .5: label.y += lineHeightReal / 2; break; default: label.y += (lineHeightReal - lineHeightSet) / 2; } if (label._imageOffset) { var offsets = label._imageOffset.split(","); if (1 === offsets.length && offsets[0]) { var offsetY = parseFloat(offsets[0]); Number.isInteger(offsetY) && (label.y += offsetY); } else if (2 === offsets.length) { var offsetX = parseFloat(offsets[0]); var _offsetY = parseFloat(offsets[1]); Number.isInteger(offsetX) && (label.x += offsetX); Number.isInteger(_offsetY) && (label.y += _offsetY); } } } var outline = label.getComponent(cc.LabelOutline); outline && outline.width && (label.y = label.y - outline.width); } }, _convertLiteralColorValue: function _convertLiteralColorValue(color) { var colorValue = color.toUpperCase(); if (cc.Color[colorValue]) return cc.Color[colorValue]; var out = cc.color(); return out.fromHEX(color); }, _applyTextAttribute: function _applyTextAttribute(labelNode, string, force) { var labelComponent = labelNode.getComponent(cc.Label); if (!labelComponent) return; var index = labelNode._styleIndex; var textStyle = null; this._textArray[index] && (textStyle = this._textArray[index].style); textStyle && textStyle.color ? labelNode.color = this._convertLiteralColorValue(textStyle.color) : labelNode.color = this.node.color; labelComponent.cacheMode = this.cacheMode; labelComponent.autoSwitchMaterial = this.autoSwitchMaterial; labelComponent.allowDynamicAtlas = this.allowDynamicAtlas; labelComponent.enableRetina = this.enableRetina; this.customMaterial && (0 === labelComponent._materials.length ? labelComponent._materials[0] = _materialVariant["default"].create(this.customMaterial, labelComponent) : labelComponent._materials[0].material !== this.customMaterial && labelComponent.setMaterial(0, this.customMaterial)); var isAsset = this.font instanceof cc.Font; isAsset && !this._isSystemFontUsed ? labelComponent.font = this.font : labelComponent.fontFamily = this.fontFamily; labelComponent.useSystemFont = this._isSystemFontUsed; labelComponent.lineHeight = this.lineHeight; labelComponent.enableBold = textStyle && textStyle.bold; labelComponent.enableItalics = textStyle && textStyle.italic; textStyle && textStyle.italic && (labelNode.skewX = 12); labelComponent.enableUnderline = textStyle && textStyle.underline; if (textStyle && textStyle.outline) { var labelOutlineComponent = labelNode.getComponent(cc.LabelOutline); labelOutlineComponent || (labelOutlineComponent = labelNode.addComponent(cc.LabelOutline)); labelOutlineComponent.color = this._convertLiteralColorValue(textStyle.outline.color); labelOutlineComponent.width = textStyle.outline.width; } textStyle && textStyle.size ? labelComponent.fontSize = textStyle.size : labelComponent.fontSize = this.fontSize; if (null !== string) { "string" !== typeof string && (string = "" + string); labelComponent.string = string; } force && labelComponent._forceUpdateRenderData(); if (textStyle && textStyle.event) { textStyle.event.click && (labelNode._clickHandler = textStyle.event.click); textStyle.event.param ? labelNode._clickParam = textStyle.event.param : labelNode._clickParam = ""; } else labelNode._clickHandler = null; }, onDestroy: function onDestroy() { for (var i = 0; i < this._labelSegments.length; ++i) { this._labelSegments[i].removeFromParent(); pool.put(this._labelSegments[i]); } } }); cc.RichText = module.exports = RichText; }), { "../assets/material/material-variant": 83, "../platform/CCMacro": 134, "../platform/js": 150, "../utils/html-text-parser": 215, "../utils/text-utils": 224, "./CCRenderComponent": 100 } ], 102: [ (function(require, module, exports) { "use strict"; var misc = require("../utils/misc"); var Component = require("./CCComponent"); var GETTINGSHORTERFACTOR = 20; var Direction = cc.Enum({ HORIZONTAL: 0, VERTICAL: 1 }); var Scrollbar = cc.Class({ name: "cc.Scrollbar", extends: require("./CCComponent"), editor: false, properties: { _scrollView: null, _touching: false, _autoHideRemainingTime: { default: 0, serializable: false }, _opacity: 255, handle: { default: null, type: cc.Sprite, tooltip: false, notify: function notify() { this._onScroll(cc.v2(0, 0)); }, animatable: false }, direction: { default: Direction.HORIZONTAL, type: Direction, tooltip: false, notify: function notify() { this._onScroll(cc.v2(0, 0)); }, animatable: false }, enableAutoHide: { default: true, animatable: false, tooltip: false }, autoHideTime: { default: 1, animatable: false, tooltip: false } }, statics: { Direction: Direction }, setTargetScrollView: function setTargetScrollView(scrollView) { this._scrollView = scrollView; }, _convertToScrollViewSpace: function _convertToScrollViewSpace(content) { var scrollViewNode = this._scrollView.node; var worldSpacePos = content.convertToWorldSpaceAR(cc.v2(-content.anchorX * content.width, -content.anchorY * content.height)); var scrollViewSpacePos = scrollViewNode.convertToNodeSpaceAR(worldSpacePos); scrollViewSpacePos.x += scrollViewNode.anchorX * scrollViewNode.width; scrollViewSpacePos.y += scrollViewNode.anchorY * scrollViewNode.height; return scrollViewSpacePos; }, _setOpacity: function _setOpacity(opacity) { if (this.handle) { this.node.opacity = opacity; this.handle.node.opacity = opacity; } }, _onScroll: function _onScroll(outOfBoundary) { if (this._scrollView) { var content = this._scrollView.content; if (content) { var contentSize = content.getContentSize(); var scrollViewSize = this._scrollView.node.getContentSize(); var handleNodeSize = this.node.getContentSize(); if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) return; if (this.enableAutoHide) { this._autoHideRemainingTime = this.autoHideTime; this._setOpacity(this._opacity); } var contentMeasure = 0; var scrollViewMeasure = 0; var outOfBoundaryValue = 0; var contentPosition = 0; var handleNodeMeasure = 0; if (this.direction === Direction.HORIZONTAL) { contentMeasure = contentSize.width; scrollViewMeasure = scrollViewSize.width; handleNodeMeasure = handleNodeSize.width; outOfBoundaryValue = outOfBoundary.x; contentPosition = -this._convertToScrollViewSpace(content).x; } else if (this.direction === Direction.VERTICAL) { contentMeasure = contentSize.height; scrollViewMeasure = scrollViewSize.height; handleNodeMeasure = handleNodeSize.height; outOfBoundaryValue = outOfBoundary.y; contentPosition = -this._convertToScrollViewSpace(content).y; } var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue); var position = this._calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length); this._updateLength(length); this._updateHanlderPosition(position); } } }, _updateHanlderPosition: function _updateHanlderPosition(position) { if (this.handle) { var oldPosition = this._fixupHandlerPosition(); this.handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y); } }, _fixupHandlerPosition: function _fixupHandlerPosition() { var barSize = this.node.getContentSize(); var barAnchor = this.node.getAnchorPoint(); var handleSize = this.handle.node.getContentSize(); var handleParent = this.handle.node.parent; var leftBottomWorldPosition = this.node.convertToWorldSpaceAR(cc.v2(-barSize.width * barAnchor.x, -barSize.height * barAnchor.y)); var fixupPosition = handleParent.convertToNodeSpaceAR(leftBottomWorldPosition); this.direction === Direction.HORIZONTAL ? fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2) : this.direction === Direction.VERTICAL && (fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y)); this.handle.node.setPosition(fixupPosition); return fixupPosition; }, _onTouchBegan: function _onTouchBegan() { if (!this.enableAutoHide) return; this._touching = true; }, _conditionalDisableScrollBar: function _conditionalDisableScrollBar(contentSize, scrollViewSize) { if (contentSize.width <= scrollViewSize.width && this.direction === Direction.HORIZONTAL) return true; if (contentSize.height <= scrollViewSize.height && this.direction === Direction.VERTICAL) return true; return false; }, _onTouchEnded: function _onTouchEnded() { if (!this.enableAutoHide) return; this._touching = false; if (this.autoHideTime <= 0) return; if (this._scrollView) { var content = this._scrollView.content; if (content) { var contentSize = content.getContentSize(); var scrollViewSize = this._scrollView.node.getContentSize(); if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) return; } } this._autoHideRemainingTime = this.autoHideTime; }, _calculateLength: function _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) { var denominatorValue = contentMeasure; outOfBoundary && (denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR); var lengthRation = scrollViewMeasure / denominatorValue; return handleNodeMeasure * lengthRation; }, _calculatePosition: function _calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) { var denominatorValue = contentMeasure - scrollViewMeasure; outOfBoundary && (denominatorValue += Math.abs(outOfBoundary)); var positionRatio = 0; if (denominatorValue) { positionRatio = contentPosition / denominatorValue; positionRatio = misc.clamp01(positionRatio); } var position = (handleNodeMeasure - actualLenth) * positionRatio; return this.direction === Direction.VERTICAL ? cc.v2(0, position) : cc.v2(position, 0); }, _updateLength: function _updateLength(length) { if (this.handle) { var handleNode = this.handle.node; var handleNodeSize = handleNode.getContentSize(); handleNode.setAnchorPoint(cc.v2(0, 0)); this.direction === Direction.HORIZONTAL ? handleNode.setContentSize(length, handleNodeSize.height) : handleNode.setContentSize(handleNodeSize.width, length); } }, _processAutoHide: function _processAutoHide(deltaTime) { if (!this.enableAutoHide || this._autoHideRemainingTime <= 0) return; if (this._touching) return; this._autoHideRemainingTime -= deltaTime; if (this._autoHideRemainingTime <= this.autoHideTime) { this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); var opacity = this._opacity * (this._autoHideRemainingTime / this.autoHideTime); this._setOpacity(opacity); } }, start: function start() { this.enableAutoHide && this._setOpacity(0); }, hide: function hide() { this._autoHideRemainingTime = 0; this._setOpacity(0); }, show: function show() { this._autoHideRemainingTime = this.autoHideTime; this._setOpacity(this._opacity); }, update: function update(dt) { this._processAutoHide(dt); } }); cc.Scrollbar = module.exports = Scrollbar; }), { "../utils/misc": 217, "./CCComponent": 92 } ], 103: [ (function(require, module, exports) { "use strict"; var NodeEvent = require("../CCNode").EventType; var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; var OUT_OF_BOUNDARY_BREAKING_FACTOR = .05; var EPSILON = 1e-4; var MOVEMENT_FACTOR = .7; var _tempPoint = cc.v2(); var _tempPrevPoint = cc.v2(); var quintEaseOut = function quintEaseOut(time) { time -= 1; return time * time * time * time * time + 1; }; var getTimeInMilliseconds = function getTimeInMilliseconds() { var currentTime = new Date(); return currentTime.getMilliseconds(); }; var EventType = cc.Enum({ SCROLL_TO_TOP: 0, SCROLL_TO_BOTTOM: 1, SCROLL_TO_LEFT: 2, SCROLL_TO_RIGHT: 3, SCROLLING: 4, BOUNCE_TOP: 5, BOUNCE_BOTTOM: 6, BOUNCE_LEFT: 7, BOUNCE_RIGHT: 8, SCROLL_ENDED: 9, TOUCH_UP: 10, AUTOSCROLL_ENDED_WITH_THRESHOLD: 11, SCROLL_BEGAN: 12 }); var eventMap = { "scroll-to-top": EventType.SCROLL_TO_TOP, "scroll-to-bottom": EventType.SCROLL_TO_BOTTOM, "scroll-to-left": EventType.SCROLL_TO_LEFT, "scroll-to-right": EventType.SCROLL_TO_RIGHT, scrolling: EventType.SCROLLING, "bounce-bottom": EventType.BOUNCE_BOTTOM, "bounce-left": EventType.BOUNCE_LEFT, "bounce-right": EventType.BOUNCE_RIGHT, "bounce-top": EventType.BOUNCE_TOP, "scroll-ended": EventType.SCROLL_ENDED, "touch-up": EventType.TOUCH_UP, "scroll-ended-with-threshold": EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD, "scroll-began": EventType.SCROLL_BEGAN }; var ScrollView = cc.Class({ name: "cc.ScrollView", extends: require("./CCViewGroup"), editor: false, ctor: function ctor() { this._topBoundary = 0; this._bottomBoundary = 0; this._leftBoundary = 0; this._rightBoundary = 0; this._touchMoveDisplacements = []; this._touchMoveTimeDeltas = []; this._touchMovePreviousTimestamp = 0; this._touchMoved = false; this._autoScrolling = false; this._autoScrollAttenuate = false; this._autoScrollStartPosition = cc.v2(0, 0); this._autoScrollTargetDelta = cc.v2(0, 0); this._autoScrollTotalTime = 0; this._autoScrollAccumulatedTime = 0; this._autoScrollCurrentlyOutOfBoundary = false; this._autoScrollBraking = false; this._autoScrollBrakingStartPosition = cc.v2(0, 0); this._outOfBoundaryAmount = cc.v2(0, 0); this._outOfBoundaryAmountDirty = true; this._stopMouseWheel = false; this._mouseWheelEventElapsedTime = 0; this._isScrollEndedWithThresholdEventFired = false; this._scrollEventEmitMask = 0; this._isBouncing = false; this._scrolling = false; }, properties: { content: { default: void 0, type: cc.Node, tooltip: false, formerlySerializedAs: "content", notify: function notify(oldValue) { this._calculateBoundary(); } }, horizontal: { default: true, animatable: false, tooltip: false }, vertical: { default: true, animatable: false, tooltip: false }, inertia: { default: true, tooltip: false }, brake: { default: .5, type: cc.Float, range: [ 0, 1, .1 ], tooltip: false }, elastic: { default: true, animatable: false, tooltip: false }, bounceDuration: { default: 1, range: [ 0, 10 ], tooltip: false }, horizontalScrollBar: { default: void 0, type: cc.Scrollbar, tooltip: false, notify: function notify() { if (this.horizontalScrollBar) { this.horizontalScrollBar.setTargetScrollView(this); this._updateScrollBar(0); } }, animatable: false }, verticalScrollBar: { default: void 0, type: cc.Scrollbar, tooltip: false, notify: function notify() { if (this.verticalScrollBar) { this.verticalScrollBar.setTargetScrollView(this); this._updateScrollBar(0); } }, animatable: false }, scrollEvents: { default: [], type: cc.Component.EventHandler, tooltip: false }, cancelInnerEvents: { default: true, animatable: false, tooltip: false }, _view: { get: function get() { if (this.content) return this.content.parent; } } }, statics: { EventType: EventType }, scrollToBottom: function scrollToBottom(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(0, 0), applyToHorizontal: false, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta, true); }, scrollToTop: function scrollToTop(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(0, 1), applyToHorizontal: false, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToLeft: function scrollToLeft(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(0, 0), applyToHorizontal: true, applyToVertical: false }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToRight: function scrollToRight(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(1, 0), applyToHorizontal: true, applyToVertical: false }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToTopLeft: function scrollToTopLeft(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(0, 1), applyToHorizontal: true, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToTopRight: function scrollToTopRight(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(1, 1), applyToHorizontal: true, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToBottomLeft: function scrollToBottomLeft(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(0, 0), applyToHorizontal: true, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToBottomRight: function scrollToBottomRight(timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(1, 0), applyToHorizontal: true, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToOffset: function scrollToOffset(offset, timeInSecond, attenuated) { var maxScrollOffset = this.getMaxScrollOffset(); var anchor = cc.v2(0, 0); 0 === maxScrollOffset.x ? anchor.x = 0 : anchor.x = offset.x / maxScrollOffset.x; 0 === maxScrollOffset.y ? anchor.y = 1 : anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y; this.scrollTo(anchor, timeInSecond, attenuated); }, getScrollOffset: function getScrollOffset() { var topDelta = this._getContentTopBoundary() - this._topBoundary; var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; return cc.v2(leftDeta, topDelta); }, getMaxScrollOffset: function getMaxScrollOffset() { var viewSize = this._view.getContentSize(); var contentSize = this.content.getContentSize(); var horizontalMaximizeOffset = contentSize.width - viewSize.width; var verticalMaximizeOffset = contentSize.height - viewSize.height; horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0; verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0; return cc.v2(horizontalMaximizeOffset, verticalMaximizeOffset); }, scrollToPercentHorizontal: function scrollToPercentHorizontal(percent, timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(percent, 0), applyToHorizontal: true, applyToVertical: false }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollTo: function scrollTo(anchor, timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(anchor), applyToHorizontal: true, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, scrollToPercentVertical: function scrollToPercentVertical(percent, timeInSecond, attenuated) { var moveDelta = this._calculateMovePercentDelta({ anchor: cc.v2(0, percent), applyToHorizontal: false, applyToVertical: true }); timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta); }, stopAutoScroll: function stopAutoScroll() { this._autoScrolling = false; this._autoScrollAccumulatedTime = this._autoScrollTotalTime; }, setContentPosition: function setContentPosition(position) { if (position.fuzzyEquals(this.getContentPosition(), EPSILON)) return; this.content.setPosition(position); this._outOfBoundaryAmountDirty = true; }, getContentPosition: function getContentPosition() { return this.content.getPosition(); }, isScrolling: function isScrolling() { return this._scrolling; }, isAutoScrolling: function isAutoScrolling() { return this._autoScrolling; }, _registerEvent: function _registerEvent() { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.on(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); }, _unregisterEvent: function _unregisterEvent() { this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.off(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); }, _onMouseWheel: function _onMouseWheel(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this.hasNestedViewGroup(event, captureListeners)) return; var deltaMove = cc.v2(0, 0); var wheelPrecision = -.1; cc.sys.os === cc.sys.OS_WINDOWS && cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX && (wheelPrecision = -.1 / 3); false, false; this.vertical ? deltaMove = cc.v2(0, event.getScrollY() * wheelPrecision) : this.horizontal && (deltaMove = cc.v2(event.getScrollY() * wheelPrecision, 0)); this._mouseWheelEventElapsedTime = 0; this._processDeltaMove(deltaMove); if (!this._stopMouseWheel) { this._handlePressLogic(); this.schedule(this._checkMouseWheel, 1 / 60); this._stopMouseWheel = true; } this._stopPropagationIfTargetIsMe(event); }, _checkMouseWheel: function _checkMouseWheel(dt) { var currentOutOfBoundary = this._getHowMuchOutOfBoundary(); var maxElapsedTime = .1; if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { this._processInertiaScroll(); this.unschedule(this._checkMouseWheel); this._dispatchEvent("scroll-ended"); this._stopMouseWheel = false; return; } this._mouseWheelEventElapsedTime += dt; if (this._mouseWheelEventElapsedTime > maxElapsedTime) { this._onScrollBarTouchEnded(); this.unschedule(this._checkMouseWheel); this._dispatchEvent("scroll-ended"); this._stopMouseWheel = false; } }, _calculateMovePercentDelta: function _calculateMovePercentDelta(options) { var anchor = options.anchor; var applyToHorizontal = options.applyToHorizontal; var applyToVertical = options.applyToVertical; this._calculateBoundary(); anchor = anchor.clampf(cc.v2(0, 0), cc.v2(1, 1)); var scrollSize = this._view.getContentSize(); var contentSize = this.content.getContentSize(); var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; leftDeta = -leftDeta; var moveDelta = cc.v2(0, 0); var totalScrollDelta = 0; if (applyToHorizontal) { totalScrollDelta = contentSize.width - scrollSize.width; moveDelta.x = leftDeta - totalScrollDelta * anchor.x; } if (applyToVertical) { totalScrollDelta = contentSize.height - scrollSize.height; moveDelta.y = bottomDeta - totalScrollDelta * anchor.y; } return moveDelta; }, _moveContentToTopLeft: function _moveContentToTopLeft(scrollViewSize) { var contentSize = this.content.getContentSize(); var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; var moveDelta = cc.v2(0, 0); var totalScrollDelta = 0; var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; leftDeta = -leftDeta; if (contentSize.height < scrollViewSize.height) { totalScrollDelta = contentSize.height - scrollViewSize.height; moveDelta.y = bottomDeta - totalScrollDelta; } if (contentSize.width < scrollViewSize.width) { totalScrollDelta = contentSize.width - scrollViewSize.width; moveDelta.x = leftDeta; } this._updateScrollBarState(); this._moveContent(moveDelta); this._adjustContentOutOfBoundary(); }, _calculateBoundary: function _calculateBoundary() { if (this.content) { var layout = this.content.getComponent(cc.Layout); layout && layout.enabledInHierarchy && layout.updateLayout(); var viewSize = this._view.getContentSize(); var anchorX = viewSize.width * this._view.anchorX; var anchorY = viewSize.height * this._view.anchorY; this._leftBoundary = -anchorX; this._bottomBoundary = -anchorY; this._rightBoundary = this._leftBoundary + viewSize.width; this._topBoundary = this._bottomBoundary + viewSize.height; this._moveContentToTopLeft(viewSize); } }, hasNestedViewGroup: function hasNestedViewGroup(event, captureListeners) { if (event.eventPhase !== cc.Event.CAPTURING_PHASE) return; if (captureListeners) for (var i = 0; i < captureListeners.length; ++i) { var item = captureListeners[i]; if (this.node === item) { if (event.target.getComponent(cc.ViewGroup)) return true; return false; } if (item.getComponent(cc.ViewGroup)) return true; } return false; }, _stopPropagationIfTargetIsMe: function _stopPropagationIfTargetIsMe(event) { event.eventPhase === cc.Event.AT_TARGET && event.target === this.node && event.stopPropagation(); }, _onTouchBegan: function _onTouchBegan(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this.hasNestedViewGroup(event, captureListeners)) return; var touch = event.touch; this.content && this._handlePressLogic(touch); this._touchMoved = false; this._stopPropagationIfTargetIsMe(event); }, _onTouchMoved: function _onTouchMoved(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this.hasNestedViewGroup(event, captureListeners)) return; var touch = event.touch; this.content && this._handleMoveLogic(touch); if (!this.cancelInnerEvents) return; var deltaMove = touch.getLocation().sub(touch.getStartLocation()); if (deltaMove.mag() > 7 && !this._touchMoved && event.target !== this.node) { var cancelEvent = new cc.Event.EventTouch(event.getTouches(), event.bubbles); cancelEvent.type = cc.Node.EventType.TOUCH_CANCEL; cancelEvent.touch = event.touch; cancelEvent.simulate = true; event.target.dispatchEvent(cancelEvent); this._touchMoved = true; } this._stopPropagationIfTargetIsMe(event); }, _onTouchEnded: function _onTouchEnded(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this.hasNestedViewGroup(event, captureListeners)) return; this._dispatchEvent("touch-up"); var touch = event.touch; this.content && this._handleReleaseLogic(touch); this._touchMoved ? event.stopPropagation() : this._stopPropagationIfTargetIsMe(event); }, _onTouchCancelled: function _onTouchCancelled(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this.hasNestedViewGroup(event, captureListeners)) return; if (!event.simulate) { var touch = event.touch; this.content && this._handleReleaseLogic(touch); } this._stopPropagationIfTargetIsMe(event); }, _processDeltaMove: function _processDeltaMove(deltaMove) { this._scrollChildren(deltaMove); this._gatherTouchMove(deltaMove); }, _getLocalAxisAlignDelta: function _getLocalAxisAlignDelta(touch) { this.node.convertToNodeSpaceAR(touch.getLocation(), _tempPoint); this.node.convertToNodeSpaceAR(touch.getPreviousLocation(), _tempPrevPoint); return _tempPoint.sub(_tempPrevPoint); }, _handleMoveLogic: function _handleMoveLogic(touch) { var deltaMove = this._getLocalAxisAlignDelta(touch); this._processDeltaMove(deltaMove); }, _scrollChildren: function _scrollChildren(deltaMove) { deltaMove = this._clampDelta(deltaMove); var realMove = deltaMove; var outOfBoundary; if (this.elastic) { outOfBoundary = this._getHowMuchOutOfBoundary(); realMove.x *= 0 === outOfBoundary.x ? 1 : .5; realMove.y *= 0 === outOfBoundary.y ? 1 : .5; } if (!this.elastic) { outOfBoundary = this._getHowMuchOutOfBoundary(realMove); realMove = realMove.add(outOfBoundary); } var vertical_scrollEventType = ""; var horizontal_scrollEventType = ""; if (this.vertical) if (realMove.y > 0) { var icBottomPos = this.content.y - this.content.anchorY * this.content.height; icBottomPos + realMove.y >= this._bottomBoundary && (vertical_scrollEventType = "scroll-to-bottom"); } else if (realMove.y < 0) { var icTopPos = this.content.y - this.content.anchorY * this.content.height + this.content.height; icTopPos + realMove.y <= this._topBoundary && (vertical_scrollEventType = "scroll-to-top"); } if (this.horizontal) if (realMove.x < 0) { var icRightPos = this.content.x - this.content.anchorX * this.content.width + this.content.width; icRightPos + realMove.x <= this._rightBoundary && (horizontal_scrollEventType = "scroll-to-right"); } else if (realMove.x > 0) { var icLeftPos = this.content.x - this.content.anchorX * this.content.width; icLeftPos + realMove.x >= this._leftBoundary && (horizontal_scrollEventType = "scroll-to-left"); } this._moveContent(realMove, false); if (this.horizontal && 0 !== realMove.x || this.vertical && 0 !== realMove.y) { if (!this._scrolling) { this._scrolling = true; this._dispatchEvent("scroll-began"); } this._dispatchEvent("scrolling"); } "" !== vertical_scrollEventType && this._dispatchEvent(vertical_scrollEventType); "" !== horizontal_scrollEventType && this._dispatchEvent(horizontal_scrollEventType); }, _handlePressLogic: function _handlePressLogic() { this._autoScrolling && this._dispatchEvent("scroll-ended"); this._autoScrolling = false; this._isBouncing = false; this._touchMovePreviousTimestamp = getTimeInMilliseconds(); this._touchMoveDisplacements.length = 0; this._touchMoveTimeDeltas.length = 0; this._onScrollBarTouchBegan(); }, _clampDelta: function _clampDelta(delta) { var contentSize = this.content.getContentSize(); var scrollViewSize = this._view.getContentSize(); contentSize.width < scrollViewSize.width && (delta.x = 0); contentSize.height < scrollViewSize.height && (delta.y = 0); return delta; }, _gatherTouchMove: function _gatherTouchMove(delta) { delta = this._clampDelta(delta); while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) { this._touchMoveDisplacements.shift(); this._touchMoveTimeDeltas.shift(); } this._touchMoveDisplacements.push(delta); var timeStamp = getTimeInMilliseconds(); this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1e3); this._touchMovePreviousTimestamp = timeStamp; }, _startBounceBackIfNeeded: function _startBounceBackIfNeeded() { if (!this.elastic) return false; var bounceBackAmount = this._getHowMuchOutOfBoundary(); bounceBackAmount = this._clampDelta(bounceBackAmount); if (bounceBackAmount.fuzzyEquals(cc.v2(0, 0), EPSILON)) return false; var bounceBackTime = Math.max(this.bounceDuration, 0); this._startAutoScroll(bounceBackAmount, bounceBackTime, true); if (!this._isBouncing) { bounceBackAmount.y > 0 && this._dispatchEvent("bounce-top"); bounceBackAmount.y < 0 && this._dispatchEvent("bounce-bottom"); bounceBackAmount.x > 0 && this._dispatchEvent("bounce-right"); bounceBackAmount.x < 0 && this._dispatchEvent("bounce-left"); this._isBouncing = true; } return true; }, _processInertiaScroll: function _processInertiaScroll() { var bounceBackStarted = this._startBounceBackIfNeeded(); if (!bounceBackStarted && this.inertia) { var touchMoveVelocity = this._calculateTouchMoveVelocity(); !touchMoveVelocity.fuzzyEquals(cc.v2(0, 0), EPSILON) && this.brake < 1 && this._startInertiaScroll(touchMoveVelocity); } this._onScrollBarTouchEnded(); }, _handleReleaseLogic: function _handleReleaseLogic(touch) { var delta = this._getLocalAxisAlignDelta(touch); this._gatherTouchMove(delta); this._processInertiaScroll(); if (this._scrolling) { this._scrolling = false; this._autoScrolling || this._dispatchEvent("scroll-ended"); } }, _isOutOfBoundary: function _isOutOfBoundary() { var outOfBoundary = this._getHowMuchOutOfBoundary(); return !outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON); }, _isNecessaryAutoScrollBrake: function _isNecessaryAutoScrollBrake() { if (this._autoScrollBraking) return true; if (this._isOutOfBoundary()) { if (!this._autoScrollCurrentlyOutOfBoundary) { this._autoScrollCurrentlyOutOfBoundary = true; this._autoScrollBraking = true; this._autoScrollBrakingStartPosition = this.getContentPosition(); return true; } } else this._autoScrollCurrentlyOutOfBoundary = false; return false; }, getScrollEndedEventTiming: function getScrollEndedEventTiming() { return EPSILON; }, _processAutoScrolling: function _processAutoScrolling(dt) { var isAutoScrollBrake = this._isNecessaryAutoScrollBrake(); var brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1; this._autoScrollAccumulatedTime += dt * (1 / brakingFactor); var percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime); this._autoScrollAttenuate && (percentage = quintEaseOut(percentage)); var newPosition = this._autoScrollStartPosition.add(this._autoScrollTargetDelta.mul(percentage)); var reachedEnd = Math.abs(percentage - 1) <= EPSILON; var fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming(); if (fireEvent && !this._isScrollEndedWithThresholdEventFired) { this._dispatchEvent("scroll-ended-with-threshold"); this._isScrollEndedWithThresholdEventFired = true; } if (this.elastic) { var brakeOffsetPosition = newPosition.sub(this._autoScrollBrakingStartPosition); isAutoScrollBrake && (brakeOffsetPosition = brakeOffsetPosition.mul(brakingFactor)); newPosition = this._autoScrollBrakingStartPosition.add(brakeOffsetPosition); } else { var moveDelta = newPosition.sub(this.getContentPosition()); var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta); if (!outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { newPosition = newPosition.add(outOfBoundary); reachedEnd = true; } } reachedEnd && (this._autoScrolling = false); var deltaMove = newPosition.sub(this.getContentPosition()); this._moveContent(this._clampDelta(deltaMove), reachedEnd); this._dispatchEvent("scrolling"); if (!this._autoScrolling) { this._isBouncing = false; this._scrolling = false; this._dispatchEvent("scroll-ended"); } }, _startInertiaScroll: function _startInertiaScroll(touchMoveVelocity) { var inertiaTotalMovement = touchMoveVelocity.mul(MOVEMENT_FACTOR); this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); }, _calculateAttenuatedFactor: function _calculateAttenuatedFactor(distance) { if (this.brake <= 0) return 1 - this.brake; return (1 - this.brake) * (1 / (1 + 14e-6 * distance + distance * distance * 8e-9)); }, _startAttenuatingAutoScroll: function _startAttenuatingAutoScroll(deltaMove, initialVelocity) { var time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag()); var targetDelta = deltaMove.normalize(); var contentSize = this.content.getContentSize(); var scrollviewSize = this._view.getContentSize(); var totalMoveWidth = contentSize.width - scrollviewSize.width; var totalMoveHeight = contentSize.height - scrollviewSize.height; var attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth); var attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight); targetDelta = cc.v2(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake)); var originalMoveLength = deltaMove.mag(); var factor = targetDelta.mag() / originalMoveLength; targetDelta = targetDelta.add(deltaMove); if (this.brake > 0 && factor > 7) { factor = Math.sqrt(factor); targetDelta = deltaMove.mul(factor).add(deltaMove); } if (this.brake > 0 && factor > 3) { factor = 3; time *= factor; } 0 === this.brake && factor > 1 && (time *= factor); this._startAutoScroll(targetDelta, time, true); }, _calculateAutoScrollTimeByInitalSpeed: function _calculateAutoScrollTimeByInitalSpeed(initalSpeed) { return Math.sqrt(Math.sqrt(initalSpeed / 5)); }, _startAutoScroll: function _startAutoScroll(deltaMove, timeInSecond, attenuated) { var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); this._autoScrolling = true; this._autoScrollTargetDelta = adjustedDeltaMove; this._autoScrollAttenuate = attenuated; this._autoScrollStartPosition = this.getContentPosition(); this._autoScrollTotalTime = timeInSecond; this._autoScrollAccumulatedTime = 0; this._autoScrollBraking = false; this._isScrollEndedWithThresholdEventFired = false; this._autoScrollBrakingStartPosition = cc.v2(0, 0); var currentOutOfBoundary = this._getHowMuchOutOfBoundary(); currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON) || (this._autoScrollCurrentlyOutOfBoundary = true); }, _calculateTouchMoveVelocity: function _calculateTouchMoveVelocity() { var totalTime = 0; totalTime = this._touchMoveTimeDeltas.reduce((function(a, b) { return a + b; }), totalTime); if (totalTime <= 0 || totalTime >= .5) return cc.v2(0, 0); var totalMovement = cc.v2(0, 0); totalMovement = this._touchMoveDisplacements.reduce((function(a, b) { return a.add(b); }), totalMovement); return cc.v2(totalMovement.x * (1 - this.brake) / totalTime, totalMovement.y * (1 - this.brake) / totalTime); }, _flattenVectorByDirection: function _flattenVectorByDirection(vector) { var result = vector; result.x = this.horizontal ? result.x : 0; result.y = this.vertical ? result.y : 0; return result; }, _moveContent: function _moveContent(deltaMove, canStartBounceBack) { var adjustedMove = this._flattenVectorByDirection(deltaMove); var newPosition = this.getContentPosition().add(adjustedMove); this.setContentPosition(newPosition); var outOfBoundary = this._getHowMuchOutOfBoundary(); this._updateScrollBar(outOfBoundary); this.elastic && canStartBounceBack && this._startBounceBackIfNeeded(); }, _getContentLeftBoundary: function _getContentLeftBoundary() { var contentPos = this.getContentPosition(); return contentPos.x - this.content.getAnchorPoint().x * this.content.getContentSize().width; }, _getContentRightBoundary: function _getContentRightBoundary() { var contentSize = this.content.getContentSize(); return this._getContentLeftBoundary() + contentSize.width; }, _getContentTopBoundary: function _getContentTopBoundary() { var contentSize = this.content.getContentSize(); return this._getContentBottomBoundary() + contentSize.height; }, _getContentBottomBoundary: function _getContentBottomBoundary() { var contentPos = this.getContentPosition(); return contentPos.y - this.content.getAnchorPoint().y * this.content.getContentSize().height; }, _getHowMuchOutOfBoundary: function _getHowMuchOutOfBoundary(addition) { addition = addition || cc.v2(0, 0); if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON) && !this._outOfBoundaryAmountDirty) return this._outOfBoundaryAmount; var outOfBoundaryAmount = cc.v2(0, 0); this._getContentLeftBoundary() + addition.x > this._leftBoundary ? outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x) : this._getContentRightBoundary() + addition.x < this._rightBoundary && (outOfBoundaryAmount.x = this._rightBoundary - (this._getContentRightBoundary() + addition.x)); this._getContentTopBoundary() + addition.y < this._topBoundary ? outOfBoundaryAmount.y = this._topBoundary - (this._getContentTopBoundary() + addition.y) : this._getContentBottomBoundary() + addition.y > this._bottomBoundary && (outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y)); if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON)) { this._outOfBoundaryAmount = outOfBoundaryAmount; this._outOfBoundaryAmountDirty = false; } outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount); return outOfBoundaryAmount; }, _updateScrollBarState: function _updateScrollBarState() { if (!this.content) return; var contentSize = this.content.getContentSize(); var scrollViewSize = this._view.getContentSize(); this.verticalScrollBar && (contentSize.height < scrollViewSize.height ? this.verticalScrollBar.hide() : this.verticalScrollBar.show()); this.horizontalScrollBar && (contentSize.width < scrollViewSize.width ? this.horizontalScrollBar.hide() : this.horizontalScrollBar.show()); }, _updateScrollBar: function _updateScrollBar(outOfBoundary) { this.horizontalScrollBar && this.horizontalScrollBar._onScroll(outOfBoundary); this.verticalScrollBar && this.verticalScrollBar._onScroll(outOfBoundary); }, _onScrollBarTouchBegan: function _onScrollBarTouchBegan() { this.horizontalScrollBar && this.horizontalScrollBar._onTouchBegan(); this.verticalScrollBar && this.verticalScrollBar._onTouchBegan(); }, _onScrollBarTouchEnded: function _onScrollBarTouchEnded() { this.horizontalScrollBar && this.horizontalScrollBar._onTouchEnded(); this.verticalScrollBar && this.verticalScrollBar._onTouchEnded(); }, _dispatchEvent: function _dispatchEvent(event) { if ("scroll-ended" === event) this._scrollEventEmitMask = 0; else if ("scroll-to-top" === event || "scroll-to-bottom" === event || "scroll-to-left" === event || "scroll-to-right" === event) { var flag = 1 << eventMap[event]; if (this._scrollEventEmitMask & flag) return; this._scrollEventEmitMask |= flag; } cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]); this.node.emit(event, this); }, _adjustContentOutOfBoundary: function _adjustContentOutOfBoundary() { this._outOfBoundaryAmountDirty = true; if (this._isOutOfBoundary()) { var outOfBoundary = this._getHowMuchOutOfBoundary(cc.v2(0, 0)); var newPosition = this.getContentPosition().add(outOfBoundary); if (this.content) { this.content.setPosition(newPosition); this._updateScrollBar(0); } } }, start: function start() { this._calculateBoundary(); this.content && cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); }, _hideScrollbar: function _hideScrollbar() { this.horizontalScrollBar && this.horizontalScrollBar.hide(); this.verticalScrollBar && this.verticalScrollBar.hide(); }, onDisable: function onDisable() { true; this._unregisterEvent(); if (this.content) { this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); this.content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); if (this._view) { this._view.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); this._view.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); this._view.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } this._hideScrollbar(); this.stopAutoScroll(); }, onEnable: function onEnable() { true; this._registerEvent(); if (this.content) { this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); this.content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); if (this._view) { this._view.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); this._view.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); this._view.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } this._updateScrollBarState(); }, update: function update(dt) { this._autoScrolling && this._processAutoScrolling(dt); } }); cc.ScrollView = module.exports = ScrollView; }), { "../CCNode": 24, "./CCViewGroup": 109 } ], 104: [ (function(require, module, exports) { "use strict"; var misc = require("../utils/misc"); var Component = require("./CCComponent"); var Direction = cc.Enum({ Horizontal: 0, Vertical: 1 }); var Slider = cc.Class({ name: "cc.Slider", extends: Component, editor: false, ctor: function ctor() { this._offset = cc.v2(); this._touchHandle = false; this._dragging = false; }, properties: { handle: { default: null, type: cc.Button, tooltip: false, notify: function notify() { false; } }, direction: { default: Direction.Horizontal, type: Direction, tooltip: false }, progress: { default: .5, type: cc.Float, range: [ 0, 1, .1 ], slide: true, tooltip: false, notify: function notify() { this._updateHandlePosition(); } }, slideEvents: { default: [], type: cc.Component.EventHandler, tooltip: false } }, statics: { Direction: Direction }, __preload: function __preload() { this._updateHandlePosition(); }, onEnable: function onEnable() { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); if (this.handle && this.handle.isValid) { this.handle.node.on(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this); this.handle.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.handle.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); } }, onDisable: function onDisable() { this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); if (this.handle && this.handle.isValid) { this.handle.node.off(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this); this.handle.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.handle.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); } }, _onHandleDragStart: function _onHandleDragStart(event) { this._dragging = true; this._touchHandle = true; this._offset = this.handle.node.convertToNodeSpaceAR(event.touch.getLocation()); event.stopPropagation(); }, _onTouchBegan: function _onTouchBegan(event) { if (!this.handle) return; this._dragging = true; this._touchHandle || this._handleSliderLogic(event.touch); event.stopPropagation(); }, _onTouchMoved: function _onTouchMoved(event) { if (!this._dragging) return; this._handleSliderLogic(event.touch); event.stopPropagation(); }, _onTouchEnded: function _onTouchEnded(event) { this._dragging = false; this._touchHandle = false; this._offset = cc.v2(); event.stopPropagation(); }, _onTouchCancelled: function _onTouchCancelled(event) { this._dragging = false; event.stopPropagation(); }, _handleSliderLogic: function _handleSliderLogic(touch) { this._updateProgress(touch); this._emitSlideEvent(); }, _emitSlideEvent: function _emitSlideEvent() { cc.Component.EventHandler.emitEvents(this.slideEvents, this); this.node.emit("slide", this); }, _updateProgress: function _updateProgress(touch) { if (!this.handle) return; var node = this.node; var localTouchPos = node.convertToNodeSpaceAR(touch.getLocation()); this.direction === Direction.Horizontal ? this.progress = misc.clamp01((localTouchPos.x - this._offset.x + node.anchorX * node.width) / node.width) : this.progress = misc.clamp01((localTouchPos.y - this._offset.y + node.anchorY * node.height) / node.height); }, _updateHandlePosition: function _updateHandlePosition() { if (!this.handle) return; var handlelocalPos; handlelocalPos = this.direction === Direction.Horizontal ? cc.v2(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0) : cc.v2(0, -this.node.height * this.node.anchorY + this.progress * this.node.height); var worldSpacePos = this.node.convertToWorldSpaceAR(handlelocalPos); this.handle.node.position = this.handle.node.parent.convertToNodeSpaceAR(worldSpacePos); } }); cc.Slider = module.exports = Slider; }), { "../utils/misc": 217, "./CCComponent": 92 } ], 105: [ (function(require, module, exports) { "use strict"; var misc = require("../utils/misc"); var NodeEvent = require("../CCNode").EventType; var RenderComponent = require("./CCRenderComponent"); var BlendFunc = require("../utils/blend-func"); var SpriteType = cc.Enum({ SIMPLE: 0, SLICED: 1, TILED: 2, FILLED: 3, MESH: 4 }); var FillType = cc.Enum({ HORIZONTAL: 0, VERTICAL: 1, RADIAL: 2 }); var SizeMode = cc.Enum({ CUSTOM: 0, TRIMMED: 1, RAW: 2 }); var State = cc.Enum({ NORMAL: 0, GRAY: 1 }); var Sprite = cc.Class({ name: "cc.Sprite", extends: RenderComponent, mixins: [ BlendFunc ], editor: false, properties: { _spriteFrame: { default: null, type: cc.SpriteFrame }, _type: SpriteType.SIMPLE, _sizeMode: SizeMode.TRIMMED, _fillType: 0, _fillCenter: cc.v2(0, 0), _fillStart: 0, _fillRange: 0, _isTrimmedMode: true, _atlas: { default: null, type: cc.SpriteAtlas, tooltip: false, editorOnly: true, visible: true, animatable: false }, spriteFrame: { get: function get() { return this._spriteFrame; }, set: function set(value, force) { var lastSprite = this._spriteFrame; false; if (lastSprite === value) return; this._spriteFrame = value; this._applySpriteFrame(lastSprite); false; }, type: cc.SpriteFrame }, type: { get: function get() { return this._type; }, set: function set(value) { if (this._type !== value) { this._type = value; this.setVertsDirty(); this._resetAssembler(); } }, type: SpriteType, animatable: false, tooltip: false }, fillType: { get: function get() { return this._fillType; }, set: function set(value) { if (value !== this._fillType) { this._fillType = value; this.setVertsDirty(); this._resetAssembler(); } }, type: FillType, tooltip: false }, fillCenter: { get: function get() { return this._fillCenter; }, set: function set(value) { this._fillCenter.x = value.x; this._fillCenter.y = value.y; this._type === SpriteType.FILLED && this.setVertsDirty(); }, tooltip: false }, fillStart: { get: function get() { return this._fillStart; }, set: function set(value) { this._fillStart = misc.clampf(value, -1, 1); this._type === SpriteType.FILLED && this.setVertsDirty(); }, tooltip: false }, fillRange: { get: function get() { return this._fillRange; }, set: function set(value) { this._fillRange = misc.clampf(value, -1, 1); this._type === SpriteType.FILLED && this.setVertsDirty(); }, tooltip: false }, trim: { get: function get() { return this._isTrimmedMode; }, set: function set(value) { if (this._isTrimmedMode !== value) { this._isTrimmedMode = value; this._type !== SpriteType.SIMPLE && this._type !== SpriteType.MESH || this.setVertsDirty(); false; } }, animatable: false, tooltip: false }, sizeMode: { get: function get() { return this._sizeMode; }, set: function set(value) { this._sizeMode = value; value !== SizeMode.CUSTOM && this._applySpriteSize(); }, animatable: false, type: SizeMode, tooltip: false }, autoSwitchMaterial: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.autoSwitchMaterial === oldValue) return; this.setVertsDirty(); } }, allowDynamicAtlas: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.allowDynamicAtlas === oldValue) return; this.setVertsDirty(); } } }, statics: { FillType: FillType, Type: SpriteType, SizeMode: SizeMode, State: State }, setVisible: function setVisible(visible) { this.enabled = visible; }, setState: function setState() {}, getState: function getState() {}, __preload: function __preload() { this._super(); false; this._applySpriteFrame(); }, onEnable: function onEnable() { this._super(); this._spriteFrame && this._spriteFrame.isValid && this._spriteFrame.ensureLoadTexture(); this.node.on(cc.Node.EventType.SIZE_CHANGED, this.setVertsDirty, this); this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this.setVertsDirty, this); }, onDisable: function onDisable() { this._super(); this.node.off(cc.Node.EventType.SIZE_CHANGED, this.setVertsDirty, this); this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this.setVertsDirty, this); }, onRestore: false, _updateMaterial: function _updateMaterial() { var texture = null; this._spriteFrame && (texture = this._spriteFrame.getTexture()); var material = this.getMaterial(0); if (material) { var oldDefine = material.getDefine("USE_TEXTURE"); void 0 === oldDefine || oldDefine || material.define("USE_TEXTURE", true); var isMultiMaterial = material.material.isMultiSupport(); if (isMultiMaterial) this._texIdDirty = true; else { var textureImpl = texture && texture.getImpl(); material.getProperty("texture") !== textureImpl && material.setProperty("texture", texture); } this._assembler && (isMultiMaterial && !this._assembler.isMulti || !isMultiMaterial && this._assembler.isMulti) && this._resetAssembler(); } BlendFunc.prototype._updateMaterial.call(this); }, _applyAtlas: false, _validateRender: function _validateRender() { var spriteFrame = this._spriteFrame; if (this._materials[0] && spriteFrame && spriteFrame.textureLoaded()) return; this.disableRender(); }, _applySpriteSize: function _applySpriteSize() { if (!this.isValid || !this._spriteFrame || !this._spriteFrame.isValid) return; if (SizeMode.RAW === this._sizeMode) { var size = this._spriteFrame._originalSize; this.node.setContentSize(size); } else if (SizeMode.TRIMMED === this._sizeMode) { var rect = this._spriteFrame._rect; this.node.setContentSize(rect.width, rect.height); } this.setVertsDirty(); }, _applySpriteFrame: function _applySpriteFrame(oldFrame) { if (!this.isValid) return; var oldTexture = oldFrame && oldFrame.isValid && oldFrame.getTexture(); oldTexture && !oldTexture.loaded && oldFrame.off("load", this._applySpriteSize, this); var spriteFrame = this._spriteFrame; var frameValid = spriteFrame && spriteFrame.isValid; var newTexture = frameValid && spriteFrame.getTexture(); oldTexture !== newTexture && this._updateMaterial(); if (newTexture && newTexture.loaded) this._applySpriteSize(); else { this.disableRender(); frameValid && spriteFrame.once("load", this._applySpriteSize, this); } false; } }); false; cc.Sprite = module.exports = Sprite; }), { "../CCNode": 24, "../utils/blend-func": 211, "../utils/misc": 217, "./CCRenderComponent": 100 } ], 106: [ (function(require, module, exports) { "use strict"; var GraySpriteState = require("../utils/gray-sprite-state"); var Toggle = cc.Class({ name: "cc.Toggle", extends: require("./CCButton"), mixins: [ GraySpriteState ], editor: false, properties: { _N$isChecked: true, isChecked: { get: function get() { return this._N$isChecked; }, set: function set(value) { if (value === this._N$isChecked) return; var group = this.toggleGroup || this._toggleContainer; if (group && group.enabled && this._N$isChecked && !group.allowSwitchOff) return; this._N$isChecked = value; this._updateCheckMark(); group && group.enabled && group.updateToggles(this); cc.Toggle._triggerEventInScript_isChecked && this._emitToggleEvents(); }, tooltip: false }, toggleGroup: { default: null, tooltip: false, type: require("./CCToggleGroup") }, checkMark: { default: null, type: cc.Sprite, tooltip: false }, checkEvents: { default: [], type: cc.Component.EventHandler }, _resizeToTarget: { animatable: false, set: function set(value) { value && this._resizeNodeToTargetNode(); } } }, statics: { _triggerEventInScript_check: false, _triggerEventInScript_isChecked: false }, onEnable: function onEnable() { this._super(); true; this._registerToggleEvent(); this.toggleGroup && this.toggleGroup.enabledInHierarchy && this.toggleGroup.addToggle(this); }, onDisable: function onDisable() { this._super(); true; this._unregisterToggleEvent(); this.toggleGroup && this.toggleGroup.enabledInHierarchy && this.toggleGroup.removeToggle(this); }, _hideCheckMark: function _hideCheckMark() { this._N$isChecked = false; this._updateCheckMark(); }, toggle: function toggle(event) { this.isChecked = !this.isChecked; cc.Toggle._triggerEventInScript_isChecked || !cc.Toggle._triggerEventInScript_check && !event || this._emitToggleEvents(); }, check: function check() { this.isChecked = true; !cc.Toggle._triggerEventInScript_isChecked && cc.Toggle._triggerEventInScript_check && this._emitToggleEvents(); }, uncheck: function uncheck() { this.isChecked = false; !cc.Toggle._triggerEventInScript_isChecked && cc.Toggle._triggerEventInScript_check && this._emitToggleEvents(); }, _updateCheckMark: function _updateCheckMark() { this.checkMark && (this.checkMark.node.active = !!this.isChecked); }, _updateDisabledState: function _updateDisabledState() { this._super(); if (this.enableAutoGrayEffect && this.checkMark) { var useGrayMaterial = !this.interactable; this._switchGrayMaterial(useGrayMaterial, this.checkMark); } }, _registerToggleEvent: function _registerToggleEvent() { this.node.on("click", this.toggle, this); }, _unregisterToggleEvent: function _unregisterToggleEvent() { this.node.off("click", this.toggle, this); }, _emitToggleEvents: function _emitToggleEvents() { this.node.emit("toggle", this); this.checkEvents && cc.Component.EventHandler.emitEvents(this.checkEvents, this); } }); cc.Toggle = module.exports = Toggle; var js = require("../platform/js"); js.get(Toggle.prototype, "_toggleContainer", (function() { var parent = this.node.parent; if (cc.Node.isNode(parent)) return parent.getComponent(cc.ToggleContainer); return null; })); }), { "../platform/js": 150, "../utils/gray-sprite-state": 214, "./CCButton": 90, "./CCToggleGroup": 108 } ], 107: [ (function(require, module, exports) { "use strict"; var ToggleContainer = cc.Class({ name: "cc.ToggleContainer", extends: cc.Component, editor: false, properties: { allowSwitchOff: { tooltip: false, default: false }, checkEvents: { default: [], type: cc.Component.EventHandler } }, updateToggles: function updateToggles(toggle) { if (!this.enabledInHierarchy) return; if (toggle.isChecked) { this.toggleItems.forEach((function(item) { item !== toggle && item.isChecked && item.enabled && item._hideCheckMark(); })); this.checkEvents && cc.Component.EventHandler.emitEvents(this.checkEvents, toggle); } }, _allowOnlyOneToggleChecked: function _allowOnlyOneToggleChecked() { var isChecked = false; this.toggleItems.forEach((function(item) { isChecked ? item._hideCheckMark() : item.isChecked && (isChecked = true); })); return isChecked; }, _makeAtLeastOneToggleChecked: function _makeAtLeastOneToggleChecked() { var isChecked = this._allowOnlyOneToggleChecked(); if (!isChecked && !this.allowSwitchOff) { var toggleItems = this.toggleItems; toggleItems.length > 0 && toggleItems[0].check(); } }, onEnable: function onEnable() { this._makeAtLeastOneToggleChecked(); this.node.on("child-added", this._allowOnlyOneToggleChecked, this); this.node.on("child-removed", this._makeAtLeastOneToggleChecked, this); }, onDisable: function onDisable() { this.node.off("child-added", this._allowOnlyOneToggleChecked, this); this.node.off("child-removed", this._makeAtLeastOneToggleChecked, this); } }); var js = require("../platform/js"); js.get(ToggleContainer.prototype, "toggleItems", (function() { return this.node._children.map((function(item) { return item.getComponent(cc.Toggle); })).filter(Boolean); })); cc.ToggleContainer = module.exports = ToggleContainer; }), { "../platform/js": 150 } ], 108: [ (function(require, module, exports) { "use strict"; var ToggleGroup = cc.Class({ name: "cc.ToggleGroup", extends: cc.Component, ctor: function ctor() { this._toggleItems = []; }, editor: false, properties: { allowSwitchOff: { tooltip: false, default: false }, toggleItems: { get: function get() { return this._toggleItems; } } }, updateToggles: function updateToggles(toggle) { if (!this.enabledInHierarchy) return; this._toggleItems.forEach((function(item) { toggle.isChecked && item !== toggle && item.isChecked && item.enabled && item._hideCheckMark(); })); }, addToggle: function addToggle(toggle) { var index = this._toggleItems.indexOf(toggle); -1 === index && this._toggleItems.push(toggle); this._allowOnlyOneToggleChecked(); }, removeToggle: function removeToggle(toggle) { var index = this._toggleItems.indexOf(toggle); index > -1 && this._toggleItems.splice(index, 1); this._makeAtLeastOneToggleChecked(); }, _allowOnlyOneToggleChecked: function _allowOnlyOneToggleChecked() { var isChecked = false; this._toggleItems.forEach((function(item) { isChecked && item.enabled && item._hideCheckMark(); item.isChecked && item.enabled && (isChecked = true); })); return isChecked; }, _makeAtLeastOneToggleChecked: function _makeAtLeastOneToggleChecked() { var isChecked = this._allowOnlyOneToggleChecked(); isChecked || this.allowSwitchOff || this._toggleItems.length > 0 && (this._toggleItems[0].isChecked = true); }, start: function start() { this._makeAtLeastOneToggleChecked(); } }); var js = require("../platform/js"); var showed = false; js.get(cc, "ToggleGroup", (function() { if (!showed) { cc.errorID(1405, "cc.ToggleGroup", "cc.ToggleContainer"); showed = true; } return ToggleGroup; })); module.exports = ToggleGroup; }), { "../platform/js": 150 } ], 109: [ (function(require, module, exports) { "use strict"; var ViewGroup = cc.Class({ name: "cc.ViewGroup", extends: require("./CCComponent") }); cc.ViewGroup = module.exports = ViewGroup; }), { "./CCComponent": 92 } ], 110: [ (function(require, module, exports) { "use strict"; var WidgetManager = require("../base-ui/CCWidgetManager"); var AlignMode = WidgetManager.AlignMode; var AlignFlags = WidgetManager._AlignFlags; var TOP = AlignFlags.TOP; var MID = AlignFlags.MID; var BOT = AlignFlags.BOT; var LEFT = AlignFlags.LEFT; var CENTER = AlignFlags.CENTER; var RIGHT = AlignFlags.RIGHT; var TOP_BOT = TOP | BOT; var LEFT_RIGHT = LEFT | RIGHT; var Widget = cc.Class({ name: "cc.Widget", extends: require("./CCComponent"), editor: false, properties: { target: { get: function get() { return this._target; }, set: function set(value) { this._target = value; false; }, type: cc.Node, tooltip: false }, isAlignTop: { get: function get() { return (this._alignFlags & TOP) > 0; }, set: function set(value) { this._setAlign(TOP, value); }, animatable: false, tooltip: false }, isAlignVerticalCenter: { get: function get() { return (this._alignFlags & MID) > 0; }, set: function set(value) { if (value) { this.isAlignTop = false; this.isAlignBottom = false; this._alignFlags |= MID; } else this._alignFlags &= ~MID; }, animatable: false, tooltip: false }, isAlignBottom: { get: function get() { return (this._alignFlags & BOT) > 0; }, set: function set(value) { this._setAlign(BOT, value); }, animatable: false, tooltip: false }, isAlignLeft: { get: function get() { return (this._alignFlags & LEFT) > 0; }, set: function set(value) { this._setAlign(LEFT, value); }, animatable: false, tooltip: false }, isAlignHorizontalCenter: { get: function get() { return (this._alignFlags & CENTER) > 0; }, set: function set(value) { if (value) { this.isAlignLeft = false; this.isAlignRight = false; this._alignFlags |= CENTER; } else this._alignFlags &= ~CENTER; }, animatable: false, tooltip: false }, isAlignRight: { get: function get() { return (this._alignFlags & RIGHT) > 0; }, set: function set(value) { this._setAlign(RIGHT, value); }, animatable: false, tooltip: false }, isStretchWidth: { get: function get() { return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT; }, visible: false }, isStretchHeight: { get: function get() { return (this._alignFlags & TOP_BOT) === TOP_BOT; }, visible: false }, top: { get: function get() { return this._top; }, set: function set(value) { this._top = value; }, tooltip: false }, bottom: { get: function get() { return this._bottom; }, set: function set(value) { this._bottom = value; }, tooltip: false }, left: { get: function get() { return this._left; }, set: function set(value) { this._left = value; }, tooltip: false }, right: { get: function get() { return this._right; }, set: function set(value) { this._right = value; }, tooltip: false }, horizontalCenter: { get: function get() { return this._horizontalCenter; }, set: function set(value) { this._horizontalCenter = value; }, tooltip: false }, verticalCenter: { get: function get() { return this._verticalCenter; }, set: function set(value) { this._verticalCenter = value; }, tooltip: false }, isAbsoluteHorizontalCenter: { get: function get() { return this._isAbsHorizontalCenter; }, set: function set(value) { this._isAbsHorizontalCenter = value; }, animatable: false }, isAbsoluteVerticalCenter: { get: function get() { return this._isAbsVerticalCenter; }, set: function set(value) { this._isAbsVerticalCenter = value; }, animatable: false }, isAbsoluteTop: { get: function get() { return this._isAbsTop; }, set: function set(value) { this._isAbsTop = value; }, animatable: false }, isAbsoluteBottom: { get: function get() { return this._isAbsBottom; }, set: function set(value) { this._isAbsBottom = value; }, animatable: false }, isAbsoluteLeft: { get: function get() { return this._isAbsLeft; }, set: function set(value) { this._isAbsLeft = value; }, animatable: false }, isAbsoluteRight: { get: function get() { return this._isAbsRight; }, set: function set(value) { this._isAbsRight = value; }, animatable: false }, alignMode: { default: AlignMode.ON_WINDOW_RESIZE, type: AlignMode, tooltip: false }, _wasAlignOnce: { default: void 0, formerlySerializedAs: "isAlignOnce" }, _target: null, _alignFlags: 0, _left: 0, _right: 0, _top: 0, _bottom: 0, _verticalCenter: 0, _horizontalCenter: 0, _isAbsLeft: true, _isAbsRight: true, _isAbsTop: true, _isAbsBottom: true, _isAbsHorizontalCenter: true, _isAbsVerticalCenter: true, _originalWidth: 0, _originalHeight: 0 }, statics: { AlignMode: AlignMode }, onLoad: function onLoad() { if (void 0 !== this._wasAlignOnce) { this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; this._wasAlignOnce = void 0; } }, onEnable: function onEnable() { WidgetManager.add(this); }, onDisable: function onDisable() { WidgetManager.remove(this); }, _validateTargetInDEV: false, _setAlign: function _setAlign(flag, isAlign) { var current = (this._alignFlags & flag) > 0; if (isAlign === current) return; var isHorizontal = (flag & LEFT_RIGHT) > 0; if (isAlign) { this._alignFlags |= flag; if (isHorizontal) { this.isAlignHorizontalCenter = false; if (this.isStretchWidth) { this._originalWidth = this.node.width; false; } } else { this.isAlignVerticalCenter = false; if (this.isStretchHeight) { this._originalHeight = this.node.height; false; } } false; } else { isHorizontal ? this.isStretchWidth && (this.node.width = this._originalWidth) : this.isStretchHeight && (this.node.height = this._originalHeight); this._alignFlags &= ~flag; } }, updateAlignment: function updateAlignment() { WidgetManager.updateAlignment(this.node); } }); Object.defineProperty(Widget.prototype, "isAlignOnce", { get: function get() { true; cc.warn("`widget.isAlignOnce` is deprecated, use `widget.alignMode === cc.Widget.AlignMode.ONCE` instead please."); return this.alignMode === AlignMode.ONCE; }, set: function set(value) { true; cc.warn("`widget.isAlignOnce` is deprecated, use `widget.alignMode = cc.Widget.AlignMode.*` instead please."); this.alignMode = value ? AlignMode.ONCE : AlignMode.ALWAYS; } }); cc.Widget = module.exports = Widget; }), { "../base-ui/CCWidgetManager": 85, "./CCComponent": 92 } ], 111: [ (function(require, module, exports) { "use strict"; require("./CCComponent"); require("./CCComponentEventHandler"); require("./missing-script"); var SubContextView = require("./SubContextView"); if (!SubContextView) { SubContextView = cc.Class({ name: "cc.SubContextView", extends: cc.Component }); cc.SubContextView = cc.WXSubContextView = cc.SwanSubContextView = SubContextView; } var components = [ require("./CCSprite"), require("./CCWidget"), require("./CCCanvas"), require("./CCAudioSource"), require("./CCAnimation"), require("./CCButton"), require("./CCLabel"), require("./CCProgressBar"), require("./CCMask"), require("./CCScrollBar"), require("./CCScrollView"), require("./CCPageViewIndicator"), require("./CCPageView"), require("./CCSlider"), require("./CCLayout"), require("./editbox/CCEditBox"), require("./CCLabelOutline"), require("./CCLabelShadow"), require("./CCRichText"), require("./CCToggleContainer"), require("./CCToggleGroup"), require("./CCToggle"), require("./CCBlockInputEvents"), require("./CCMotionStreak"), require("./CCSafeArea"), SubContextView ]; module.exports = components; }), { "./CCAnimation": 88, "./CCAudioSource": void 0, "./CCBlockInputEvents": 89, "./CCButton": 90, "./CCCanvas": 91, "./CCComponent": 92, "./CCComponentEventHandler": 93, "./CCLabel": 94, "./CCLabelOutline": 95, "./CCLabelShadow": 96, "./CCLayout": 97, "./CCMask": 98, "./CCMotionStreak": 99, "./CCPageView": void 0, "./CCPageViewIndicator": void 0, "./CCProgressBar": void 0, "./CCRichText": 101, "./CCSafeArea": void 0, "./CCScrollBar": 102, "./CCScrollView": 103, "./CCSlider": 104, "./CCSprite": 105, "./CCToggle": 106, "./CCToggleContainer": 107, "./CCToggleGroup": 108, "./CCWidget": 110, "./SubContextView": void 0, "./editbox/CCEditBox": void 0, "./missing-script": 112 } ], 112: [ (function(require, module, exports) { "use strict"; var js = cc.js; var MissingScript = cc.Class({ name: "cc.MissingScript", extends: cc.Component, editor: { inspector: "packages://inspector/inspectors/comps/missing-script.js" }, properties: { compiled: { default: false, serializable: false }, _$erialized: { default: null, visible: false, editorOnly: true } }, ctor: false, statics: { safeFindClass: function safeFindClass(id) { var cls = js._getClassById(id); if (cls) return cls; cc.deserialize.reportMissingClass(id); return MissingScript; } }, onLoad: function onLoad() { cc.warnID(4600, this.node.name); } }); cc._MissingScript = module.exports = MissingScript; }), {} ], 113: [ (function(require, module, exports) { "use strict"; var js = cc.js; require("../event/event"); var EventMouse = function EventMouse(eventType, bubbles) { cc.Event.call(this, cc.Event.MOUSE, bubbles); this._eventType = eventType; this._button = 0; this._x = 0; this._y = 0; this._prevX = 0; this._prevY = 0; this._scrollX = 0; this._scrollY = 0; }; js.extend(EventMouse, cc.Event); var proto = EventMouse.prototype; proto.setScrollData = function(scrollX, scrollY) { this._scrollX = scrollX; this._scrollY = scrollY; }; proto.getScrollX = function() { return this._scrollX; }; proto.getScrollY = function() { return this._scrollY; }; proto.setLocation = function(x, y) { this._x = x; this._y = y; }; proto.getLocation = function() { return cc.v2(this._x, this._y); }; proto.getLocationInView = function() { return cc.v2(this._x, cc.view._designResolutionSize.height - this._y); }; proto._setPrevCursor = function(x, y) { this._prevX = x; this._prevY = y; }; proto.getPreviousLocation = function() { return cc.v2(this._prevX, this._prevY); }; proto.getDelta = function() { return cc.v2(this._x - this._prevX, this._y - this._prevY); }; proto.getDeltaX = function() { return this._x - this._prevX; }; proto.getDeltaY = function() { return this._y - this._prevY; }; proto.setButton = function(button) { this._button = button; }; proto.getButton = function() { return this._button; }; proto.getLocationX = function() { return this._x; }; proto.getLocationY = function() { return this._y; }; EventMouse.NONE = 0; EventMouse.DOWN = 1; EventMouse.UP = 2; EventMouse.MOVE = 3; EventMouse.SCROLL = 4; EventMouse.BUTTON_LEFT = 0; EventMouse.BUTTON_RIGHT = 2; EventMouse.BUTTON_MIDDLE = 1; EventMouse.BUTTON_4 = 3; EventMouse.BUTTON_5 = 4; EventMouse.BUTTON_6 = 5; EventMouse.BUTTON_7 = 6; EventMouse.BUTTON_8 = 7; var EventTouch = function EventTouch(touchArr, bubbles) { cc.Event.call(this, cc.Event.TOUCH, bubbles); this._eventCode = 0; this._touches = touchArr || []; this.touch = null; this.currentTouch = null; }; js.extend(EventTouch, cc.Event); proto = EventTouch.prototype; proto.getEventCode = function() { return this._eventCode; }; proto.getTouches = function() { return this._touches; }; proto._setEventCode = function(eventCode) { this._eventCode = eventCode; }; proto._setTouches = function(touches) { this._touches = touches; }; proto.setLocation = function(x, y) { this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y); }; proto.getLocation = function() { return this.touch ? this.touch.getLocation() : cc.v2(); }; proto.getLocationInView = function() { return this.touch ? this.touch.getLocationInView() : cc.v2(); }; proto.getPreviousLocation = function() { return this.touch ? this.touch.getPreviousLocation() : cc.v2(); }; proto.getStartLocation = function() { return this.touch ? this.touch.getStartLocation() : cc.v2(); }; proto.getID = function() { return this.touch ? this.touch.getID() : null; }; proto.getDelta = function() { return this.touch ? this.touch.getDelta() : cc.v2(); }; proto.getDeltaX = function() { return this.touch ? this.touch.getDelta().x : 0; }; proto.getDeltaY = function() { return this.touch ? this.touch.getDelta().y : 0; }; proto.getLocationX = function() { return this.touch ? this.touch.getLocationX() : 0; }; proto.getLocationY = function() { return this.touch ? this.touch.getLocationY() : 0; }; EventTouch.MAX_TOUCHES = 5; EventTouch.BEGAN = 0; EventTouch.MOVED = 1; EventTouch.ENDED = 2; EventTouch.CANCELED = 3; var EventAcceleration = function EventAcceleration(acc, bubbles) { cc.Event.call(this, cc.Event.ACCELERATION, bubbles); this.acc = acc; }; js.extend(EventAcceleration, cc.Event); var EventKeyboard = function EventKeyboard(keyCode, isPressed, bubbles) { cc.Event.call(this, cc.Event.KEYBOARD, bubbles); this.keyCode = keyCode; this.isPressed = isPressed; }; js.extend(EventKeyboard, cc.Event); cc.Event.EventMouse = EventMouse; cc.Event.EventTouch = EventTouch; cc.Event.EventAcceleration = EventAcceleration; cc.Event.EventKeyboard = EventKeyboard; module.exports = cc.Event; }), { "../event/event": 120 } ], 114: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); cc.EventListener = function(type, listenerID, callback) { this._onEvent = callback; this._type = type || 0; this._listenerID = listenerID || ""; this._registered = false; this._fixedPriority = 0; this._node = null; this._target = null; this._paused = true; this._isEnabled = true; }; cc.EventListener.prototype = { constructor: cc.EventListener, _setPaused: function _setPaused(paused) { this._paused = paused; }, _isPaused: function _isPaused() { return this._paused; }, _setRegistered: function _setRegistered(registered) { this._registered = registered; }, _isRegistered: function _isRegistered() { return this._registered; }, _getType: function _getType() { return this._type; }, _getListenerID: function _getListenerID() { return this._listenerID; }, _setFixedPriority: function _setFixedPriority(fixedPriority) { this._fixedPriority = fixedPriority; }, _getFixedPriority: function _getFixedPriority() { return this._fixedPriority; }, _setSceneGraphPriority: function _setSceneGraphPriority(node) { this._target = node; this._node = node; }, _getSceneGraphPriority: function _getSceneGraphPriority() { return this._node; }, checkAvailable: function checkAvailable() { return null !== this._onEvent; }, clone: function clone() { return null; }, setEnabled: function setEnabled(enabled) { this._isEnabled = enabled; }, isEnabled: function isEnabled() { return this._isEnabled; }, retain: function retain() {}, release: function release() {} }; cc.EventListener.UNKNOWN = 0; cc.EventListener.TOUCH_ONE_BY_ONE = 1; cc.EventListener.TOUCH_ALL_AT_ONCE = 2; cc.EventListener.KEYBOARD = 3; cc.EventListener.MOUSE = 4; cc.EventListener.ACCELERATION = 6; cc.EventListener.CUSTOM = 8; var ListenerID = cc.EventListener.ListenerID = { MOUSE: "__cc_mouse", TOUCH_ONE_BY_ONE: "__cc_touch_one_by_one", TOUCH_ALL_AT_ONCE: "__cc_touch_all_at_once", KEYBOARD: "__cc_keyboard", ACCELERATION: "__cc_acceleration" }; var Custom = function Custom(listenerId, callback) { this._onCustomEvent = callback; cc.EventListener.call(this, cc.EventListener.CUSTOM, listenerId, this._callback); }; js.extend(Custom, cc.EventListener); js.mixin(Custom.prototype, { _onCustomEvent: null, _callback: function _callback(event) { null !== this._onCustomEvent && this._onCustomEvent(event); }, checkAvailable: function checkAvailable() { return cc.EventListener.prototype.checkAvailable.call(this) && null !== this._onCustomEvent; }, clone: function clone() { return new Custom(this._listenerID, this._onCustomEvent); } }); var Mouse = function Mouse() { cc.EventListener.call(this, cc.EventListener.MOUSE, ListenerID.MOUSE, this._callback); }; js.extend(Mouse, cc.EventListener); js.mixin(Mouse.prototype, { onMouseDown: null, onMouseUp: null, onMouseMove: null, onMouseScroll: null, _callback: function _callback(event) { var eventType = cc.Event.EventMouse; switch (event._eventType) { case eventType.DOWN: this.onMouseDown && this.onMouseDown(event); break; case eventType.UP: this.onMouseUp && this.onMouseUp(event); break; case eventType.MOVE: this.onMouseMove && this.onMouseMove(event); break; case eventType.SCROLL: this.onMouseScroll && this.onMouseScroll(event); } }, clone: function clone() { var eventListener = new Mouse(); eventListener.onMouseDown = this.onMouseDown; eventListener.onMouseUp = this.onMouseUp; eventListener.onMouseMove = this.onMouseMove; eventListener.onMouseScroll = this.onMouseScroll; return eventListener; }, checkAvailable: function checkAvailable() { return true; } }); var TouchOneByOne = function TouchOneByOne() { cc.EventListener.call(this, cc.EventListener.TOUCH_ONE_BY_ONE, ListenerID.TOUCH_ONE_BY_ONE, null); this._claimedTouches = []; }; js.extend(TouchOneByOne, cc.EventListener); js.mixin(TouchOneByOne.prototype, { constructor: TouchOneByOne, _claimedTouches: null, swallowTouches: false, onTouchBegan: null, onTouchMoved: null, onTouchEnded: null, onTouchCancelled: null, setSwallowTouches: function setSwallowTouches(needSwallow) { this.swallowTouches = needSwallow; }, isSwallowTouches: function isSwallowTouches() { return this.swallowTouches; }, clone: function clone() { var eventListener = new TouchOneByOne(); eventListener.onTouchBegan = this.onTouchBegan; eventListener.onTouchMoved = this.onTouchMoved; eventListener.onTouchEnded = this.onTouchEnded; eventListener.onTouchCancelled = this.onTouchCancelled; eventListener.swallowTouches = this.swallowTouches; return eventListener; }, checkAvailable: function checkAvailable() { if (!this.onTouchBegan) { cc.logID(1801); return false; } return true; } }); var TouchAllAtOnce = function TouchAllAtOnce() { cc.EventListener.call(this, cc.EventListener.TOUCH_ALL_AT_ONCE, ListenerID.TOUCH_ALL_AT_ONCE, null); }; js.extend(TouchAllAtOnce, cc.EventListener); js.mixin(TouchAllAtOnce.prototype, { constructor: TouchAllAtOnce, onTouchesBegan: null, onTouchesMoved: null, onTouchesEnded: null, onTouchesCancelled: null, clone: function clone() { var eventListener = new TouchAllAtOnce(); eventListener.onTouchesBegan = this.onTouchesBegan; eventListener.onTouchesMoved = this.onTouchesMoved; eventListener.onTouchesEnded = this.onTouchesEnded; eventListener.onTouchesCancelled = this.onTouchesCancelled; return eventListener; }, checkAvailable: function checkAvailable() { if (null === this.onTouchesBegan && null === this.onTouchesMoved && null === this.onTouchesEnded && null === this.onTouchesCancelled) { cc.logID(1802); return false; } return true; } }); var Acceleration = function Acceleration(callback) { this._onAccelerationEvent = callback; cc.EventListener.call(this, cc.EventListener.ACCELERATION, ListenerID.ACCELERATION, this._callback); }; js.extend(Acceleration, cc.EventListener); js.mixin(Acceleration.prototype, { constructor: Acceleration, _onAccelerationEvent: null, _callback: function _callback(event) { this._onAccelerationEvent(event.acc, event); }, checkAvailable: function checkAvailable() { cc.assertID(this._onAccelerationEvent, 1803); return true; }, clone: function clone() { return new Acceleration(this._onAccelerationEvent); } }); var Keyboard = function Keyboard() { cc.EventListener.call(this, cc.EventListener.KEYBOARD, ListenerID.KEYBOARD, this._callback); }; js.extend(Keyboard, cc.EventListener); js.mixin(Keyboard.prototype, { constructor: Keyboard, onKeyPressed: null, onKeyReleased: null, _callback: function _callback(event) { event.isPressed ? this.onKeyPressed && this.onKeyPressed(event.keyCode, event) : this.onKeyReleased && this.onKeyReleased(event.keyCode, event); }, clone: function clone() { var eventListener = new Keyboard(); eventListener.onKeyPressed = this.onKeyPressed; eventListener.onKeyReleased = this.onKeyReleased; return eventListener; }, checkAvailable: function checkAvailable() { if (null === this.onKeyPressed && null === this.onKeyReleased) { cc.logID(1800); return false; } return true; } }); cc.EventListener.create = function(argObj) { cc.assertID(argObj && argObj.event, 1900); var listenerType = argObj.event; delete argObj.event; var listener = null; if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) listener = new TouchOneByOne(); else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) listener = new TouchAllAtOnce(); else if (listenerType === cc.EventListener.MOUSE) listener = new Mouse(); else if (listenerType === cc.EventListener.CUSTOM) { listener = new Custom(argObj.eventName, argObj.callback); delete argObj.eventName; delete argObj.callback; } else if (listenerType === cc.EventListener.KEYBOARD) listener = new Keyboard(); else if (listenerType === cc.EventListener.ACCELERATION) { listener = new Acceleration(argObj.callback); delete argObj.callback; } for (var key in argObj) listener[key] = argObj[key]; return listener; }; module.exports = cc.EventListener; }), { "../platform/js": 150 } ], 115: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); require("./CCEventListener"); var ListenerID = cc.EventListener.ListenerID; var _EventListenerVector = function _EventListenerVector() { this._fixedListeners = []; this._sceneGraphListeners = []; this.gt0Index = 0; }; _EventListenerVector.prototype = { constructor: _EventListenerVector, size: function size() { return this._fixedListeners.length + this._sceneGraphListeners.length; }, empty: function empty() { return 0 === this._fixedListeners.length && 0 === this._sceneGraphListeners.length; }, push: function push(listener) { 0 === listener._getFixedPriority() ? this._sceneGraphListeners.push(listener) : this._fixedListeners.push(listener); }, clearSceneGraphListeners: function clearSceneGraphListeners() { this._sceneGraphListeners.length = 0; }, clearFixedListeners: function clearFixedListeners() { this._fixedListeners.length = 0; }, clear: function clear() { this._sceneGraphListeners.length = 0; this._fixedListeners.length = 0; }, getFixedPriorityListeners: function getFixedPriorityListeners() { return this._fixedListeners; }, getSceneGraphPriorityListeners: function getSceneGraphPriorityListeners() { return this._sceneGraphListeners; } }; var __getListenerID = function __getListenerID(event) { var eventType = cc.Event, type = event.type; if (type === eventType.ACCELERATION) return ListenerID.ACCELERATION; if (type === eventType.KEYBOARD) return ListenerID.KEYBOARD; if (type.startsWith(eventType.MOUSE)) return ListenerID.MOUSE; type.startsWith(eventType.TOUCH) && cc.logID(2e3); return ""; }; var eventManager = { DIRTY_NONE: 0, DIRTY_FIXED_PRIORITY: 1, DIRTY_SCENE_GRAPH_PRIORITY: 2, DIRTY_ALL: 3, _listenersMap: {}, _priorityDirtyFlagMap: {}, _nodeListenersMap: {}, _toAddedListeners: [], _toRemovedListeners: [], _dirtyListeners: {}, _inDispatch: 0, _isEnabled: false, _currentTouch: null, _currentTouchListener: null, _internalCustomListenerIDs: [], _setDirtyForNode: function _setDirtyForNode(node) { var selListeners = this._nodeListenersMap[node._id]; if (selListeners) for (var j = 0, len = selListeners.length; j < len; j++) { var selListener = selListeners[j]; var listenerID = selListener._getListenerID(); null == this._dirtyListeners[listenerID] && (this._dirtyListeners[listenerID] = true); } if (node.childrenCount > 0) { var children = node._children; for (var i = 0, _len = children.length; i < _len; i++) this._setDirtyForNode(children[i]); } }, pauseTarget: function pauseTarget(node, recursive) { if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } var listeners = this._nodeListenersMap[node._id], i, len; if (listeners) for (i = 0, len = listeners.length; i < len; i++) { var listener = listeners[i]; listener._setPaused(true); listener._claimedTouches && listener._claimedTouches.includes(this._currentTouch) && this._clearCurTouch(); } if (true === recursive) { var locChildren = node._children; for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) this.pauseTarget(locChildren[i], true); } }, resumeTarget: function resumeTarget(node, recursive) { if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } var listeners = this._nodeListenersMap[node._id], i, len; if (listeners) for (i = 0, len = listeners.length; i < len; i++) listeners[i]._setPaused(false); this._setDirtyForNode(node); if (true === recursive) { var locChildren = node._children; for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) this.resumeTarget(locChildren[i], true); } }, _addListener: function _addListener(listener) { 0 === this._inDispatch ? this._forceAddEventListener(listener) : this._toAddedListeners.push(listener); }, _forceAddEventListener: function _forceAddEventListener(listener) { var listenerID = listener._getListenerID(); var listeners = this._listenersMap[listenerID]; if (!listeners) { listeners = new _EventListenerVector(); this._listenersMap[listenerID] = listeners; } listeners.push(listener); if (0 === listener._getFixedPriority()) { this._setDirty(listenerID, this.DIRTY_SCENE_GRAPH_PRIORITY); var node = listener._getSceneGraphPriority(); null === node && cc.logID(3507); this._associateNodeAndEventListener(node, listener); node.activeInHierarchy && this.resumeTarget(node); } else this._setDirty(listenerID, this.DIRTY_FIXED_PRIORITY); }, _getListeners: function _getListeners(listenerID) { return this._listenersMap[listenerID]; }, _updateDirtyFlagForSceneGraph: function _updateDirtyFlagForSceneGraph() { var locDirtyListeners = this._dirtyListeners; for (var selKey in locDirtyListeners) this._setDirty(selKey, this.DIRTY_SCENE_GRAPH_PRIORITY); this._dirtyListeners = {}; }, _removeAllListenersInVector: function _removeAllListenersInVector(listenerVector) { if (!listenerVector) return; var selListener; for (var i = listenerVector.length - 1; i >= 0; i--) { selListener = listenerVector[i]; selListener._setRegistered(false); if (null != selListener._getSceneGraphPriority()) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); } 0 === this._inDispatch && cc.js.array.removeAt(listenerVector, i); } }, _removeListenersForListenerID: function _removeListenersForListenerID(listenerID) { var listeners = this._listenersMap[listenerID], i; if (listeners) { var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); this._removeAllListenersInVector(sceneGraphPriorityListeners); this._removeAllListenersInVector(fixedPriorityListeners); delete this._priorityDirtyFlagMap[listenerID]; if (!this._inDispatch) { listeners.clear(); delete this._listenersMap[listenerID]; } } var locToAddedListeners = this._toAddedListeners, listener; for (i = locToAddedListeners.length - 1; i >= 0; i--) { listener = locToAddedListeners[i]; listener && listener._getListenerID() === listenerID && cc.js.array.removeAt(locToAddedListeners, i); } }, _sortEventListeners: function _sortEventListeners(listenerID) { var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap; locFlagMap[listenerID] && (dirtyFlag = locFlagMap[listenerID]); if (dirtyFlag !== this.DIRTY_NONE) { locFlagMap[listenerID] = this.DIRTY_NONE; dirtyFlag & this.DIRTY_FIXED_PRIORITY && this._sortListenersOfFixedPriority(listenerID); if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY) { var rootEntity = cc.director.getScene(); rootEntity && this._sortListenersOfSceneGraphPriority(listenerID); } } }, _sortListenersOfSceneGraphPriority: function _sortListenersOfSceneGraphPriority(listenerID) { var listeners = this._getListeners(listenerID); if (!listeners) return; var sceneGraphListener = listeners.getSceneGraphPriorityListeners(); if (!sceneGraphListener || 0 === sceneGraphListener.length) return; listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); }, _sortEventListenersOfSceneGraphPriorityDes: function _sortEventListenersOfSceneGraphPriorityDes(l1, l2) { var node1 = l1._getSceneGraphPriority(), node2 = l2._getSceneGraphPriority(); if (!(l2 && node2 && node2._activeInHierarchy && null !== node2._parent)) return -1; if (!l1 || !node1 || !node1._activeInHierarchy || null === node1._parent) return 1; var p1 = node1, p2 = node2, ex = false; while (p1._parent._id !== p2._parent._id) { p1 = null === p1._parent._parent ? (ex = true) && node2 : p1._parent; p2 = null === p2._parent._parent ? (ex = true) && node1 : p2._parent; } if (p1._id === p2._id) { if (p1._id === node2._id) return -1; if (p1._id === node1._id) return 1; } return ex ? p1._localZOrder - p2._localZOrder : p2._localZOrder - p1._localZOrder; }, _sortListenersOfFixedPriority: function _sortListenersOfFixedPriority(listenerID) { var listeners = this._listenersMap[listenerID]; if (!listeners) return; var fixedListeners = listeners.getFixedPriorityListeners(); if (!fixedListeners || 0 === fixedListeners.length) return; fixedListeners.sort(this._sortListenersOfFixedPriorityAsc); var index = 0; for (var len = fixedListeners.length; index < len; ) { if (fixedListeners[index]._getFixedPriority() >= 0) break; ++index; } listeners.gt0Index = index; }, _sortListenersOfFixedPriorityAsc: function _sortListenersOfFixedPriorityAsc(l1, l2) { return l1._getFixedPriority() - l2._getFixedPriority(); }, _onUpdateListeners: function _onUpdateListeners(listeners) { var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); var i, selListener, idx, toRemovedListeners = this._toRemovedListeners; if (sceneGraphPriorityListeners) for (i = sceneGraphPriorityListeners.length - 1; i >= 0; i--) { selListener = sceneGraphPriorityListeners[i]; if (!selListener._isRegistered()) { cc.js.array.removeAt(sceneGraphPriorityListeners, i); idx = toRemovedListeners.indexOf(selListener); -1 !== idx && toRemovedListeners.splice(idx, 1); } } if (fixedPriorityListeners) for (i = fixedPriorityListeners.length - 1; i >= 0; i--) { selListener = fixedPriorityListeners[i]; if (!selListener._isRegistered()) { cc.js.array.removeAt(fixedPriorityListeners, i); idx = toRemovedListeners.indexOf(selListener); -1 !== idx && toRemovedListeners.splice(idx, 1); } } sceneGraphPriorityListeners && 0 === sceneGraphPriorityListeners.length && listeners.clearSceneGraphListeners(); fixedPriorityListeners && 0 === fixedPriorityListeners.length && listeners.clearFixedListeners(); }, frameUpdateListeners: function frameUpdateListeners() { var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; for (var selKey in locListenersMap) if (locListenersMap[selKey].empty()) { delete locPriorityDirtyFlagMap[selKey]; delete locListenersMap[selKey]; } var locToAddedListeners = this._toAddedListeners; if (0 !== locToAddedListeners.length) { for (var i = 0, len = locToAddedListeners.length; i < len; i++) this._forceAddEventListener(locToAddedListeners[i]); locToAddedListeners.length = 0; } 0 !== this._toRemovedListeners.length && this._cleanToRemovedListeners(); }, _updateTouchListeners: function _updateTouchListeners(event) { var locInDispatch = this._inDispatch; cc.assertID(locInDispatch > 0, 3508); if (locInDispatch > 1) return; var listeners; listeners = this._listenersMap[ListenerID.TOUCH_ONE_BY_ONE]; listeners && this._onUpdateListeners(listeners); listeners = this._listenersMap[ListenerID.TOUCH_ALL_AT_ONCE]; listeners && this._onUpdateListeners(listeners); cc.assertID(1 === locInDispatch, 3509); var locToAddedListeners = this._toAddedListeners; if (0 !== locToAddedListeners.length) { for (var i = 0, len = locToAddedListeners.length; i < len; i++) this._forceAddEventListener(locToAddedListeners[i]); this._toAddedListeners.length = 0; } 0 !== this._toRemovedListeners.length && this._cleanToRemovedListeners(); }, _cleanToRemovedListeners: function _cleanToRemovedListeners() { var toRemovedListeners = this._toRemovedListeners; for (var i = 0; i < toRemovedListeners.length; i++) { var selListener = toRemovedListeners[i]; var listeners = this._listenersMap[selListener._getListenerID()]; if (!listeners) continue; var idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); if (sceneGraphPriorityListeners) { idx = sceneGraphPriorityListeners.indexOf(selListener); -1 !== idx && sceneGraphPriorityListeners.splice(idx, 1); } if (fixedPriorityListeners) { idx = fixedPriorityListeners.indexOf(selListener); -1 !== idx && fixedPriorityListeners.splice(idx, 1); } } toRemovedListeners.length = 0; }, _onTouchEventCallback: function _onTouchEventCallback(listener, argsObj) { if (!listener._isRegistered()) return false; var event = argsObj.event, selTouch = event.currentTouch; event.currentTarget = listener._node; var isClaimed = false, removedIdx; var getCode = event.getEventCode(), EventTouch = cc.Event.EventTouch; if (getCode === EventTouch.BEGAN) { if (!cc.macro.ENABLE_MULTI_TOUCH && eventManager._currentTouch) { var node = eventManager._currentTouchListener._node; if (node && node.activeInHierarchy) return false; } if (listener.onTouchBegan) { isClaimed = listener.onTouchBegan(selTouch, event); if (isClaimed && listener._registered) { listener._claimedTouches.push(selTouch); eventManager._currentTouchListener = listener; eventManager._currentTouch = selTouch; } } } else if (listener._claimedTouches.length > 0 && -1 !== (removedIdx = listener._claimedTouches.indexOf(selTouch))) { isClaimed = true; if (!cc.macro.ENABLE_MULTI_TOUCH && eventManager._currentTouch && eventManager._currentTouch !== selTouch) return false; if (getCode === EventTouch.MOVED && listener.onTouchMoved) listener.onTouchMoved(selTouch, event); else if (getCode === EventTouch.ENDED) { listener.onTouchEnded && listener.onTouchEnded(selTouch, event); listener._registered && listener._claimedTouches.splice(removedIdx, 1); eventManager._clearCurTouch(); } else if (getCode === EventTouch.CANCELED) { listener.onTouchCancelled && listener.onTouchCancelled(selTouch, event); listener._registered && listener._claimedTouches.splice(removedIdx, 1); eventManager._clearCurTouch(); } } if (event.isStopped()) { eventManager._updateTouchListeners(event); return true; } if (isClaimed && listener.swallowTouches) { argsObj.needsMutableSet && argsObj.touches.splice(selTouch, 1); return true; } return false; }, _dispatchTouchEvent: function _dispatchTouchEvent(event) { this._sortEventListeners(ListenerID.TOUCH_ONE_BY_ONE); this._sortEventListeners(ListenerID.TOUCH_ALL_AT_ONCE); var oneByOneListeners = this._getListeners(ListenerID.TOUCH_ONE_BY_ONE); var allAtOnceListeners = this._getListeners(ListenerID.TOUCH_ALL_AT_ONCE); if (null === oneByOneListeners && null === allAtOnceListeners) return; var originalTouches = event.getTouches(), mutableTouches = cc.js.array.copy(originalTouches); var oneByOneArgsObj = { event: event, needsMutableSet: oneByOneListeners && allAtOnceListeners, touches: mutableTouches, selTouch: null }; if (oneByOneListeners) for (var i = 0; i < originalTouches.length; i++) { event.currentTouch = originalTouches[i]; event._propagationStopped = event._propagationImmediateStopped = false; this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj); } if (allAtOnceListeners && mutableTouches.length > 0) { this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, { event: event, touches: mutableTouches }); if (event.isStopped()) return; } this._updateTouchListeners(event); }, _onTouchesEventCallback: function _onTouchesEventCallback(listener, callbackParams) { if (!listener._registered) return false; var EventTouch = cc.Event.EventTouch, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode(); event.currentTarget = listener._node; getCode === EventTouch.BEGAN && listener.onTouchesBegan ? listener.onTouchesBegan(touches, event) : getCode === EventTouch.MOVED && listener.onTouchesMoved ? listener.onTouchesMoved(touches, event) : getCode === EventTouch.ENDED && listener.onTouchesEnded ? listener.onTouchesEnded(touches, event) : getCode === EventTouch.CANCELED && listener.onTouchesCancelled && listener.onTouchesCancelled(touches, event); if (event.isStopped()) { eventManager._updateTouchListeners(event); return true; } return false; }, _associateNodeAndEventListener: function _associateNodeAndEventListener(node, listener) { var listeners = this._nodeListenersMap[node._id]; if (!listeners) { listeners = []; this._nodeListenersMap[node._id] = listeners; } listeners.push(listener); }, _dissociateNodeAndEventListener: function _dissociateNodeAndEventListener(node, listener) { var listeners = this._nodeListenersMap[node._id]; if (listeners) { cc.js.array.remove(listeners, listener); 0 === listeners.length && delete this._nodeListenersMap[node._id]; } }, _dispatchEventToListeners: function _dispatchEventToListeners(listeners, onEvent, eventOrArgs) { var shouldStopPropagation = false; var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); var i = 0, j, selListener; if (fixedPriorityListeners && 0 !== fixedPriorityListeners.length) for (;i < listeners.gt0Index; ++i) { selListener = fixedPriorityListeners[i]; if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { shouldStopPropagation = true; break; } } if (sceneGraphPriorityListeners && !shouldStopPropagation) for (j = 0; j < sceneGraphPriorityListeners.length; j++) { selListener = sceneGraphPriorityListeners[j]; if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { shouldStopPropagation = true; break; } } if (fixedPriorityListeners && !shouldStopPropagation) for (;i < fixedPriorityListeners.length; ++i) { selListener = fixedPriorityListeners[i]; if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { shouldStopPropagation = true; break; } } }, _setDirty: function _setDirty(listenerID, flag) { var locDirtyFlagMap = this._priorityDirtyFlagMap; null == locDirtyFlagMap[listenerID] ? locDirtyFlagMap[listenerID] = flag : locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID]; }, _sortNumberAsc: function _sortNumberAsc(a, b) { return a - b; }, hasEventListener: function hasEventListener(listenerID) { return !!this._getListeners(listenerID); }, addListener: function addListener(listener, nodeOrPriority) { cc.assertID(listener && nodeOrPriority, 3503); if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode)) { cc.warnID(3506); return; } if (listener instanceof cc.EventListener) { if (listener._isRegistered()) { cc.logID(3505); return; } } else { cc.assertID(!cc.js.isNumber(nodeOrPriority), 3504); listener = cc.EventListener.create(listener); } if (!listener.checkAvailable()) return; if (cc.js.isNumber(nodeOrPriority)) { if (0 === nodeOrPriority) { cc.logID(3500); return; } listener._setSceneGraphPriority(null); listener._setFixedPriority(nodeOrPriority); listener._setRegistered(true); listener._setPaused(false); this._addListener(listener); } else { listener._setSceneGraphPriority(nodeOrPriority); listener._setFixedPriority(0); listener._setRegistered(true); this._addListener(listener); } return listener; }, addCustomListener: function addCustomListener(eventName, callback) { var listener = new cc.EventListener.create({ event: cc.EventListener.CUSTOM, eventName: eventName, callback: callback }); this.addListener(listener, 1); return listener; }, removeListener: function removeListener(listener) { if (null == listener) return; var isFound, locListener = this._listenersMap; for (var selKey in locListener) { var listeners = locListener[selKey]; var fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener); if (isFound) this._setDirty(listener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY); else { isFound = this._removeListenerInVector(fixedPriorityListeners, listener); isFound && this._setDirty(listener._getListenerID(), this.DIRTY_FIXED_PRIORITY); } if (listeners.empty()) { delete this._priorityDirtyFlagMap[listener._getListenerID()]; delete locListener[selKey]; } if (isFound) break; } if (!isFound) { var locToAddedListeners = this._toAddedListeners; for (var i = locToAddedListeners.length - 1; i >= 0; i--) { var selListener = locToAddedListeners[i]; if (selListener === listener) { cc.js.array.removeAt(locToAddedListeners, i); selListener._setRegistered(false); break; } } } this._currentTouchListener === listener && this._clearCurTouch(); }, _clearCurTouch: function _clearCurTouch() { this._currentTouchListener = null; this._currentTouch = null; }, _removeListenerInCallback: function _removeListenerInCallback(listeners, callback) { if (null == listeners) return false; for (var i = listeners.length - 1; i >= 0; i--) { var selListener = listeners[i]; if (selListener._onCustomEvent === callback || selListener._onEvent === callback) { selListener._setRegistered(false); if (null != selListener._getSceneGraphPriority()) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); } 0 === this._inDispatch ? cc.js.array.removeAt(listeners, i) : this._toRemovedListeners.push(selListener); return true; } } return false; }, _removeListenerInVector: function _removeListenerInVector(listeners, listener) { if (null == listeners) return false; for (var i = listeners.length - 1; i >= 0; i--) { var selListener = listeners[i]; if (selListener === listener) { selListener._setRegistered(false); if (null != selListener._getSceneGraphPriority()) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); } 0 === this._inDispatch ? cc.js.array.removeAt(listeners, i) : this._toRemovedListeners.push(selListener); return true; } } return false; }, removeListeners: function removeListeners(listenerType, recursive) { var i, _t = this; if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) { cc.warnID(3506); return; } if (void 0 !== listenerType._id) { var listeners = _t._nodeListenersMap[listenerType._id], i; if (listeners) { var listenersCopy = cc.js.array.copy(listeners); for (i = 0; i < listenersCopy.length; i++) _t.removeListener(listenersCopy[i]); delete _t._nodeListenersMap[listenerType._id]; } var locToAddedListeners = _t._toAddedListeners; for (i = 0; i < locToAddedListeners.length; ) { var listener = locToAddedListeners[i]; if (listener._getSceneGraphPriority() === listenerType) { listener._setSceneGraphPriority(null); listener._setRegistered(false); locToAddedListeners.splice(i, 1); } else ++i; } if (true === recursive) { var locChildren = listenerType.children, len; for (i = 0, len = locChildren.length; i < len; i++) _t.removeListeners(locChildren[i], true); } } else listenerType === cc.EventListener.TOUCH_ONE_BY_ONE ? _t._removeListenersForListenerID(ListenerID.TOUCH_ONE_BY_ONE) : listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE ? _t._removeListenersForListenerID(ListenerID.TOUCH_ALL_AT_ONCE) : listenerType === cc.EventListener.MOUSE ? _t._removeListenersForListenerID(ListenerID.MOUSE) : listenerType === cc.EventListener.ACCELERATION ? _t._removeListenersForListenerID(ListenerID.ACCELERATION) : listenerType === cc.EventListener.KEYBOARD ? _t._removeListenersForListenerID(ListenerID.KEYBOARD) : cc.logID(3501); }, removeCustomListeners: function removeCustomListeners(customEventName) { this._removeListenersForListenerID(customEventName); }, removeAllListeners: function removeAllListeners() { var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs; for (var selKey in locListeners) -1 === locInternalCustomEventIDs.indexOf(selKey) && this._removeListenersForListenerID(selKey); }, setPriority: function setPriority(listener, fixedPriority) { if (null == listener) return; var locListeners = this._listenersMap; for (var selKey in locListeners) { var selListeners = locListeners[selKey]; var fixedPriorityListeners = selListeners.getFixedPriorityListeners(); if (fixedPriorityListeners) { var found = fixedPriorityListeners.indexOf(listener); if (-1 !== found) { null != listener._getSceneGraphPriority() && cc.logID(3502); if (listener._getFixedPriority() !== fixedPriority) { listener._setFixedPriority(fixedPriority); this._setDirty(listener._getListenerID(), this.DIRTY_FIXED_PRIORITY); } return; } } } }, setEnabled: function setEnabled(enabled) { this._isEnabled = enabled; }, isEnabled: function isEnabled() { return this._isEnabled; }, dispatchEvent: function dispatchEvent(event) { if (!this._isEnabled) return; this._updateDirtyFlagForSceneGraph(); this._inDispatch++; if (!event || !event.getType) { cc.errorID(3511); return; } if (event.getType().startsWith(cc.Event.TOUCH)) { this._dispatchTouchEvent(event); this._inDispatch--; return; } var listenerID = __getListenerID(event); this._sortEventListeners(listenerID); var selListeners = this._listenersMap[listenerID]; if (null != selListeners) { this._dispatchEventToListeners(selListeners, this._onListenerCallback, event); this._onUpdateListeners(selListeners); } this._inDispatch--; }, _onListenerCallback: function _onListenerCallback(listener, event) { event.currentTarget = listener._target; listener._onEvent(event); return event.isStopped(); }, dispatchCustomEvent: function dispatchCustomEvent(eventName, optionalUserData) { var ev = new cc.Event.EventCustom(eventName); ev.setUserData(optionalUserData); this.dispatchEvent(ev); } }; js.get(cc, "eventManager", (function() { cc.errorID(1405, "cc.eventManager", "cc.EventTarget or cc.systemEvent"); return eventManager; })); module.exports = cc.internal.eventManager = eventManager; }), { "../platform/js": 150, "./CCEventListener": 114 } ], 116: [ (function(require, module, exports) { "use strict"; cc.Touch = function(x, y, id) { this._lastModified = 0; this.setTouchInfo(id, x, y); }; cc.Touch.prototype = { constructor: cc.Touch, getLocation: function getLocation() { return cc.v2(this._point.x, this._point.y); }, getLocationX: function getLocationX() { return this._point.x; }, getLocationY: function getLocationY() { return this._point.y; }, getPreviousLocation: function getPreviousLocation() { return cc.v2(this._prevPoint.x, this._prevPoint.y); }, getStartLocation: function getStartLocation() { return cc.v2(this._startPoint.x, this._startPoint.y); }, getDelta: function getDelta() { return this._point.sub(this._prevPoint); }, getLocationInView: function getLocationInView() { return cc.v2(this._point.x, cc.view._designResolutionSize.height - this._point.y); }, getPreviousLocationInView: function getPreviousLocationInView() { return cc.v2(this._prevPoint.x, cc.view._designResolutionSize.height - this._prevPoint.y); }, getStartLocationInView: function getStartLocationInView() { return cc.v2(this._startPoint.x, cc.view._designResolutionSize.height - this._startPoint.y); }, getID: function getID() { return this._id; }, setTouchInfo: function setTouchInfo(id, x, y) { this._prevPoint = this._point; this._point = cc.v2(x || 0, y || 0); this._id = id; if (!this._startPointCaptured) { this._startPoint = cc.v2(this._point); cc.view._convertPointWithScale(this._startPoint); this._startPointCaptured = true; } }, _setPoint: function _setPoint(x, y) { if (void 0 === y) { this._point.x = x.x; this._point.y = x.y; } else { this._point.x = x; this._point.y = y; } }, _setPrevPoint: function _setPrevPoint(x, y) { this._prevPoint = void 0 === y ? cc.v2(x.x, x.y) : cc.v2(x || 0, y || 0); } }; }), {} ], 117: [ (function(require, module, exports) { "use strict"; require("./CCEvent"); require("./CCTouch"); require("./CCEventListener"); var eventManager = require("./CCEventManager"); module.exports = eventManager; false; }), { "./CCEvent": 113, "./CCEventListener": 114, "./CCEventManager": 115, "./CCTouch": 116 } ], 118: [ (function(require, module, exports) { "use strict"; var js = cc.js; var CallbacksInvoker = require("../platform/callbacks-invoker"); function EventListeners() { CallbacksInvoker.call(this); } js.extend(EventListeners, CallbacksInvoker); EventListeners.prototype.emit = function(event, captureListeners) { var key = event.type; var list = this._callbackTable[key]; if (list) { var rootInvoker = !list.isInvoking; list.isInvoking = true; var infos = list.callbackInfos; for (var i = 0, len = infos.length; i < len; ++i) { var info = infos[i]; if (info && info.callback) { info.callback.call(info.target, event, captureListeners); if (event._propagationImmediateStopped) break; } } if (rootInvoker) { list.isInvoking = false; list.containCanceled && list.purgeCanceled(); } } }; module.exports = EventListeners; false; }), { "../platform/callbacks-invoker": 142 } ], 119: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); var CallbacksInvoker = require("../platform/callbacks-invoker"); var fastRemove = js.array.fastRemove; function EventTarget() { CallbacksInvoker.call(this); } js.extend(EventTarget, CallbacksInvoker); var proto = EventTarget.prototype; proto.__on = proto.on; proto.on = function(type, callback, target, once) { if (!callback) { cc.errorID(6800); return; } if (!this.hasEventListener(type, callback, target)) { this.__on(type, callback, target, once); target && target.__eventTargets && target.__eventTargets.push(this); } return callback; }; proto.__off = proto.off; proto.off = function(type, callback, target) { if (callback) { this.__off(type, callback, target); target && target.__eventTargets && fastRemove(target.__eventTargets, this); } else { var list = this._callbackTable[type]; if (!list) return; var infos = list.callbackInfos; for (var i = 0; i < infos.length; ++i) { var _target = infos[i] && infos[i].target; _target && _target.__eventTargets && fastRemove(_target.__eventTargets, this); } this.removeAll(type); } }; proto.targetOff = function(target) { this.removeAll(target); target && target.__eventTargets && fastRemove(target.__eventTargets, this); }; proto.once = function(type, callback, target) { this.on(type, callback, target, true); }; proto.dispatchEvent = function(event) { this.emit(event.type, event); }; proto.clear = function() { for (var key in this._callbackTable) { var list = this._callbackTable[key]; var infos = list.callbackInfos; for (var i = infos.length - 1; i >= 0; i--) { var info = infos[i]; info && this.off(key, info.callback, info.target); } } }; cc.EventTarget = module.exports = EventTarget; }), { "../platform/callbacks-invoker": 142, "../platform/js": 150 } ], 120: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); cc.Event = function(type, bubbles) { this.type = type; this.bubbles = !!bubbles; this.target = null; this.currentTarget = null; this.eventPhase = 0; this._propagationStopped = false; this._propagationImmediateStopped = false; }; cc.Event.prototype = { constructor: cc.Event, unuse: function unuse() { this.type = cc.Event.NO_TYPE; this.target = null; this.currentTarget = null; this.eventPhase = cc.Event.NONE; this._propagationStopped = false; this._propagationImmediateStopped = false; }, reuse: function reuse(type, bubbles) { this.type = type; this.bubbles = bubbles || false; }, stopPropagation: function stopPropagation() { this._propagationStopped = true; }, stopPropagationImmediate: function stopPropagationImmediate() { this._propagationImmediateStopped = true; }, isStopped: function isStopped() { return this._propagationStopped || this._propagationImmediateStopped; }, getCurrentTarget: function getCurrentTarget() { return this.currentTarget; }, getType: function getType() { return this.type; } }; cc.Event.NO_TYPE = "no_type"; cc.Event.TOUCH = "touch"; cc.Event.MOUSE = "mouse"; cc.Event.KEYBOARD = "keyboard"; cc.Event.ACCELERATION = "acceleration"; cc.Event.NONE = 0; cc.Event.CAPTURING_PHASE = 1; cc.Event.AT_TARGET = 2; cc.Event.BUBBLING_PHASE = 3; var EventCustom = function EventCustom(type, bubbles) { cc.Event.call(this, type, bubbles); this.detail = null; }; js.extend(EventCustom, cc.Event); EventCustom.prototype.reset = EventCustom; EventCustom.prototype.setUserData = function(data) { this.detail = data; }; EventCustom.prototype.getUserData = function() { return this.detail; }; EventCustom.prototype.getEventName = cc.Event.prototype.getType; var MAX_POOL_SIZE = 10; var _eventPool = new js.Pool(MAX_POOL_SIZE); EventCustom.put = function(event) { _eventPool.put(event); }; EventCustom.get = function(type, bubbles) { var event = _eventPool._get(); event ? event.reset(type, bubbles) : event = new EventCustom(type, bubbles); return event; }; cc.Event.EventCustom = EventCustom; module.exports = cc.Event; }), { "../platform/js": 150 } ], 121: [ (function(require, module, exports) { "use strict"; require("./event"); require("./event-listeners"); require("./event-target"); require("./system-event"); }), { "./event": 120, "./event-listeners": 118, "./event-target": 119, "./system-event": 122 } ], 122: [ (function(require, module, exports) { "use strict"; var EventTarget = require("../event/event-target"); var eventManager = require("../event-manager"); var inputManger = require("../platform/CCInputManager"); var EventType = cc.Enum({ KEY_DOWN: "keydown", KEY_UP: "keyup", DEVICEMOTION: "devicemotion" }); var keyboardListener = null; var accelerationListener = null; var SystemEvent = cc.Class({ name: "SystemEvent", extends: EventTarget, statics: { EventType: EventType }, setAccelerometerEnabled: function setAccelerometerEnabled(isEnable) { false; isEnable && window.DeviceMotionEvent && "function" === typeof DeviceMotionEvent.requestPermission ? DeviceMotionEvent.requestPermission().then((function(response) { console.log("Device Motion Event request permission: " + response); inputManger.setAccelerometerEnabled("granted" === response); })) : inputManger.setAccelerometerEnabled(isEnable); }, setAccelerometerInterval: function setAccelerometerInterval(interval) { false; inputManger.setAccelerometerInterval(interval); }, on: function on(type, callback, target, once) { false; this._super(type, callback, target, once); if (type === EventType.KEY_DOWN || type === EventType.KEY_UP) { keyboardListener || (keyboardListener = cc.EventListener.create({ event: cc.EventListener.KEYBOARD, onKeyPressed: function onKeyPressed(keyCode, event) { event.type = EventType.KEY_DOWN; cc.systemEvent.dispatchEvent(event); }, onKeyReleased: function onKeyReleased(keyCode, event) { event.type = EventType.KEY_UP; cc.systemEvent.dispatchEvent(event); } })); eventManager.hasEventListener(cc.EventListener.ListenerID.KEYBOARD) || eventManager.addListener(keyboardListener, 1); } if (type === EventType.DEVICEMOTION) { accelerationListener || (accelerationListener = cc.EventListener.create({ event: cc.EventListener.ACCELERATION, callback: function callback(acc, event) { event.type = EventType.DEVICEMOTION; cc.systemEvent.dispatchEvent(event); } })); eventManager.hasEventListener(cc.EventListener.ListenerID.ACCELERATION) || eventManager.addListener(accelerationListener, 1); } }, off: function off(type, callback, target) { false; this._super(type, callback, target); if (keyboardListener && (type === EventType.KEY_DOWN || type === EventType.KEY_UP)) { var hasKeyDownEventListener = this.hasEventListener(EventType.KEY_DOWN); var hasKeyUpEventListener = this.hasEventListener(EventType.KEY_UP); hasKeyDownEventListener || hasKeyUpEventListener || eventManager.removeListener(keyboardListener); } accelerationListener && type === EventType.DEVICEMOTION && eventManager.removeListener(accelerationListener); } }); cc.SystemEvent = module.exports = SystemEvent; cc.systemEvent = new cc.SystemEvent(); }), { "../event-manager": 117, "../event/event-target": 119, "../platform/CCInputManager": 133 } ], 123: [ (function(require, module, exports) { "use strict"; var RenderComponent = require("../components/CCRenderComponent"); var Material = require("../assets/material/CCMaterial"); var Types = require("./types"); var LineCap = Types.LineCap; var LineJoin = Types.LineJoin; var Graphics = cc.Class({ name: "cc.Graphics", extends: RenderComponent, editor: false, ctor: function ctor() { this._impl = new Graphics._Impl(this); }, properties: { _lineWidth: 2, _strokeColor: cc.Color.BLACK, _lineJoin: LineJoin.MITER, _lineCap: LineCap.BUTT, _fillColor: cc.Color.WHITE, _miterLimit: 10, lineWidth: { get: function get() { return this._lineWidth; }, set: function set(value) { this._lineWidth = value; this._impl.lineWidth = value; } }, lineJoin: { get: function get() { return this._lineJoin; }, set: function set(value) { this._lineJoin = value; this._impl.lineJoin = value; }, type: LineJoin }, lineCap: { get: function get() { return this._lineCap; }, set: function set(value) { this._lineCap = value; this._impl.lineCap = value; }, type: LineCap }, strokeColor: { get: function get() { return this._strokeColor; }, set: function set(value) { this._impl.strokeColor = this._strokeColor = cc.color(value); } }, fillColor: { get: function get() { return this._fillColor; }, set: function set(value) { this._impl.fillColor = this._fillColor = cc.color(value); } }, miterLimit: { get: function get() { return this._miterLimit; }, set: function set(value) { this._miterLimit = value; this._impl.miterLimit = value; } } }, statics: { LineJoin: LineJoin, LineCap: LineCap }, onRestore: function onRestore() { this._impl || (this._impl = new Graphics._Impl(this)); }, onDestroy: function onDestroy() { this.clear(true); this._super(); this._impl = null; }, _getDefaultMaterial: function _getDefaultMaterial() { return Material.getBuiltinMaterial("2d-graphics"); }, _updateMaterial: function _updateMaterial() { var material = this._materials[0]; if (!material) return; void 0 !== material.getDefine("CC_USE_MODEL") && material.define("CC_USE_MODEL", true); void 0 !== material.getDefine("CC_SUPPORT_standard_derivatives") && cc.sys.glExtension("OES_standard_derivatives") && material.define("CC_SUPPORT_standard_derivatives", true); }, moveTo: function moveTo(x, y) { if (true, x instanceof cc.Vec2) { cc.warn("[moveTo] : Can not pass Vec2 as [x, y] value, please check it."); return; } this._impl.moveTo(x, y); }, lineTo: function lineTo(x, y) { if (true, x instanceof cc.Vec2) { cc.warn("[moveTo] : Can not pass Vec2 as [x, y] value, please check it."); return; } this._impl.lineTo(x, y); }, bezierCurveTo: function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) { this._impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); }, quadraticCurveTo: function quadraticCurveTo(cx, cy, x, y) { this._impl.quadraticCurveTo(cx, cy, x, y); }, arc: function arc(cx, cy, r, startAngle, endAngle, counterclockwise) { this._impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise); }, ellipse: function ellipse(cx, cy, rx, ry) { this._impl.ellipse(cx, cy, rx, ry); }, circle: function circle(cx, cy, r) { this._impl.circle(cx, cy, r); }, rect: function rect(x, y, w, h) { this._impl.rect(x, y, w, h); }, roundRect: function roundRect(x, y, w, h, r) { this._impl.roundRect(x, y, w, h, r); }, fillRect: function fillRect(x, y, w, h) { this.rect(x, y, w, h); this.fill(); }, clear: function clear(clean) { this._impl.clear(clean); this._assembler && this._assembler.clear(clean); }, close: function close() { this._impl.close(); }, stroke: function stroke() { this._assembler || this._resetAssembler(); this._assembler.stroke(this); }, fill: function fill() { this._assembler || this._resetAssembler(); this._assembler.fill(this); } }); cc.Graphics = module.exports = Graphics; cc.Graphics.Types = Types; cc.Graphics.Helper = require("./helper"); }), { "../assets/material/CCMaterial": 76, "../components/CCRenderComponent": 100, "./helper": 124, "./types": 126 } ], 124: [ (function(require, module, exports) { "use strict"; var PointFlags = require("./types").PointFlags; var PI = Math.PI; var min = Math.min; var max = Math.max; var cos = Math.cos; var sin = Math.sin; var abs = Math.abs; var sign = Math.sign; var KAPPA90 = .5522847493; function arc(ctx, cx, cy, r, startAngle, endAngle, counterclockwise) { counterclockwise = counterclockwise || false; var a = 0, da = 0, hda = 0, kappa = 0; var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; var px = 0, py = 0, ptanx = 0, ptany = 0; var i, ndivs; da = endAngle - startAngle; if (counterclockwise) if (abs(da) >= 2 * PI) da = 2 * PI; else while (da < 0) da += 2 * PI; else if (abs(da) >= 2 * PI) da = 2 * -PI; else while (da > 0) da -= 2 * PI; ndivs = 0 | max(1, min(abs(da) / (.5 * PI) + .5, 5)); hda = da / ndivs / 2; kappa = abs(4 / 3 * (1 - cos(hda)) / sin(hda)); counterclockwise || (kappa = -kappa); for (i = 0; i <= ndivs; i++) { a = startAngle + da * (i / ndivs); dx = cos(a); dy = sin(a); x = cx + dx * r; y = cy + dy * r; tanx = -dy * r * kappa; tany = dx * r * kappa; 0 === i ? ctx.moveTo(x, y) : ctx.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y); px = x; py = y; ptanx = tanx; ptany = tany; } } function ellipse(ctx, cx, cy, rx, ry) { ctx.moveTo(cx - rx, cy); ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry); ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy); ctx.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry); ctx.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy); ctx.close(); } function roundRect(ctx, x, y, w, h, r) { if (r < .1) { ctx.rect(x, y, w, h); return; } var rx = min(r, .5 * abs(w)) * sign(w), ry = min(r, .5 * abs(h)) * sign(h); ctx.moveTo(x, y + ry); ctx.lineTo(x, y + h - ry); ctx.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h); ctx.lineTo(x + w - rx, y + h); ctx.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry); ctx.lineTo(x + w, y + ry); ctx.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y); ctx.lineTo(x + rx, y); ctx.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry); ctx.close(); } function tesselateBezier(ctx, x1, y1, x2, y2, x3, y3, x4, y4, level, type) { var x12, y12, x23, y23, x34, y34, x123, y123, x234, y234, x1234, y1234; var dx, dy, d2, d3; if (level > 10) return; x12 = .5 * (x1 + x2); y12 = .5 * (y1 + y2); x23 = .5 * (x2 + x3); y23 = .5 * (y2 + y3); x34 = .5 * (x3 + x4); y34 = .5 * (y3 + y4); x123 = .5 * (x12 + x23); y123 = .5 * (y12 + y23); dx = x4 - x1; dy = y4 - y1; d2 = abs((x2 - x4) * dy - (y2 - y4) * dx); d3 = abs((x3 - x4) * dy - (y3 - y4) * dx); if ((d2 + d3) * (d2 + d3) < ctx._tessTol * (dx * dx + dy * dy)) { ctx._addPoint(x4, y4, 0 === type ? type | PointFlags.PT_BEVEL : type); return; } x234 = .5 * (x23 + x34); y234 = .5 * (y23 + y34); x1234 = .5 * (x123 + x234); y1234 = .5 * (y123 + y234); tesselateBezier(ctx, x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0); tesselateBezier(ctx, x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type); } module.exports = { arc: arc, ellipse: ellipse, roundRect: roundRect, tesselateBezier: tesselateBezier }; }), { "./types": 126 } ], 125: [ (function(require, module, exports) { "use strict"; require("./graphics"); }), { "./graphics": 123 } ], 126: [ (function(require, module, exports) { "use strict"; var LineCap = cc.Enum({ BUTT: 0, ROUND: 1, SQUARE: 2 }); var LineJoin = cc.Enum({ BEVEL: 0, ROUND: 1, MITER: 2 }); var PointFlags = cc.Enum({ PT_CORNER: 1, PT_LEFT: 2, PT_BEVEL: 4, PT_INNERBEVEL: 8 }); module.exports = { LineCap: LineCap, LineJoin: LineJoin, PointFlags: PointFlags }; }), {} ], 127: [ (function(require, module, exports) { "use strict"; require("./platform"); require("./assets"); true; require("./CCNode"); require("./CCPrivateNode"); require("./CCScene"); require("./components"); require("./graphics"); require("./collider"); require("./collider/CCIntersection"); require("./physics"); require("./camera/CCCamera"); require("./geom-utils"); require("./sp"); require("./mesh"); require("./3d"); require("./base-ui/CCWidgetManager"); }), { "./3d": void 0, "./CCNode": 24, "./CCPrivateNode": 25, "./CCScene": 26, "./assets": 74, "./base-ui/CCWidgetManager": 85, "./camera/CCCamera": 86, "./collider": void 0, "./collider/CCIntersection": void 0, "./components": 111, "./geom-utils": void 0, "./graphics": 125, "./mesh": void 0, "./physics": void 0, "./platform": 147, "./sp": 203 } ], 128: [ (function(require, module, exports) { "use strict"; var CompScheduler = require("./component-scheduler"); var Flags = require("./platform/CCObject").Flags; var js = require("./platform/js"); var callerFunctor = false; var MAX_POOL_SIZE = 4; var IsPreloadStarted = Flags.IsPreloadStarted; var IsOnLoadStarted = Flags.IsOnLoadStarted; var IsOnLoadCalled = Flags.IsOnLoadCalled; var Deactivating = Flags.Deactivating; var callPreloadInTryCatch = false; var callOnLoadInTryCatch = false; var callOnDestroyInTryCatch = false; var callOnFocusInTryCatch = false; var callOnLostFocusInTryCatch = false; var UnsortedInvoker = cc.Class({ extends: CompScheduler.LifeCycleInvoker, add: function add(comp) { this._zero.array.push(comp); }, remove: function remove(comp) { this._zero.fastRemove(comp); }, cancelInactive: function cancelInactive(flagToClear) { CompScheduler.LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear); }, invoke: function invoke() { this._invoke(this._zero); this._zero.array.length = 0; } }); var invokePreload = CompScheduler.createInvokeImpl("c.__preload();"); var invokeOnLoad = CompScheduler.createInvokeImpl("c.onLoad();c._objFlags|=" + IsOnLoadCalled, false, IsOnLoadCalled); var activateTasksPool = new js.Pool(MAX_POOL_SIZE); activateTasksPool.get = function getActivateTask() { var task = this._get() || { preload: new UnsortedInvoker(invokePreload), onLoad: new CompScheduler.OneOffInvoker(invokeOnLoad), onEnable: new CompScheduler.OneOffInvoker(CompScheduler.invokeOnEnable) }; task.preload._zero.i = -1; var invoker = task.onLoad; invoker._zero.i = -1; invoker._neg.i = -1; invoker._pos.i = -1; invoker = task.onEnable; invoker._zero.i = -1; invoker._neg.i = -1; invoker._pos.i = -1; return task; }; function _componentCorrupted(node, comp, index) { false; comp ? node._removeComponent(comp) : js.array.removeAt(node._components, index); } function _onLoadInEditor(comp) { if (comp.onLoad && !cc.engine._isPlaying) { var focused = Editor.Selection.curActivate("node") === comp.node.uuid; focused ? comp.onFocusInEditor && callOnFocusInTryCatch(comp) : comp.onLostFocusInEditor && callOnLostFocusInTryCatch(comp); } true; _Scene.AssetsWatcher.start(comp); } function ctor() { this._activatingStack = []; } var NodeActivator = cc.Class({ ctor: ctor, reset: ctor, _activateNodeRecursively: function _activateNodeRecursively(node, preloadInvoker, onLoadInvoker, onEnableInvoker) { if (node._objFlags & Deactivating) { cc.errorID(3816, node.name); return; } node._activeInHierarchy = true; var originCount = node._components.length; for (var i = 0; i < originCount; ++i) { var component = node._components[i]; if (component instanceof cc.Component) this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker); else { _componentCorrupted(node, component, i); --i; --originCount; } } node._childArrivalOrder = node._children.length; for (var _i = 0, len = node._children.length; _i < len; ++_i) { var child = node._children[_i]; child._localZOrder = 4294901760 & child._localZOrder | _i + 1; child._active && this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker); } node._onPostActivated(true); }, _deactivateNodeRecursively: function _deactivateNodeRecursively(node) { false; node._objFlags |= Deactivating; node._activeInHierarchy = false; var originCount = node._components.length; for (var c = 0; c < originCount; ++c) { var component = node._components[c]; if (component._enabled) { cc.director._compScheduler.disableComp(component); if (node._activeInHierarchy) { node._objFlags &= ~Deactivating; return; } } } for (var i = 0, len = node._children.length; i < len; ++i) { var child = node._children[i]; if (child._activeInHierarchy) { this._deactivateNodeRecursively(child); if (node._activeInHierarchy) { node._objFlags &= ~Deactivating; return; } } } node._onPostActivated(false); node._objFlags &= ~Deactivating; }, activateNode: function activateNode(node, active) { if (active) { var task = activateTasksPool.get(); this._activatingStack.push(task); this._activateNodeRecursively(node, task.preload, task.onLoad, task.onEnable); task.preload.invoke(); task.onLoad.invoke(); task.onEnable.invoke(); this._activatingStack.pop(); activateTasksPool.put(task); } else { this._deactivateNodeRecursively(node); var stack = this._activatingStack; for (var i = 0; i < stack.length; i++) { var lastTask = stack[i]; lastTask.preload.cancelInactive(IsPreloadStarted); lastTask.onLoad.cancelInactive(IsOnLoadStarted); lastTask.onEnable.cancelInactive(); } } node.emit("active-in-hierarchy-changed", node); }, activateComp: function(comp, preloadInvoker, onLoadInvoker, onEnableInvoker) { if (!cc.isValid(comp, true)) return; if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; comp.__preload && (preloadInvoker ? preloadInvoker.add(comp) : comp.__preload()); } if (!(comp._objFlags & IsOnLoadStarted)) { comp._objFlags |= IsOnLoadStarted; if (comp.onLoad) if (onLoadInvoker) onLoadInvoker.add(comp); else { comp.onLoad(); comp._objFlags |= IsOnLoadCalled; } else comp._objFlags |= IsOnLoadCalled; } if (comp._enabled) { var deactivatedOnLoading = !comp.node._activeInHierarchy; if (deactivatedOnLoading) return; cc.director._compScheduler.enableComp(comp, onEnableInvoker); } }, destroyComp: function(comp) { cc.director._compScheduler.disableComp(comp); comp.onDestroy && comp._objFlags & IsOnLoadCalled && comp.onDestroy(); }, resetComp: false }); module.exports = NodeActivator; }), { "./component-scheduler": 87, "./platform/CCObject": 135, "./platform/js": 150, "./utils/misc": 217 } ], 129: [ (function(require, module, exports) { "use strict"; var js = require("./js"); var Enum = require("./CCEnum"); var utils = require("./utils"); var _isPlainEmptyObj_DEV = utils.isPlainEmptyObj_DEV; var _cloneable_DEV = utils.cloneable_DEV; var Attr = require("./attribute"); var DELIMETER = Attr.DELIMETER; var preprocess = require("./preprocess-class"); require("./requiring-frame"); var BUILTIN_ENTRIES = [ "name", "extends", "mixins", "ctor", "__ctor__", "properties", "statics", "editor", "__ES6__" ]; var INVALID_STATICS_DEV = false; function pushUnique(array, item) { array.indexOf(item) < 0 && array.push(item); } var deferredInitializer = { datas: null, push: function push(data) { if (this.datas) this.datas.push(data); else { this.datas = [ data ]; var self = this; setTimeout((function() { self.init(); }), 0); } }, init: function init() { var datas = this.datas; if (datas) { for (var i = 0; i < datas.length; ++i) { var data = datas[i]; var cls = data.cls; var properties = data.props; "function" === typeof properties && (properties = properties()); var name = js.getClassName(cls); properties ? declareProperties(cls, name, properties, cls.$super, data.mixins) : cc.errorID(3633, name); } this.datas = null; } } }; function appendProp(cls, name) { false; pushUnique(cls.__props__, name); } function defineProp(cls, className, propName, val, es6) { var defaultValue = val["default"]; false; Attr.setClassAttr(cls, propName, "default", defaultValue); appendProp(cls, propName); parseAttributes(cls, val, className, propName, false); var i; false, false; } function defineGetSet(cls, name, propName, val, es6) { var getter = val.get; var setter = val.set; var proto = cls.prototype; var d = Object.getOwnPropertyDescriptor(proto, propName); var setterUndefined = !d; if (getter) { false; parseAttributes(cls, val, name, propName, true); false, false; Attr.setClassAttr(cls, propName, "serializable", false); false; es6 || js.get(proto, propName, getter, setterUndefined, setterUndefined); false, false; } if (setter) { if (!es6) { false; js.set(proto, propName, setter, setterUndefined, setterUndefined); } false, false; } } function getDefault(defaultVal) { if ("function" === typeof defaultVal) { false; return defaultVal(); } return defaultVal; } function mixinWithInherited(dest, src, filter) { for (var prop in src) dest.hasOwnProperty(prop) || filter && !filter(prop) || Object.defineProperty(dest, prop, js.getPropertyDescriptor(src, prop)); } function doDefine(className, baseClass, mixins, options) { var shouldAddProtoCtor; var __ctor__ = options.__ctor__; var ctor = options.ctor; var __es6__ = options.__ES6__; var ctorToUse; false; var ctors; var fireClass; if (__es6__) { ctors = [ ctor ]; fireClass = ctor; } else { ctors = __ctor__ ? [ __ctor__ ] : _getAllCtors(baseClass, mixins, options); fireClass = _createCtor(ctors, baseClass, className, options); js.value(fireClass, "extend", (function(options) { options["extends"] = this; return CCClass(options); }), true); } js.value(fireClass, "__ctors__", ctors.length > 0 ? ctors : null, true); var prototype = fireClass.prototype; if (baseClass) { if (!__es6__) { js.extend(fireClass, baseClass); prototype = fireClass.prototype; } fireClass.$super = baseClass; false; } if (mixins) { for (var m = mixins.length - 1; m >= 0; m--) { var mixin = mixins[m]; mixinWithInherited(prototype, mixin.prototype); mixinWithInherited(fireClass, mixin, (function(prop) { return mixin.hasOwnProperty(prop) && true; })); CCClass._isCCClass(mixin) && mixinWithInherited(Attr.getClassAttrs(fireClass), Attr.getClassAttrs(mixin)); } prototype.constructor = fireClass; } __es6__ || (prototype.__initProps__ = compileProps); js.setClassName(className, fireClass); return fireClass; } function define(className, baseClass, mixins, options) { var Component = cc.Component; var frame = cc._RF.peek(); if (frame && js.isChildClassOf(baseClass, Component)) { if (js.isChildClassOf(frame.cls, Component)) { cc.errorID(3615); return null; } false; className = className || frame.script; } var cls = doDefine(className, baseClass, mixins, options); if (frame) if (js.isChildClassOf(baseClass, Component)) { var uuid = frame.uuid; if (uuid) { js._setClassId(uuid, cls); false; } frame.cls = cls; } else js.isChildClassOf(frame.cls, Component) || (frame.cls = cls); return cls; } function normalizeClassName_DEV(className) { var DefaultName = "CCClass"; if (className) { className = className.replace(/^[^$A-Za-z_]/, "_").replace(/[^0-9A-Za-z_$]/g, "_"); try { Function("function " + className + "(){}")(); return className; } catch (e) {} } return DefaultName; } function getNewValueTypeCodeJit(value) { var clsName = js.getClassName(value); var type = value.constructor; var res = "new " + clsName + "("; for (var i = 0; i < type.__props__.length; i++) { var prop = type.__props__[i]; var propVal = value[prop]; false; res += propVal; i < type.__props__.length - 1 && (res += ","); } return res + ")"; } function escapeForJS(s) { return JSON.stringify(s).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } function getInitPropsJit(attrs, propList) { var F = []; var func = ""; for (var i = 0; i < propList.length; i++) { var prop = propList[i]; var attrKey = prop + DELIMETER + "default"; if (attrKey in attrs) { var statement; statement = IDENTIFIER_RE.test(prop) ? "this." + prop + "=" : "this[" + escapeForJS(prop) + "]="; var expression; var def = attrs[attrKey]; if ("object" === typeof def && def) expression = def instanceof cc.ValueType ? getNewValueTypeCodeJit(def) : Array.isArray(def) ? "[]" : "{}"; else if ("function" === typeof def) { var index = F.length; F.push(def); expression = "F[" + index + "]()"; false; } else expression = "string" === typeof def ? escapeForJS(def) : def; statement = statement + expression + ";\n"; func += statement; } } var initProps; initProps = 0 === F.length ? Function(func) : Function("F", "return (function(){\n" + func + "})")(F); return initProps; } function getInitProps(attrs, propList) { var props = null; var simpleEnd = 0; var valueTypeEnd = 0; (function() { var simples = null; var valueTypes = null; var advanceds = null; for (var i = 0; i < propList.length; ++i) { var prop = propList[i]; var attrKey = prop + DELIMETER + "default"; if (attrKey in attrs) { var def = attrs[attrKey]; if ("object" === typeof def && def || "function" === typeof def) if (def instanceof cc.ValueType) { valueTypes || (valueTypes = []); valueTypes.push(prop, def); } else { advanceds || (advanceds = []); advanceds.push(prop, def); } else { simples || (simples = []); simples.push(prop, def); } } } simpleEnd = simples ? simples.length : 0; valueTypeEnd = simpleEnd + (valueTypes ? valueTypes.length : 0); var totalLength = valueTypeEnd + (advanceds ? advanceds.length : 0); props = new Array(totalLength); for (var _i = 0; _i < simpleEnd; ++_i) props[_i] = simples[_i]; for (var _i2 = simpleEnd; _i2 < valueTypeEnd; ++_i2) props[_i2] = valueTypes[_i2 - simpleEnd]; for (var _i3 = valueTypeEnd; _i3 < totalLength; ++_i3) props[_i3] = advanceds[_i3 - valueTypeEnd]; })(); return function() { var i = 0; for (;i < simpleEnd; i += 2) this[props[i]] = props[i + 1]; for (;i < valueTypeEnd; i += 2) this[props[i]] = props[i + 1].clone(); for (;i < props.length; i += 2) { var def = props[i + 1]; if (Array.isArray(def)) this[props[i]] = []; else { var value; if ("object" === typeof def) value = {}; else { false; value = def(); } this[props[i]] = value; } } }; } var IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/; function compileProps(actualClass) { var attrs = Attr.getClassAttrs(actualClass); var propList = actualClass.__props__; if (null === propList) { deferredInitializer.init(); propList = actualClass.__props__; } var initProps = getInitPropsJit(attrs, propList); actualClass.prototype.__initProps__ = initProps; initProps.call(this); } var _createCtor = function(ctors, baseClass, className, options) { var superCallBounded = baseClass && boundSuperCalls(baseClass, options, className); var ctorName = "CCClass"; var body = "return function " + ctorName + "(){\n"; superCallBounded && (body += "this._super=null;\n"); body += "this.__initProps__(" + ctorName + ");\n"; var ctorLen = ctors.length; if (ctorLen > 0) { var useTryCatch = false; useTryCatch && (body += "try{\n"); var SNIPPET = "].apply(this,arguments);\n"; if (1 === ctorLen) body += ctorName + ".__ctors__[0" + SNIPPET; else { body += "var cs=" + ctorName + ".__ctors__;\n"; for (var i = 0; i < ctorLen; i++) body += "cs[" + i + SNIPPET; } useTryCatch && (body += "}catch(e){\ncc._throw(e);\n}\n"); } body += "}"; return Function(body)(); }; function _validateCtor_DEV(ctor, baseClass, className, options) { var originCtor; false; !(ctor.length > 0) || className && className.startsWith("cc.") || cc.warnID(3617, className); return ctor; } function _getAllCtors(baseClass, mixins, options) { function getCtors(cls) { return CCClass._isCCClass(cls) ? cls.__ctors__ || [] : [ cls ]; } var ctors = []; var baseOrMixins = [ baseClass ].concat(mixins); for (var b = 0; b < baseOrMixins.length; b++) { var baseOrMixin = baseOrMixins[b]; if (baseOrMixin) { var baseCtors = getCtors(baseOrMixin); for (var c = 0; c < baseCtors.length; c++) pushUnique(ctors, baseCtors[c]); } } var ctor = options.ctor; ctor && ctors.push(ctor); return ctors; } var SuperCallReg = /xyz/.test((function() { xyz; })) ? /\b\._super\b/ : /.*/; var SuperCallRegStrict = /xyz/.test((function() { xyz; })) ? /this\._super\s*\(/ : /(NONE){99}/; function boundSuperCalls(baseClass, options, className) { var hasSuperCall = false; for (var funcName in options) { if (BUILTIN_ENTRIES.indexOf(funcName) >= 0) continue; var func = options[funcName]; if ("function" !== typeof func) continue; var pd = js.getPropertyDescriptor(baseClass.prototype, funcName); if (pd) { var superFunc = pd.value; if ("function" === typeof superFunc) { if (SuperCallReg.test(func)) { hasSuperCall = true; options[funcName] = (function(superFunc, func) { return function() { var tmp = this._super; this._super = superFunc; var ret = func.apply(this, arguments); this._super = tmp; return ret; }; })(superFunc, func); } continue; } } false; } return hasSuperCall; } function declareProperties(cls, className, properties, baseClass, mixins, es6) { cls.__props__ = []; baseClass && baseClass.__props__ && (cls.__props__ = baseClass.__props__.slice()); if (mixins) for (var m = 0; m < mixins.length; ++m) { var mixin = mixins[m]; mixin.__props__ && (cls.__props__ = cls.__props__.concat(mixin.__props__.filter((function(x) { return cls.__props__.indexOf(x) < 0; })))); } if (properties) { preprocess.preprocessAttrs(properties, className, cls, es6); for (var propName in properties) { var val = properties[propName]; "default" in val ? defineProp(cls, className, propName, val, es6) : defineGetSet(cls, className, propName, val, es6); } } var attrs = Attr.getClassAttrs(cls); cls.__values__ = cls.__props__.filter((function(prop) { return false !== attrs[prop + DELIMETER + "serializable"]; })); } function CCClass(options) { options = options || {}; var name = options.name; var base = options["extends"]; var mixins = options.mixins; var cls = define(name, base, mixins, options); name || (name = cc.js.getClassName(cls)); cls._sealed = true; base && (base._sealed = false); var properties = options.properties; if ("function" === typeof properties || base && null === base.__props__ || mixins && mixins.some((function(x) { return null === x.__props__; }))) { false; deferredInitializer.push({ cls: cls, props: properties, mixins: mixins }); cls.__props__ = cls.__values__ = null; } else declareProperties(cls, name, properties, base, options.mixins, options.__ES6__); var statics = options.statics; if (statics) { var staticPropName; false; for (staticPropName in statics) cls[staticPropName] = statics[staticPropName]; } for (var funcName in options) { if (BUILTIN_ENTRIES.indexOf(funcName) >= 0) continue; var func = options[funcName]; if (!preprocess.validateMethodWithProps(func, funcName, name, cls, base)) continue; js.value(cls.prototype, funcName, func, true, true); } var editor = options.editor; editor && cc.Component._registerEditorProps(cls, editor); return cls; } CCClass._isCCClass = function(constructor) { return constructor && constructor.hasOwnProperty("__ctors__"); }; CCClass._fastDefine = function(className, constructor, serializableFields) { js.setClassName(className, constructor); var props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields); var attrs = Attr.getClassAttrs(constructor); for (var i = 0; i < props.length; i++) { var key = props[i]; attrs[key + DELIMETER + "visible"] = false; attrs[key + DELIMETER + "default"] = serializableFields[key]; } }; CCClass.Attr = Attr; CCClass.attr = Attr.attr; CCClass.getInheritanceChain = function(klass) { var chain = []; for (;;) { klass = js.getSuper(klass); if (!klass) break; klass !== Object && chain.push(klass); } return chain; }; var PrimitiveTypes = { Integer: "Number", Float: "Number", Boolean: "Boolean", String: "String" }; var onAfterProps_ET = []; function parseAttributes(cls, attributes, className, propName, usedInGetter) { var ERR_Type = ""; var attrs = null; var propNamePrefix = ""; function initAttrs() { propNamePrefix = propName + DELIMETER; return attrs = Attr.getClassAttrs(cls); } false, false; var type = attributes.type; if (type) { var primitiveType = PrimitiveTypes[type]; if (primitiveType) { (attrs || initAttrs())[propNamePrefix + "type"] = type; (false, false) && !attributes._short && onAfterProps_ET.push(Attr.getTypeChecker_ET(primitiveType, "cc." + type)); } else if ("Object" === type) false; else if (type === Attr.ScriptUuid) { (attrs || initAttrs())[propNamePrefix + "type"] = "Script"; attrs[propNamePrefix + "ctor"] = cc.ScriptAsset; } else if ("object" === typeof type) if (Enum.isEnum(type)) { (attrs || initAttrs())[propNamePrefix + "type"] = "Enum"; attrs[propNamePrefix + "enumList"] = Enum.getList(type); } else false; else if ("function" === typeof type) { (attrs || initAttrs())[propNamePrefix + "type"] = "Object"; attrs[propNamePrefix + "ctor"] = type; (false, false) && !attributes._short && onAfterProps_ET.push(Attr.getObjTypeChecker_ET(type)); } else false; } function parseSimpleAttr(attrName, expectType) { if (attrName in attributes) { var val = attributes[attrName]; typeof val === expectType && ((attrs || initAttrs())[propNamePrefix + attrName] = val); } } if (attributes.editorOnly) { false; (attrs || initAttrs())[propNamePrefix + "editorOnly"] = true; } false; if (false === attributes.serializable) { false; (attrs || initAttrs())[propNamePrefix + "serializable"] = false; } parseSimpleAttr("formerlySerializedAs", "string"); false; var visible; var startsWithUS; false; var range = attributes.range; if (range) if (Array.isArray(range)) if (range.length >= 2) { (attrs || initAttrs())[propNamePrefix + "min"] = range[0]; attrs[propNamePrefix + "max"] = range[1]; range.length > 2 && (attrs[propNamePrefix + "step"] = range[2]); } else false; else false; parseSimpleAttr("min", "number"); parseSimpleAttr("max", "number"); parseSimpleAttr("step", "number"); parseSimpleAttr("userData", "object"); } cc.Class = CCClass; module.exports = { isArray: function isArray(defaultVal) { defaultVal = getDefault(defaultVal); return Array.isArray(defaultVal); }, fastDefine: CCClass._fastDefine, getNewValueTypeCode: (true, getNewValueTypeCodeJit), IDENTIFIER_RE: IDENTIFIER_RE, escapeForJS: escapeForJS, getDefault: getDefault }; false; }), { "./CCEnum": 131, "./attribute": 141, "./js": 150, "./preprocess-class": 151, "./requiring-frame": 152, "./utils": 153 } ], 130: [ (function(require, module, exports) { "use strict"; require("./CCClass"); var Preprocess = require("./preprocess-class"); var js = require("./js"); var isPlainEmptyObj_DEV = false; var CACHE_KEY = "__ccclassCache__"; function fNOP(ctor) { return ctor; } function getSubDict(obj, key) { return obj[key] || (obj[key] = {}); } function checkCtorArgument(decorate) { return function(target) { if ("function" === typeof target) return decorate(target); return function(ctor) { return decorate(ctor, target); }; }; } function _checkNormalArgument(validator_DEV, decorate, decoratorName) { return function(target) { false; return function(ctor) { return decorate(ctor, target); }; }; } var checkCompArgument = _checkNormalArgument.bind(null, false); function _argumentChecker(type) { return _checkNormalArgument.bind(null, false); } var checkStringArgument = _argumentChecker("string"); var checkNumberArgument = _argumentChecker("number"); function getClassCache(ctor, decoratorName) { false; return getSubDict(ctor, CACHE_KEY); } function getDefaultFromInitializer(initializer) { var value; try { value = initializer(); } catch (e) { return initializer; } return "object" !== typeof value || null === value ? value : initializer; } function extractActualDefaultValues(ctor) { var dummyObj; try { dummyObj = new ctor(); } catch (e) { false; return {}; } return dummyObj; } function genProperty(ctor, properties, propName, options, desc, cache) { var fullOptions; var isGetset = desc && (desc.get || desc.set); options && (fullOptions = Preprocess.getFullFormOfProperty(options, isGetset)); var existsProperty = properties[propName]; var prop = js.mixin(existsProperty || {}, fullOptions || options || {}); if (isGetset) { var errorProps; false; desc.get && (prop.get = desc.get); desc.set && (prop.set = desc.set); } else { false; var defaultValue = void 0; var isDefaultValueSpecified = false; if (desc) { if (desc.initializer) { defaultValue = getDefaultFromInitializer(desc.initializer); isDefaultValueSpecified = true; } } else { var actualDefaultValues = cache["default"] || (cache["default"] = extractActualDefaultValues(ctor)); if (actualDefaultValues.hasOwnProperty(propName)) { defaultValue = actualDefaultValues[propName]; isDefaultValueSpecified = true; } } false, false; prop["default"] = defaultValue; } properties[propName] = prop; } var ccclass = checkCtorArgument((function(ctor, name) { var base = js.getSuper(ctor); base === Object && (base = null); var proto = { name: name, extends: base, ctor: ctor, __ES6__: true }; var cache = ctor[CACHE_KEY]; if (cache) { var decoratedProto = cache.proto; decoratedProto && js.mixin(proto, decoratedProto); ctor[CACHE_KEY] = void 0; } var res = cc.Class(proto); var propNames; var i; var prop; var desc; var func; false; return res; })); function property(ctorProtoOrOptions, propName, desc) { var options = null; function normalized(ctorProto, propName, desc) { var cache = getClassCache(ctorProto.constructor); if (cache) { var ccclassProto = getSubDict(cache, "proto"); var properties = getSubDict(ccclassProto, "properties"); genProperty(ctorProto.constructor, properties, propName, options, desc, cache); } } if ("undefined" === typeof propName) { options = ctorProtoOrOptions; return normalized; } normalized(ctorProtoOrOptions, propName, desc); } function createEditorDecorator(argCheckFunc, editorPropName, staticValue) { return argCheckFunc((function(ctor, decoratedValue) { var cache = getClassCache(ctor, editorPropName); if (cache) { var value = void 0 !== staticValue ? staticValue : decoratedValue; var proto = getSubDict(cache, "proto"); getSubDict(proto, "editor")[editorPropName] = value; } }), editorPropName); } function createDummyDecorator(argCheckFunc) { return argCheckFunc(fNOP); } var executeInEditMode = createDummyDecorator(checkCtorArgument, "executeInEditMode", true); var requireComponent = createEditorDecorator(checkCompArgument, "requireComponent"); var menu = createDummyDecorator(checkStringArgument, "menu"); var executionOrder = createEditorDecorator(checkNumberArgument, "executionOrder"); var disallowMultiple = createDummyDecorator(checkCtorArgument, "disallowMultiple"); var playOnFocus = createDummyDecorator(checkCtorArgument, "playOnFocus", true); var inspector = createDummyDecorator(checkStringArgument, "inspector"); var icon = createDummyDecorator(checkStringArgument, "icon"); var help = createDummyDecorator(checkStringArgument, "help"); function mixins() { var mixins = []; for (var i = 0; i < arguments.length; i++) mixins[i] = arguments[i]; return function(ctor) { var cache = getClassCache(ctor, "mixins"); cache && (getSubDict(cache, "proto").mixins = mixins); }; } cc._decorator = module.exports = { ccclass: ccclass, property: property, executeInEditMode: executeInEditMode, requireComponent: requireComponent, menu: menu, executionOrder: executionOrder, disallowMultiple: disallowMultiple, playOnFocus: playOnFocus, inspector: inspector, icon: icon, help: help, mixins: mixins }; }), { "./CCClass": 129, "./js": 150, "./preprocess-class": 151, "./utils": 153 } ], 131: [ (function(require, module, exports) { "use strict"; var js = require("./js"); function Enum(obj) { if ("__enums__" in obj) return obj; js.value(obj, "__enums__", null, true); var lastIndex = -1; var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var val = obj[key]; if (-1 === val) { val = ++lastIndex; obj[key] = val; } else if ("number" === typeof val) lastIndex = val; else if ("string" === typeof val && Number.isInteger(parseFloat(key))) continue; var reverseKey = "" + val; if (key !== reverseKey) { if ((false, false) && reverseKey in obj && obj[reverseKey] !== key) { cc.errorID(7100, reverseKey); continue; } js.value(obj, reverseKey, key); } } return obj; } Enum.isEnum = function(enumType) { return enumType && enumType.hasOwnProperty("__enums__"); }; Enum.getList = function(enumDef) { if (enumDef.__enums__) return enumDef.__enums__; var enums = enumDef.__enums__ = []; for (var name in enumDef) { var value = enumDef[name]; Number.isInteger(value) && enums.push({ name: name, value: value }); } enums.sort((function(a, b) { return a.value - b.value; })); return enums; }; var _TestEnum; false; module.exports = cc.Enum = Enum; }), { "./js": 150 } ], 132: [ (function(require, module, exports) { "use strict"; var eventManager = require("../event-manager"); var inputManager = require("./CCInputManager"); var PORTRAIT = 0; var LANDSCAPE_LEFT = -90; var PORTRAIT_UPSIDE_DOWN = 180; var LANDSCAPE_RIGHT = 90; var _didAccelerateFun; cc.Acceleration = function(x, y, z, timestamp) { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.timestamp = timestamp || 0; }; inputManager.setAccelerometerEnabled = function(isEnable) { var _t = this; if (_t._accelEnabled === isEnable) return; _t._accelEnabled = isEnable; var scheduler = cc.director.getScheduler(); scheduler.enableForTarget(_t); if (_t._accelEnabled) { _t._registerAccelerometerEvent(); _t._accelCurTime = 0; scheduler.scheduleUpdate(_t); } else { _t._unregisterAccelerometerEvent(); _t._accelCurTime = 0; scheduler.unscheduleUpdate(_t); } false, false; }; inputManager.setAccelerometerInterval = function(interval) { if (this._accelInterval !== interval) { this._accelInterval = interval; false, false; } }; inputManager._registerKeyboardEvent = function() { cc.game.canvas.addEventListener("keydown", (function(e) { eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, true)); e.stopPropagation(); e.preventDefault(); }), false); cc.game.canvas.addEventListener("keyup", (function(e) { eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, false)); e.stopPropagation(); e.preventDefault(); }), false); }; inputManager._registerAccelerometerEvent = function() { var w = window, _t = this; _t._acceleration = new cc.Acceleration(); _t._accelDeviceEvent = w.DeviceMotionEvent || w.DeviceOrientationEvent; cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ && (_t._accelDeviceEvent = window.DeviceOrientationEvent); var _deviceEventType = _t._accelDeviceEvent === w.DeviceMotionEvent ? "devicemotion" : "deviceorientation"; var ua = navigator.userAgent; (/Android/.test(ua) || /Adr/.test(ua) && cc.sys.browserType === cc.BROWSER_TYPE_UC) && (_t._minus = -1); _didAccelerateFun = _t.didAccelerate.bind(_t); w.addEventListener(_deviceEventType, _didAccelerateFun, false); }; inputManager._unregisterAccelerometerEvent = function() { var w = window, _t = this; var _deviceEventType = _t._accelDeviceEvent === w.DeviceMotionEvent ? "devicemotion" : "deviceorientation"; _didAccelerateFun && w.removeEventListener(_deviceEventType, _didAccelerateFun, false); }; inputManager.didAccelerate = function(eventData) { var _t = this, w = window; if (!_t._accelEnabled) return; var mAcceleration = _t._acceleration; var x, y, z; if (_t._accelDeviceEvent === window.DeviceMotionEvent) { var eventAcceleration = eventData["accelerationIncludingGravity"]; x = _t._accelMinus * eventAcceleration.x * .1; y = _t._accelMinus * eventAcceleration.y * .1; z = .1 * eventAcceleration.z; } else { x = eventData["gamma"] / 90 * .981; y = -eventData["beta"] / 90 * .981; z = eventData["alpha"] / 90 * .981; } if (cc.view._isRotated) { var tmp = x; x = -y; y = tmp; } mAcceleration.x = x; mAcceleration.y = y; mAcceleration.z = z; mAcceleration.timestamp = eventData.timeStamp || Date.now(); var tmpX = mAcceleration.x; if (w.orientation === LANDSCAPE_RIGHT) { mAcceleration.x = -mAcceleration.y; mAcceleration.y = tmpX; } else if (w.orientation === LANDSCAPE_LEFT) { mAcceleration.x = mAcceleration.y; mAcceleration.y = -tmpX; } else if (w.orientation === PORTRAIT_UPSIDE_DOWN) { mAcceleration.x = -mAcceleration.x; mAcceleration.y = -mAcceleration.y; } if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ) { mAcceleration.x = -mAcceleration.x; mAcceleration.y = -mAcceleration.y; } }; }), { "../event-manager": 117, "./CCInputManager": 133 } ], 133: [ (function(require, module, exports) { "use strict"; var macro = require("./CCMacro"); var sys = require("./CCSys"); var eventManager = require("../event-manager"); var _vec2 = cc.v2(); var inputManager = { _mousePressed: false, _isRegisterEvent: false, _preTouchPoint: cc.v2(0, 0), _prevMousePoint: cc.v2(0, 0), _preTouchPool: [], _preTouchPoolPointer: 0, _touches: [], _maxTouches: 10, _touchesIntegerDict: {}, _indexBitsUsed: 0, _touchesCache: {}, _touchCount: 0, _accelEnabled: false, _accelInterval: .2, _accelMinus: 1, _accelCurTime: 0, _acceleration: null, _accelDeviceEvent: null, _canvasBoundingRect: { left: 0, top: 0, adjustedLeft: 0, adjustedTop: 0, width: 0, height: 0 }, _getUnUsedIndex: function _getUnUsedIndex() { var now = cc.sys.now(); var timeout = macro.TOUCH_TIMEOUT; var temp = this._indexBitsUsed; var unused = -1; var locTouches = this._touches; var locTouchesIntDict = this._touchesIntegerDict; var locTouchesCache = this._touchesCache; for (var i = 0; i < this._maxTouches; i++) { if (1 & temp) { var ccTouch = locTouches[i]; if (ccTouch && now - ccTouch._lastModified > timeout) { var touchID = ccTouch.getID(); delete locTouchesIntDict[touchID]; delete locTouchesCache[touchID]; this._touchCount--; if (-1 === unused) { unused = i; this._indexBitsUsed |= 1 << i; } else this._indexBitsUsed &= ~(1 << i); } } else if (-1 === unused) { unused = i; this._indexBitsUsed |= 1 << i; } temp >>= 1; } return unused; }, _glView: null, _updateCanvasBoundingRect: function _updateCanvasBoundingRect() { var element = cc.game.canvas; var canvasBoundingRect = this._canvasBoundingRect; var docElem = document.documentElement; var leftOffset = window.pageXOffset - docElem.clientLeft; var topOffset = window.pageYOffset - docElem.clientTop; if (element.getBoundingClientRect) { var box = element.getBoundingClientRect(); canvasBoundingRect.left = box.left + leftOffset; canvasBoundingRect.top = box.top + topOffset; canvasBoundingRect.width = box.width; canvasBoundingRect.height = box.height; } else if (element instanceof HTMLCanvasElement) { canvasBoundingRect.left = leftOffset; canvasBoundingRect.top = topOffset; canvasBoundingRect.width = element.width; canvasBoundingRect.height = element.height; } else { canvasBoundingRect.left = leftOffset; canvasBoundingRect.top = topOffset; canvasBoundingRect.width = parseInt(element.style.width); canvasBoundingRect.height = parseInt(element.style.height); } }, handleTouchesBegin: function handleTouchesBegin(touches) { var now = sys.now(); var selTouch, index, touchID, handleTouches = []; var locTouches = this._touches; var locTouchesIntDict = this._touchesIntegerDict; var locTouchesCache = this._touchesCache; for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = locTouchesIntDict[touchID]; if (void 0 === index) { var unusedIndex = this._getUnUsedIndex(); if (-1 === unusedIndex) { cc.logID(2300, unusedIndex); continue; } var ccTouch = new cc.Touch(selTouch._point.x, selTouch._point.y, touchID); ccTouch._setPrevPoint(selTouch._prevPoint); ccTouch._lastModified = now; locTouches[unusedIndex] = ccTouch; locTouchesIntDict[touchID] = unusedIndex; locTouchesCache[touchID] = ccTouch; this._touchCount++; handleTouches.push(ccTouch); } } if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.BEGAN; eventManager.dispatchEvent(touchEvent); } }, handleTouchesMove: function handleTouchesMove(touches) { var now = sys.now(); var selTouch, index, touchID, handleTouches = []; var locTouches = this._touches; var locTouchesIntDict = this._touchesIntegerDict; for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = locTouchesIntDict[touchID]; if (void 0 === index) continue; var ccTouch = locTouches[index]; if (ccTouch) { ccTouch._setPoint(selTouch._point); ccTouch._setPrevPoint(selTouch._prevPoint); ccTouch._lastModified = now; handleTouches.push(ccTouch); } } if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.MOVED; eventManager.dispatchEvent(touchEvent); } }, handleTouchesEnd: function handleTouchesEnd(touches) { var handleTouches = this.getSetOfTouchesEndOrCancel(touches); if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.ENDED; eventManager.dispatchEvent(touchEvent); } this._preTouchPool.length = 0; }, handleTouchesCancel: function handleTouchesCancel(touches) { var handleTouches = this.getSetOfTouchesEndOrCancel(touches); if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.CANCELED; eventManager.dispatchEvent(touchEvent); } this._preTouchPool.length = 0; }, getSetOfTouchesEndOrCancel: function getSetOfTouchesEndOrCancel(touches) { var selTouch, index, touchID, handleTouches = []; var locTouches = this._touches; var locTouchesIntDict = this._touchesIntegerDict; var locTouchesCache = this._touchesCache; for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = locTouchesIntDict[touchID]; if (void 0 === index) continue; var ccTouch = locTouches[index]; if (ccTouch) { ccTouch._setPoint(selTouch._point); ccTouch._setPrevPoint(selTouch._prevPoint); handleTouches.push(ccTouch); delete locTouchesIntDict[touchID]; delete locTouchesCache[touchID]; this._touchCount--; this._indexBitsUsed &= ~(1 << index); } } return handleTouches; }, getGlobalTouchCount: function getGlobalTouchCount() { return this._touchCount; }, getGlobalTouches: function getGlobalTouches() { return this._touchesCache; }, getPreTouch: function getPreTouch(touch) { var preTouch = null; var locPreTouchPool = this._preTouchPool; var id = touch.getID(); for (var i = locPreTouchPool.length - 1; i >= 0; i--) if (locPreTouchPool[i].getID() === id) { preTouch = locPreTouchPool[i]; break; } preTouch || (preTouch = touch); return preTouch; }, setPreTouch: function setPreTouch(touch) { var find = false; var locPreTouchPool = this._preTouchPool; var id = touch.getID(); for (var i = locPreTouchPool.length - 1; i >= 0; i--) if (locPreTouchPool[i].getID() === id) { locPreTouchPool[i] = touch; find = true; break; } if (!find) if (locPreTouchPool.length <= 50) locPreTouchPool.push(touch); else { locPreTouchPool[this._preTouchPoolPointer] = touch; this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50; } }, getTouchByXY: function getTouchByXY(tx, ty, pos) { var locPreTouch = this._preTouchPoint; var location = this._glView.convertToLocationInView(tx, ty, pos); var touch = new cc.Touch(location.x, location.y, 0); touch._setPrevPoint(locPreTouch.x, locPreTouch.y); locPreTouch.x = location.x; locPreTouch.y = location.y; return touch; }, getMouseEvent: function getMouseEvent(location, pos, eventType) { var locPreMouse = this._prevMousePoint; var mouseEvent = new cc.Event.EventMouse(eventType); mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y); locPreMouse.x = location.x; locPreMouse.y = location.y; this._glView._convertMouseToLocationInView(locPreMouse, pos); mouseEvent.setLocation(locPreMouse.x, locPreMouse.y); return mouseEvent; }, getPointByEvent: function getPointByEvent(event, pos) { cc.sys.browserType !== cc.sys.BROWSER_TYPE_QQ && cc.sys.browserType !== cc.sys.BROWSER_TYPE_UC && cc.sys.browserType !== cc.sys.BROWSER_TYPE_SAFARI || this._updateCanvasBoundingRect(); if (null != event.pageX) return { x: event.pageX, y: event.pageY }; pos.left -= document.body.scrollLeft; pos.top -= document.body.scrollTop; return { x: event.clientX, y: event.clientY }; }, getTouchesByEvent: function getTouchesByEvent(event, pos) { var touchArr = [], locView = this._glView; var touch_event, touch, preLocation; var locPreTouch = this._preTouchPoint; var length = event.changedTouches.length; for (var i = 0; i < length; i++) { touch_event = event.changedTouches[i]; if (touch_event) { var location = void 0; location = sys.BROWSER_TYPE_FIREFOX === sys.browserType ? locView.convertToLocationInView(touch_event.pageX, touch_event.pageY, pos, _vec2) : locView.convertToLocationInView(touch_event.clientX, touch_event.clientY, pos, _vec2); if (null != touch_event.identifier) { touch = new cc.Touch(location.x, location.y, touch_event.identifier); preLocation = this.getPreTouch(touch).getLocation(); touch._setPrevPoint(preLocation.x, preLocation.y); this.setPreTouch(touch); } else { touch = new cc.Touch(location.x, location.y); touch._setPrevPoint(locPreTouch.x, locPreTouch.y); } locPreTouch.x = location.x; locPreTouch.y = location.y; touchArr.push(touch); } } return touchArr; }, registerSystemEvent: function registerSystemEvent(element) { if (this._isRegisterEvent) return; this._glView = cc.view; var selfPointer = this; var canvasBoundingRect = this._canvasBoundingRect; window.addEventListener("resize", this._updateCanvasBoundingRect.bind(this)); var prohibition = sys.isMobile; var supportMouse = "mouse" in sys.capabilities; var supportTouches = "touches" in sys.capabilities; if (supportMouse) { if (!prohibition) { window.addEventListener("mousedown", (function() { selfPointer._mousePressed = true; }), false); window.addEventListener("mouseup", (function(event) { if (!selfPointer._mousePressed) return; selfPointer._mousePressed = false; var location = selfPointer.getPointByEvent(event, canvasBoundingRect); if (!cc.rect(canvasBoundingRect.left, canvasBoundingRect.top, canvasBoundingRect.width, canvasBoundingRect.height).contains(location)) { selfPointer.handleTouchesEnd([ selfPointer.getTouchByXY(location.x, location.y, canvasBoundingRect) ]); var mouseEvent = selfPointer.getMouseEvent(location, canvasBoundingRect, cc.Event.EventMouse.UP); mouseEvent.setButton(event.button); eventManager.dispatchEvent(mouseEvent); } }), false); } var EventMouse = cc.Event.EventMouse; var _mouseEventsOnElement = [ !prohibition && [ "mousedown", EventMouse.DOWN, function(event, mouseEvent, location, canvasBoundingRect) { selfPointer._mousePressed = true; selfPointer.handleTouchesBegin([ selfPointer.getTouchByXY(location.x, location.y, canvasBoundingRect) ]); element.focus(); } ], !prohibition && [ "mouseup", EventMouse.UP, function(event, mouseEvent, location, canvasBoundingRect) { selfPointer._mousePressed = false; selfPointer.handleTouchesEnd([ selfPointer.getTouchByXY(location.x, location.y, canvasBoundingRect) ]); } ], !prohibition && [ "mousemove", EventMouse.MOVE, function(event, mouseEvent, location, canvasBoundingRect) { selfPointer.handleTouchesMove([ selfPointer.getTouchByXY(location.x, location.y, canvasBoundingRect) ]); selfPointer._mousePressed || mouseEvent.setButton(null); } ], [ "mousewheel", EventMouse.SCROLL, function(event, mouseEvent) { mouseEvent.setScrollData(0, event.wheelDelta); } ], [ "DOMMouseScroll", EventMouse.SCROLL, function(event, mouseEvent) { mouseEvent.setScrollData(0, -120 * event.detail); } ] ]; for (var i = 0; i < _mouseEventsOnElement.length; ++i) { var entry = _mouseEventsOnElement[i]; entry && (function() { var name = entry[0]; var type = entry[1]; var handler = entry[2]; element.addEventListener(name, (function(event) { var location = selfPointer.getPointByEvent(event, canvasBoundingRect); var mouseEvent = selfPointer.getMouseEvent(location, canvasBoundingRect, type); mouseEvent.setButton(event.button); handler(event, mouseEvent, location, canvasBoundingRect); eventManager.dispatchEvent(mouseEvent); event.stopPropagation(); event.preventDefault(); }), false); })(); } } if (window.navigator.msPointerEnabled) { var _pointerEventsMap = { MSPointerDown: selfPointer.handleTouchesBegin, MSPointerMove: selfPointer.handleTouchesMove, MSPointerUp: selfPointer.handleTouchesEnd, MSPointerCancel: selfPointer.handleTouchesCancel }; var _loop = function _loop(eventName) { var touchEvent = _pointerEventsMap[eventName]; element.addEventListener(eventName, (function(event) { var documentElement = document.documentElement; canvasBoundingRect.adjustedLeft = canvasBoundingRect.left - documentElement.scrollLeft; canvasBoundingRect.adjustedTop = canvasBoundingRect.top - documentElement.scrollTop; touchEvent.call(selfPointer, [ selfPointer.getTouchByXY(event.clientX, event.clientY, canvasBoundingRect) ]); event.stopPropagation(); }), false); }; for (var eventName in _pointerEventsMap) _loop(eventName); } if (supportTouches) { var _touchEventsMap = { touchstart: function touchstart(touchesToHandle) { selfPointer.handleTouchesBegin(touchesToHandle); element.focus(); }, touchmove: function touchmove(touchesToHandle) { selfPointer.handleTouchesMove(touchesToHandle); }, touchend: function touchend(touchesToHandle) { selfPointer.handleTouchesEnd(touchesToHandle); }, touchcancel: function touchcancel(touchesToHandle) { selfPointer.handleTouchesCancel(touchesToHandle); } }; var registerTouchEvent = function registerTouchEvent(eventName) { var handler = _touchEventsMap[eventName]; element.addEventListener(eventName, (function(event) { if (!event.changedTouches) return; var body = document.body; canvasBoundingRect.adjustedLeft = canvasBoundingRect.left - (body.scrollLeft || window.scrollX || 0); canvasBoundingRect.adjustedTop = canvasBoundingRect.top - (body.scrollTop || window.scrollY || 0); handler(selfPointer.getTouchesByEvent(event, canvasBoundingRect)); event.stopPropagation(); event.preventDefault(); }), false); }; for (var _eventName in _touchEventsMap) registerTouchEvent(_eventName); } this._registerKeyboardEvent(); this._isRegisterEvent = true; }, _registerKeyboardEvent: function _registerKeyboardEvent() {}, _registerAccelerometerEvent: function _registerAccelerometerEvent() {}, update: function update(dt) { if (this._accelCurTime > this._accelInterval) { this._accelCurTime -= this._accelInterval; eventManager.dispatchEvent(new cc.Event.EventAcceleration(this._acceleration)); } this._accelCurTime += dt; } }; module.exports = cc.internal.inputManager = inputManager; }), { "../event-manager": 117, "./CCMacro": 134, "./CCSys": 138 } ], 134: [ (function(require, module, exports) { "use strict"; cc.macro = { RAD: Math.PI / 180, DEG: 180 / Math.PI, REPEAT_FOREVER: Number.MAX_VALUE - 1, FLT_EPSILON: 1.192092896e-7, MIN_ZINDEX: -Math.pow(2, 15), MAX_ZINDEX: Math.pow(2, 15) - 1, ONE: 1, ZERO: 0, SRC_ALPHA: 770, SRC_ALPHA_SATURATE: 776, SRC_COLOR: 768, DST_ALPHA: 772, DST_COLOR: 774, ONE_MINUS_SRC_ALPHA: 771, ONE_MINUS_SRC_COLOR: 769, ONE_MINUS_DST_ALPHA: 773, ONE_MINUS_DST_COLOR: 775, ONE_MINUS_CONSTANT_ALPHA: 32772, ONE_MINUS_CONSTANT_COLOR: 32770, ORIENTATION_PORTRAIT: 1, ORIENTATION_LANDSCAPE: 2, ORIENTATION_AUTO: 3, DENSITYDPI_DEVICE: "device-dpi", DENSITYDPI_HIGH: "high-dpi", DENSITYDPI_MEDIUM: "medium-dpi", DENSITYDPI_LOW: "low-dpi", FIX_ARTIFACTS_BY_STRECHING_TEXEL_TMX: true, DIRECTOR_STATS_POSITION: cc.v2(0, 0), ENABLE_STACKABLE_ACTIONS: true, TOUCH_TIMEOUT: 5e3, BATCH_VERTEX_COUNT: 2e4, ENABLE_TILEDMAP_CULLING: true, ENABLE_TRANSPARENT_CANVAS: false, ENABLE_WEBGL_ANTIALIAS: false, ENABLE_CULLING: false, CLEANUP_IMAGE_CACHE: false, SHOW_MESH_WIREFRAME: false, SHOW_MESH_NORMAL: false, ENABLE_MULTI_TOUCH: true, ALLOW_IMAGE_BITMAP: !cc.sys.isMobile, ENABLE_NATIVE_TTF_RENDERER: false }; Object.defineProperty(cc.macro, "ROTATE_ACTION_CCW", { set: function set(value) { cc.RotateTo && cc.RotateBy && (cc.RotateTo._reverse = cc.RotateBy._reverse = value); } }); var SUPPORT_TEXTURE_FORMATS = [ ".pkm", ".pvr", ".webp", ".jpg", ".jpeg", ".bmp", ".png" ]; cc.macro.SUPPORT_TEXTURE_FORMATS = SUPPORT_TEXTURE_FORMATS; cc.macro.KEY = { none: 0, back: 6, menu: 18, backspace: 8, tab: 9, enter: 13, shift: 16, ctrl: 17, alt: 18, pause: 19, capslock: 20, escape: 27, space: 32, pageup: 33, pagedown: 34, end: 35, home: 36, left: 37, up: 38, right: 39, down: 40, select: 41, insert: 45, Delete: 46, 0: 48, 1: 49, 2: 50, 3: 51, 4: 52, 5: 53, 6: 54, 7: 55, 8: 56, 9: 57, a: 65, b: 66, c: 67, d: 68, e: 69, f: 70, g: 71, h: 72, i: 73, j: 74, k: 75, l: 76, m: 77, n: 78, o: 79, p: 80, q: 81, r: 82, s: 83, t: 84, u: 85, v: 86, w: 87, x: 88, y: 89, z: 90, num0: 96, num1: 97, num2: 98, num3: 99, num4: 100, num5: 101, num6: 102, num7: 103, num8: 104, num9: 105, "*": 106, "+": 107, "-": 109, numdel: 110, "/": 111, f1: 112, f2: 113, f3: 114, f4: 115, f5: 116, f6: 117, f7: 118, f8: 119, f9: 120, f10: 121, f11: 122, f12: 123, numlock: 144, scrolllock: 145, ";": 186, semicolon: 186, equal: 187, "=": 187, ",": 188, comma: 188, dash: 189, ".": 190, period: 190, forwardslash: 191, grave: 192, "[": 219, openbracket: 219, backslash: 220, "]": 221, closebracket: 221, quote: 222, dpadLeft: 1e3, dpadRight: 1001, dpadUp: 1003, dpadDown: 1004, dpadCenter: 1005 }; cc.macro.ImageFormat = cc.Enum({ JPG: 0, PNG: 1, TIFF: 2, WEBP: 3, PVR: 4, ETC: 5, S3TC: 6, ATITC: 7, TGA: 8, RAWDATA: 9, UNKNOWN: 10 }); cc.macro.BlendFactor = cc.Enum({ ONE: 1, ZERO: 0, SRC_ALPHA: 770, SRC_COLOR: 768, DST_ALPHA: 772, DST_COLOR: 774, ONE_MINUS_SRC_ALPHA: 771, ONE_MINUS_SRC_COLOR: 769, ONE_MINUS_DST_ALPHA: 773, ONE_MINUS_DST_COLOR: 775 }); cc.macro.TextAlignment = cc.Enum({ LEFT: 0, CENTER: 1, RIGHT: 2 }); cc.macro.VerticalTextAlignment = cc.Enum({ TOP: 0, CENTER: 1, BOTTOM: 2 }); module.exports = cc.macro; }), {} ], 135: [ (function(require, module, exports) { "use strict"; var js = require("./js"); var CCClass = require("./CCClass"); var Destroyed = 1; var RealDestroyed = 2; var ToDestroy = 4; var DontSave = 8; var EditorOnly = 16; var Dirty = 32; var DontDestroy = 64; var Destroying = 128; var Deactivating = 256; var LockedInEditor = 512; var HideInHierarchy = 1024; var IsOnEnableCalled = 2048; var IsEditorOnEnableCalled = 4096; var IsPreloadStarted = 8192; var IsOnLoadCalled = 16384; var IsOnLoadStarted = 32768; var IsStartCalled = 65536; var IsRotationLocked = 1 << 17; var IsScaleLocked = 1 << 18; var IsAnchorLocked = 1 << 19; var IsSizeLocked = 1 << 20; var IsPositionLocked = 1 << 21; var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating | IsPreloadStarted | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | IsOnEnableCalled | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked); function CCObject() { this._name = ""; this._objFlags = 0; } CCClass.fastDefine("cc.Object", CCObject, { _name: "", _objFlags: 0 }); js.value(CCObject, "Flags", { Destroyed: Destroyed, DontSave: DontSave, EditorOnly: EditorOnly, Dirty: Dirty, DontDestroy: DontDestroy, PersistentMask: PersistentMask, Destroying: Destroying, Deactivating: Deactivating, LockedInEditor: LockedInEditor, HideInHierarchy: HideInHierarchy, IsPreloadStarted: IsPreloadStarted, IsOnLoadStarted: IsOnLoadStarted, IsOnLoadCalled: IsOnLoadCalled, IsOnEnableCalled: IsOnEnableCalled, IsStartCalled: IsStartCalled, IsEditorOnEnableCalled: IsEditorOnEnableCalled, IsPositionLocked: IsPositionLocked, IsRotationLocked: IsRotationLocked, IsScaleLocked: IsScaleLocked, IsAnchorLocked: IsAnchorLocked, IsSizeLocked: IsSizeLocked }); var objectsToDestroy = []; function deferredDestroy() { var deleteCount = objectsToDestroy.length; for (var i = 0; i < deleteCount; ++i) { var obj = objectsToDestroy[i]; obj._objFlags & Destroyed || obj._destroyImmediate(); } deleteCount === objectsToDestroy.length ? objectsToDestroy.length = 0 : objectsToDestroy.splice(0, deleteCount); false; } js.value(CCObject, "_deferredDestroy", deferredDestroy); false; var prototype = CCObject.prototype; js.getset(prototype, "name", (function() { return this._name; }), (function(value) { this._name = value; }), true); js.get(prototype, "isValid", (function() { return !(this._objFlags & Destroyed); }), true); false, false; var deferredDestroyTimer = null; prototype.destroy = function() { if (this._objFlags & Destroyed) { cc.warnID(5e3); return false; } if (this._objFlags & ToDestroy) return false; this._objFlags |= ToDestroy; objectsToDestroy.push(this); false; return true; }; false, false; function compileDestruct(obj, ctor) { var shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; var idToSkip = shouldSkipId ? "_id" : null; var key, propsToReset = {}; for (key in obj) if (obj.hasOwnProperty(key)) { if (key === idToSkip) continue; switch (typeof obj[key]) { case "string": propsToReset[key] = ""; break; case "object": case "function": propsToReset[key] = null; } } if (cc.Class._isCCClass(ctor)) { var attrs = cc.Class.Attr.getClassAttrs(ctor); var propList = ctor.__props__; for (var i = 0; i < propList.length; i++) { key = propList[i]; var attrKey = key + cc.Class.Attr.DELIMETER + "default"; if (attrKey in attrs) { if (shouldSkipId && "_id" === key) continue; switch (typeof attrs[attrKey]) { case "string": propsToReset[key] = ""; break; case "object": case "function": propsToReset[key] = null; break; case "undefined": propsToReset[key] = void 0; } } } } true; var func = ""; for (key in propsToReset) { var statement; statement = CCClass.IDENTIFIER_RE.test(key) ? "o." + key + "=" : "o[" + CCClass.escapeForJS(key) + "]="; var val = propsToReset[key]; "" === val && (val = '""'); func += statement + val + ";\n"; } return Function("o", func); } prototype._destruct = function() { var ctor = this.constructor; var destruct = ctor.__destruct__; if (!destruct) { destruct = compileDestruct(this, ctor); js.value(ctor, "__destruct__", destruct, true); } destruct(this); }; prototype._onPreDestroy = null; prototype._destroyImmediate = function() { if (this._objFlags & Destroyed) { cc.errorID(5e3); return; } this._onPreDestroy && this._onPreDestroy(); true; this._destruct(); this._objFlags |= Destroyed; }; false; prototype._deserialize = null; cc.isValid = function(value, strictMode) { return "object" === typeof value ? !!value && !(value._objFlags & (strictMode ? Destroyed | ToDestroy : Destroyed)) : "undefined" !== typeof value; }; false, false; cc.Object = module.exports = CCObject; }), { "./CCClass": 129, "./js": 150 } ], 136: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); cc.SAXParser = function() { if (true, window.DOMParser) { this._isSupportDOMParser = true; this._parser = new DOMParser(); } else { this._isSupportDOMParser = false; this._parser = null; } }; cc.SAXParser.prototype = { constructor: cc.SAXParser, parse: function parse(xmlTxt) { return this._parseXML(xmlTxt); }, _parseXML: function _parseXML(textxml) { var xmlDoc; if (this._isSupportDOMParser) xmlDoc = this._parser.parseFromString(textxml, "text/xml"); else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(textxml); } return xmlDoc; } }; cc.PlistParser = function() { cc.SAXParser.call(this); }; js.extend(cc.PlistParser, cc.SAXParser); js.mixin(cc.PlistParser.prototype, { parse: function parse(xmlTxt) { var xmlDoc = this._parseXML(xmlTxt); var plist = xmlDoc.documentElement; if ("plist" !== plist.tagName) { cc.warnID(5100); return {}; } var node = null; for (var i = 0, len = plist.childNodes.length; i < len; i++) { node = plist.childNodes[i]; if (1 === node.nodeType) break; } xmlDoc = null; return this._parseNode(node); }, _parseNode: function _parseNode(node) { var data = null, tagName = node.tagName; if ("dict" === tagName) data = this._parseDict(node); else if ("array" === tagName) data = this._parseArray(node); else if ("string" === tagName) if (1 === node.childNodes.length) data = node.firstChild.nodeValue; else { data = ""; for (var i = 0; i < node.childNodes.length; i++) data += node.childNodes[i].nodeValue; } else "false" === tagName ? data = false : "true" === tagName ? data = true : "real" === tagName ? data = parseFloat(node.firstChild.nodeValue) : "integer" === tagName && (data = parseInt(node.firstChild.nodeValue, 10)); return data; }, _parseArray: function _parseArray(node) { var data = []; for (var i = 0, len = node.childNodes.length; i < len; i++) { var child = node.childNodes[i]; if (1 !== child.nodeType) continue; data.push(this._parseNode(child)); } return data; }, _parseDict: function _parseDict(node) { var data = {}; var key = null; for (var i = 0, len = node.childNodes.length; i < len; i++) { var child = node.childNodes[i]; if (1 !== child.nodeType) continue; "key" === child.tagName ? key = child.firstChild.nodeValue : data[key] = this._parseNode(child); } return data; } }); cc.saxParser = new cc.SAXParser(); cc.plistParser = new cc.PlistParser(); module.exports = { saxParser: cc.saxParser, plistParser: cc.plistParser }; }), { "../platform/js": 150 } ], 137: [ (function(require, module, exports) { "use strict"; cc.screen = { _supportsFullScreen: false, _onfullscreenchange: null, _onfullscreenerror: null, _preOnFullScreenChange: null, _preOnFullScreenError: null, _preOnTouch: null, _touchEvent: "", _fn: null, _fnMap: [ [ "requestFullscreen", "exitFullscreen", "fullscreenchange", "fullscreenEnabled", "fullscreenElement", "fullscreenerror" ], [ "requestFullScreen", "exitFullScreen", "fullScreenchange", "fullScreenEnabled", "fullScreenElement", "fullscreenerror" ], [ "webkitRequestFullScreen", "webkitCancelFullScreen", "webkitfullscreenchange", "webkitIsFullScreen", "webkitCurrentFullScreenElement", "webkitfullscreenerror" ], [ "mozRequestFullScreen", "mozCancelFullScreen", "mozfullscreenchange", "mozFullScreen", "mozFullScreenElement", "mozfullscreenerror" ], [ "msRequestFullscreen", "msExitFullscreen", "MSFullscreenChange", "msFullscreenEnabled", "msFullscreenElement", "msfullscreenerror" ] ], init: function init() { this._fn = {}; var i, l, val, map = this._fnMap, valL; for (i = 0, l = map.length; i < l; i++) { val = map[i]; if (val && "undefined" !== typeof document[val[1]]) { for (i = 0, valL = val.length; i < valL; i++) this._fn[map[0][i]] = val[i]; break; } } this._supportsFullScreen = void 0 !== this._fn.requestFullscreen; this._touchEvent = "ontouchend" in window ? "touchend" : "mousedown"; }, fullScreen: function fullScreen() { return !!this._supportsFullScreen && !!(document[this._fn.fullscreenElement] || document[this._fn.webkitFullscreenElement] || document[this._fn.mozFullScreenElement]); }, requestFullScreen: function requestFullScreen(element, onFullScreenChange, onFullScreenError) { if (element && "video" === element.tagName.toLowerCase()) { if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser && element.readyState > 0) { element.webkitEnterFullscreen && element.webkitEnterFullscreen(); return; } element.setAttribute("x5-video-player-fullscreen", "true"); } if (!this._supportsFullScreen) return; element = element || document.documentElement; if (onFullScreenChange) { var eventName = this._fn.fullscreenchange; this._onfullscreenchange && document.removeEventListener(eventName, this._onfullscreenchange); this._onfullscreenchange = onFullScreenChange; document.addEventListener(eventName, onFullScreenChange, false); } if (onFullScreenError) { var _eventName = this._fn.fullscreenerror; this._onfullscreenerror && document.removeEventListener(_eventName, this._onfullscreenerror); this._onfullscreenerror = onFullScreenError; document.addEventListener(_eventName, onFullScreenError, { once: true }); } var requestPromise = element[this._fn.requestFullscreen](); "undefined" === typeof document[this._fn.fullscreenerror] && window.Promise && requestPromise instanceof Promise && requestPromise["catch"]((function(err) {})); }, exitFullScreen: function exitFullScreen(element) { if (element && "video" === element.tagName.toLowerCase()) { if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser) { element.webkitExitFullscreen && element.webkitExitFullscreen(); return; } element.setAttribute("x5-video-player-fullscreen", "false"); } return !this._supportsFullScreen || document[this._fn.exitFullscreen](); }, autoFullScreen: function autoFullScreen(element, onFullScreenChange) { element = element || document.body; this._ensureFullScreen(element, onFullScreenChange); this.requestFullScreen(element, onFullScreenChange); }, disableAutoFullScreen: function disableAutoFullScreen(element) { var touchTarget = cc.game.canvas || element; var touchEventName = this._touchEvent; if (this._preOnTouch) { touchTarget.removeEventListener(touchEventName, this._preOnTouch); this._preOnTouch = null; } }, _ensureFullScreen: function _ensureFullScreen(element, onFullScreenChange) { var self = this; var touchTarget = cc.game.canvas || element; var fullScreenErrorEventName = this._fn.fullscreenerror; var touchEventName = this._touchEvent; function onFullScreenError() { self._preOnFullScreenError = null; function onTouch() { self._preOnTouch = null; self.requestFullScreen(element, onFullScreenChange); } self._preOnTouch && touchTarget.removeEventListener(touchEventName, self._preOnTouch); self._preOnTouch = onTouch; touchTarget.addEventListener(touchEventName, self._preOnTouch, { once: true }); } this._preOnFullScreenError && element.removeEventListener(fullScreenErrorEventName, this._preOnFullScreenError); this._preOnFullScreenError = onFullScreenError; element.addEventListener(fullScreenErrorEventName, onFullScreenError, { once: true }); } }; cc.screen.init(); }), {} ], 138: [ (function(require, module, exports) { "use strict"; var settingPlatform; true; settingPlatform = window._CCSettings ? _CCSettings.platform : void 0; var isVivoGame = "qgame" === settingPlatform; var isOppoGame = "quickgame" === settingPlatform; var isHuaweiGame = "huawei" === settingPlatform; var isJKWGame = "jkw-game" === settingPlatform; var isQttGame = "qtt-game" === settingPlatform; var isLinkSure = "link-sure" === settingPlatform; var _global = "undefined" === typeof window ? global : window; function initSys() { cc.sys = {}; var sys = cc.sys; sys.LANGUAGE_ENGLISH = "en"; sys.LANGUAGE_CHINESE = "zh"; sys.LANGUAGE_FRENCH = "fr"; sys.LANGUAGE_ITALIAN = "it"; sys.LANGUAGE_GERMAN = "de"; sys.LANGUAGE_SPANISH = "es"; sys.LANGUAGE_DUTCH = "du"; sys.LANGUAGE_RUSSIAN = "ru"; sys.LANGUAGE_KOREAN = "ko"; sys.LANGUAGE_JAPANESE = "ja"; sys.LANGUAGE_HUNGARIAN = "hu"; sys.LANGUAGE_PORTUGUESE = "pt"; sys.LANGUAGE_ARABIC = "ar"; sys.LANGUAGE_NORWEGIAN = "no"; sys.LANGUAGE_POLISH = "pl"; sys.LANGUAGE_TURKISH = "tr"; sys.LANGUAGE_UKRAINIAN = "uk"; sys.LANGUAGE_ROMANIAN = "ro"; sys.LANGUAGE_BULGARIAN = "bg"; sys.LANGUAGE_UNKNOWN = "unknown"; sys.OS_IOS = "iOS"; sys.OS_ANDROID = "Android"; sys.OS_WINDOWS = "Windows"; sys.OS_MARMALADE = "Marmalade"; sys.OS_LINUX = "Linux"; sys.OS_BADA = "Bada"; sys.OS_BLACKBERRY = "Blackberry"; sys.OS_OSX = "OS X"; sys.OS_WP8 = "WP8"; sys.OS_WINRT = "WINRT"; sys.OS_UNKNOWN = "Unknown"; sys.UNKNOWN = -1; sys.WIN32 = 0; sys.LINUX = 1; sys.MACOS = 2; sys.ANDROID = 3; sys.IPHONE = 4; sys.IPAD = 5; sys.BLACKBERRY = 6; sys.NACL = 7; sys.EMSCRIPTEN = 8; sys.TIZEN = 9; sys.WINRT = 10; sys.WP8 = 11; sys.MOBILE_BROWSER = 100; sys.DESKTOP_BROWSER = 101; sys.EDITOR_PAGE = 102; sys.EDITOR_CORE = 103; sys.WECHAT_GAME = 104; sys.QQ_PLAY = 105; sys.FB_PLAYABLE_ADS = 106; sys.BAIDU_GAME = 107; sys.VIVO_GAME = 108; sys.OPPO_GAME = 109; sys.HUAWEI_GAME = 110; sys.XIAOMI_GAME = 111; sys.JKW_GAME = 112; sys.ALIPAY_GAME = 113; sys.WECHAT_GAME_SUB = 114; sys.BAIDU_GAME_SUB = 115; sys.QTT_GAME = 116; sys.BYTEDANCE_GAME = 117; sys.BYTEDANCE_GAME_SUB = 118; sys.LINKSURE = 119; sys.TAOBAO = 120; sys.BROWSER_TYPE_WECHAT = "wechat"; sys.BROWSER_TYPE_ANDROID = "androidbrowser"; sys.BROWSER_TYPE_IE = "ie"; sys.BROWSER_TYPE_EDGE = "edge"; sys.BROWSER_TYPE_QQ = "qqbrowser"; sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser"; sys.BROWSER_TYPE_UC = "ucbrowser"; sys.BROWSER_TYPE_UCBS = "ucbs"; sys.BROWSER_TYPE_360 = "360browser"; sys.BROWSER_TYPE_BAIDU_APP = "baiduboxapp"; sys.BROWSER_TYPE_BAIDU = "baidubrowser"; sys.BROWSER_TYPE_MAXTHON = "maxthon"; sys.BROWSER_TYPE_OPERA = "opera"; sys.BROWSER_TYPE_OUPENG = "oupeng"; sys.BROWSER_TYPE_MIUI = "miuibrowser"; sys.BROWSER_TYPE_FIREFOX = "firefox"; sys.BROWSER_TYPE_SAFARI = "safari"; sys.BROWSER_TYPE_CHROME = "chrome"; sys.BROWSER_TYPE_LIEBAO = "liebao"; sys.BROWSER_TYPE_QZONE = "qzone"; sys.BROWSER_TYPE_SOUGOU = "sogou"; sys.BROWSER_TYPE_HUAWEI = "huawei"; sys.BROWSER_TYPE_UNKNOWN = "unknown"; sys.isNative = false; sys.isBrowser = "object" === typeof window && "object" === typeof document && true; sys.glExtension = function(name) { return !!cc.renderer.device.ext(name); }; sys.getMaxJointMatrixSize = function() { if (!sys._maxJointMatrixSize) { var JOINT_MATRICES_SIZE = 50; var LEFT_UNIFORM_SIZE = 10; var gl = cc.game._renderContext; var maxUniforms = Math.floor(gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS) / 4) - LEFT_UNIFORM_SIZE; sys._maxJointMatrixSize = maxUniforms < JOINT_MATRICES_SIZE ? 0 : JOINT_MATRICES_SIZE; } return sys._maxJointMatrixSize; }; sys.getSafeAreaRect = function() { var visibleSize = cc.view.getVisibleSize(); return cc.rect(0, 0, visibleSize.width, visibleSize.height); }; if (_global.__globalAdapter && _global.__globalAdapter.adaptSys) _global.__globalAdapter.adaptSys(sys); else { false; var platform; var languageCode; var w; var h; var ratio; var capabilities; false, false; var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement; var ua = nav.userAgent.toLowerCase(); false; sys.isMobile = /mobile|android|iphone|ipad/.test(ua); "undefined" !== typeof FbPlayableAd ? sys.platform = sys.FB_PLAYABLE_ADS : sys.platform = sys.isMobile ? sys.MOBILE_BROWSER : sys.DESKTOP_BROWSER; var currLanguage = nav.language; currLanguage = currLanguage || nav.browserLanguage; sys.languageCode = currLanguage.toLowerCase(); currLanguage = currLanguage ? currLanguage.split("-")[0] : sys.LANGUAGE_ENGLISH; sys.language = currLanguage; var isAndroid = false, iOS = false, osVersion = "", osMainVersion = 0; var uaResult = /android\s*(\d+(?:\.\d+)*)/i.exec(ua) || /android\s*(\d+(?:\.\d+)*)/i.exec(nav.platform); if (uaResult) { isAndroid = true; osVersion = uaResult[1] || ""; osMainVersion = parseInt(osVersion) || 0; } uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua); if (uaResult) { iOS = true; osVersion = uaResult[2] || ""; osMainVersion = parseInt(osVersion) || 0; } else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || "MacIntel" === nav.platform && nav.maxTouchPoints && nav.maxTouchPoints > 1) { iOS = true; osVersion = ""; osMainVersion = 0; } var osName = sys.OS_UNKNOWN; -1 !== nav.appVersion.indexOf("Win") ? osName = sys.OS_WINDOWS : iOS ? osName = sys.OS_IOS : -1 !== nav.appVersion.indexOf("Mac") ? osName = sys.OS_OSX : -1 !== nav.appVersion.indexOf("X11") && -1 === nav.appVersion.indexOf("Linux") ? osName = sys.OS_UNIX : isAndroid ? osName = sys.OS_ANDROID : -1 === nav.appVersion.indexOf("Linux") && -1 === ua.indexOf("ubuntu") || (osName = sys.OS_LINUX); sys.os = osName; sys.osVersion = osVersion; sys.osMainVersion = osMainVersion; sys.browserType = sys.BROWSER_TYPE_UNKNOWN; (function() { var typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i; var typeReg2 = /qq|ucbrowser|ubrowser|edge|HuaweiBrowser/i; var typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i; var browserTypes = typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua); var browserType = browserTypes ? browserTypes[0].toLowerCase() : sys.BROWSER_TYPE_UNKNOWN; "safari" === browserType && isAndroid ? browserType = sys.BROWSER_TYPE_ANDROID : "qq" === browserType && ua.match(/android.*applewebkit/i) && (browserType = sys.BROWSER_TYPE_ANDROID); var typeMap = { micromessenger: sys.BROWSER_TYPE_WECHAT, trident: sys.BROWSER_TYPE_IE, edge: sys.BROWSER_TYPE_EDGE, "360 aphone": sys.BROWSER_TYPE_360, mxbrowser: sys.BROWSER_TYPE_MAXTHON, "opr/": sys.BROWSER_TYPE_OPERA, ubrowser: sys.BROWSER_TYPE_UC, huaweibrowser: sys.BROWSER_TYPE_HUAWEI }; "qqbrowser" !== browserType && "mqqbrowser" !== browserType || ua.match(/wechat|micromessenger/i) && (browserType = sys.BROWSER_TYPE_WECHAT); sys.browserType = typeMap[browserType] || browserType; })(); sys.browserVersion = ""; (function() { var versionReg1 = /(mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|uc|ucbs|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui(?:.hybrid)?)(mobile)?(browser)?\/?([\d.]+)/i; var versionReg2 = /(qq|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i; var tmp = ua.match(versionReg1); tmp || (tmp = ua.match(versionReg2)); sys.browserVersion = tmp ? tmp[4] : ""; })(); var w = window.innerWidth || document.documentElement.clientWidth; var h = window.innerHeight || document.documentElement.clientHeight; var ratio = window.devicePixelRatio || 1; sys.windowPixelResolution = { width: ratio * w, height: ratio * h }; sys._checkWebGLRenderMode = function() { if (cc.game.renderType !== cc.game.RENDER_TYPE_WEBGL) throw new Error("This feature supports WebGL render mode only."); }; var _tmpCanvas1 = document.createElement("canvas"); var create3DContext = function create3DContext(canvas, opt_attribs, opt_contextType) { if (!opt_contextType) return create3DContext(canvas, opt_attribs, "webgl") || create3DContext(canvas, opt_attribs, "experimental-webgl") || create3DContext(canvas, opt_attribs, "webkit-3d") || create3DContext(canvas, opt_attribs, "moz-webgl") || null; try { return canvas.getContext(opt_contextType, opt_attribs); } catch (e) { return null; } }; try { var localStorage = sys.localStorage = win.localStorage; localStorage.setItem("storage", ""); localStorage.removeItem("storage"); localStorage = null; } catch (e) { var warn = function warn() { cc.warnID(5200); }; sys.localStorage = { getItem: warn, setItem: warn, removeItem: warn, clear: warn }; } var _supportWebp = _tmpCanvas1.toDataURL("image/webp").startsWith("data:image/webp"); var _supportCanvas = !!_tmpCanvas1.getContext("2d"); var _supportWebGL = false; false; win.WebGLRenderingContext && (_supportWebGL = true); var capabilities = sys.capabilities = { canvas: _supportCanvas, opengl: _supportWebGL, webp: _supportWebp, imageBitmap: false }; if ("undefined" !== typeof createImageBitmap && "undefined" !== typeof Blob) { _tmpCanvas1.width = _tmpCanvas1.height = 2; createImageBitmap(_tmpCanvas1, {}).then((function(imageBitmap) { capabilities.imageBitmap = true; imageBitmap.close && imageBitmap.close(); }))["catch"]((function(err) {})); } (void 0 !== docEle["ontouchstart"] || void 0 !== doc["ontouchstart"] || nav.msPointerEnabled) && (capabilities["touches"] = true); void 0 !== docEle["onmouseup"] && (capabilities["mouse"] = true); void 0 !== docEle["onkeyup"] && (capabilities["keyboard"] = true); (win.DeviceMotionEvent || win.DeviceOrientationEvent) && (capabilities["accelerometer"] = true); var __audioSupport; (function() { var DEBUG = false; var version = sys.browserVersion; var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); __audioSupport = { ONLY_ONE: false, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false }; sys.os === sys.OS_IOS && (__audioSupport.USE_LOADER_EVENT = "loadedmetadata"); if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) { __audioSupport.DELAY_CREATE_CTX = true; __audioSupport.USE_LOADER_EVENT = "canplay"; } sys.os === sys.OS_ANDROID && sys.browserType === sys.BROWSER_TYPE_UC && (__audioSupport.ONE_SOURCE = true); DEBUG && setTimeout((function() { cc.log("browse type: " + sys.browserType); cc.log("browse version: " + version); cc.log("MULTI_CHANNEL: " + __audioSupport.MULTI_CHANNEL); cc.log("WEB_AUDIO: " + __audioSupport.WEB_AUDIO); cc.log("AUTOPLAY: " + __audioSupport.AUTOPLAY); }), 0); })(); try { if (__audioSupport.WEB_AUDIO) { __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); __audioSupport.DELAY_CREATE_CTX && setTimeout((function() { __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }), 0); } } catch (error) { __audioSupport.WEB_AUDIO = false; cc.logID(5201); } var formatSupport = []; (function() { var audio = document.createElement("audio"); if (audio.canPlayType) { var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); ogg && formatSupport.push(".ogg"); var mp3 = audio.canPlayType("audio/mpeg"); mp3 && formatSupport.push(".mp3"); var wav = audio.canPlayType('audio/wav; codecs="1"'); wav && formatSupport.push(".wav"); var mp4 = audio.canPlayType("audio/mp4"); mp4 && formatSupport.push(".mp4"); var m4a = audio.canPlayType("audio/x-m4a"); m4a && formatSupport.push(".m4a"); } })(); __audioSupport.format = formatSupport; sys.__audioSupport = __audioSupport; } sys.NetworkType = { NONE: 0, LAN: 1, WWAN: 2 }; sys.getNetworkType = function() { return sys.NetworkType.LAN; }; sys.getBatteryLevel = function() { return 1; }; sys.garbageCollect = function() {}; sys.restartVM = function() {}; sys.isObjectValid = function(obj) { if (obj) return true; return false; }; sys.dump = function() { var self = this; var str = ""; str += "isMobile : " + self.isMobile + "\r\n"; str += "language : " + self.language + "\r\n"; str += "browserType : " + self.browserType + "\r\n"; str += "browserVersion : " + self.browserVersion + "\r\n"; str += "capabilities : " + JSON.stringify(self.capabilities) + "\r\n"; str += "os : " + self.os + "\r\n"; str += "osVersion : " + self.osVersion + "\r\n"; str += "platform : " + self.platform + "\r\n"; str += "Using " + (cc.game.renderType === cc.game.RENDER_TYPE_WEBGL ? "WEBGL" : "CANVAS") + " renderer.\r\n"; cc.log(str); }; sys.openURL = function(url) { false, false; window.open(url); }; sys.now = function() { return Date.now ? Date.now() : +new Date(); }; return sys; } var sys = cc && cc.sys ? cc.sys : initSys(); module.exports = sys; }), {} ], 139: [ (function(require, module, exports) { "use strict"; var EventTarget = require("../event/event-target"); var js = require("../platform/js"); var renderer = require("../renderer"); require("../platform/CCClass"); var __BrowserGetter = { init: function init() { this.html = document.getElementsByTagName("html")[0]; }, availWidth: function availWidth(frame) { return frame && frame !== this.html ? frame.clientWidth : window.innerWidth; }, availHeight: function availHeight(frame) { return frame && frame !== this.html ? frame.clientHeight : window.innerHeight; }, meta: { width: "device-width" }, adaptationType: cc.sys.browserType }; cc.sys.os === cc.sys.OS_IOS && (__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI); switch (__BrowserGetter.adaptationType) { case cc.sys.BROWSER_TYPE_SAFARI: case cc.sys.BROWSER_TYPE_SOUGOU: case cc.sys.BROWSER_TYPE_UC: __BrowserGetter.meta["minimal-ui"] = "true"; __BrowserGetter.availWidth = function(frame) { return frame.clientWidth; }; __BrowserGetter.availHeight = function(frame) { return frame.clientHeight; }; } var _scissorRect = null; var View = function View() { EventTarget.call(this); var _t = this, _strategyer = cc.ContainerStrategy, _strategy = cc.ContentStrategy; __BrowserGetter.init(this); _t._frameSize = cc.size(0, 0); _t._designResolutionSize = cc.size(0, 0); _t._originalDesignResolutionSize = cc.size(0, 0); _t._scaleX = 1; _t._scaleY = 1; _t._viewportRect = cc.rect(0, 0, 0, 0); _t._visibleRect = cc.rect(0, 0, 0, 0); _t._autoFullScreen = false; _t._devicePixelRatio = 1; false; _t._maxPixelRatio = 2; _t._retinaEnabled = false; _t._resizeCallback = null; _t._resizing = false; _t._resizeWithBrowserSize = false; _t._orientationChanging = true; _t._isRotated = false; _t._orientation = cc.macro.ORIENTATION_AUTO; _t._isAdjustViewport = true; _t._antiAliasEnabled = false; _t._resolutionPolicy = null; _t._rpExactFit = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT); _t._rpShowAll = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL); _t._rpNoBorder = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER); _t._rpFixedHeight = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT); _t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); cc.game.once(cc.game.EVENT_ENGINE_INITED, this.init, this); }; cc.js.extend(View, EventTarget); cc.js.mixin(View.prototype, { init: function init() { this._initFrameSize(); var w = cc.game.canvas.width, h = cc.game.canvas.height; this._designResolutionSize.width = w; this._designResolutionSize.height = h; this._originalDesignResolutionSize.width = w; this._originalDesignResolutionSize.height = h; this._viewportRect.width = w; this._viewportRect.height = h; this._visibleRect.width = w; this._visibleRect.height = h; cc.winSize.width = this._visibleRect.width; cc.winSize.height = this._visibleRect.height; cc.visibleRect && cc.visibleRect.init(this._visibleRect); }, _resizeEvent: function _resizeEvent(forceOrEvent) { var view; view = this.setDesignResolutionSize ? this : cc.view; var sys = cc.sys; if (sys.browserType === sys.BROWSER_TYPE_UC && sys.os === sys.OS_IOS) { setTimeout((function() { view._resizeEvent(forceOrEvent); }), 0); return; } var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height, prevRotated = view._isRotated; if (cc.sys.isMobile) { var containerStyle = cc.game.container.style, margin = containerStyle.margin; containerStyle.margin = "0"; containerStyle.display = "none"; view._initFrameSize(); containerStyle.margin = margin; containerStyle.display = "block"; } else view._initFrameSize(); if (true !== forceOrEvent && view._isRotated === prevRotated && view._frameSize.width === prevFrameW && view._frameSize.height === prevFrameH) return; var width = view._originalDesignResolutionSize.width; var height = view._originalDesignResolutionSize.height; view._resizing = true; width > 0 && view.setDesignResolutionSize(width, height, view._resolutionPolicy); view._resizing = false; view.emit("canvas-resize"); view._resizeCallback && view._resizeCallback.call(); }, _orientationChange: function _orientationChange() { cc.view._orientationChanging = true; cc.view._resizeEvent(); cc.sys.browserType === cc.sys.BROWSER_TYPE_SAFARI && cc.sys.isMobile && setTimeout((function() { window.innerHeight > window.innerWidth && window.scrollTo(0, 1); }), 500); }, _resize: function _resize() { cc.view._resizeEvent(false); }, resizeWithBrowserSize: function resizeWithBrowserSize(enabled) { if (enabled) { if (!this._resizeWithBrowserSize) { this._resizeWithBrowserSize = true; window.addEventListener("resize", this._resize); window.addEventListener("orientationchange", this._orientationChange); } } else if (this._resizeWithBrowserSize) { this._resizeWithBrowserSize = false; window.removeEventListener("resize", this._resize); window.removeEventListener("orientationchange", this._orientationChange); } }, setResizeCallback: function setResizeCallback(callback) { false; "function" !== typeof callback && null != callback || (this._resizeCallback = callback); }, setOrientation: function setOrientation(orientation) { orientation &= cc.macro.ORIENTATION_AUTO; if (orientation && this._orientation !== orientation) { this._orientation = orientation; var designWidth = this._originalDesignResolutionSize.width; var designHeight = this._originalDesignResolutionSize.height; this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); } }, _initFrameSize: function _initFrameSize() { var locFrameSize = this._frameSize; var w = __BrowserGetter.availWidth(cc.game.frame); var h = __BrowserGetter.availHeight(cc.game.frame); var isLandscape = w >= h; if ((false, !cc.sys.isMobile) || isLandscape && this._orientation & cc.macro.ORIENTATION_LANDSCAPE || !isLandscape && this._orientation & cc.macro.ORIENTATION_PORTRAIT) { locFrameSize.width = w; locFrameSize.height = h; cc.game.container.style["-webkit-transform"] = "rotate(0deg)"; cc.game.container.style.transform = "rotate(0deg)"; this._isRotated = false; } else { locFrameSize.width = h; locFrameSize.height = w; cc.game.container.style["-webkit-transform"] = "rotate(90deg)"; cc.game.container.style.transform = "rotate(90deg)"; cc.game.container.style["-webkit-transform-origin"] = "0px 0px 0px"; cc.game.container.style.transformOrigin = "0px 0px 0px"; this._isRotated = true; } this._orientationChanging && setTimeout((function() { cc.view._orientationChanging = false; }), 1e3); }, _setViewportMeta: function _setViewportMeta(metas, overwrite) { var vp = document.getElementById("cocosMetaElement"); vp && overwrite && document.head.removeChild(vp); var elems = document.getElementsByName("viewport"), currentVP = elems ? elems[0] : null, content, key, pattern; content = currentVP ? currentVP.content : ""; vp = vp || document.createElement("meta"); vp.id = "cocosMetaElement"; vp.name = "viewport"; vp.content = ""; for (key in metas) if (-1 == content.indexOf(key)) content += "," + key + "=" + metas[key]; else if (overwrite) { pattern = new RegExp(key + "s*=s*[^,]+"); content = content.replace(pattern, key + "=" + metas[key]); } /^,/.test(content) && (content = content.substr(1)); vp.content = content; currentVP && (currentVP.content = content); document.head.appendChild(vp); }, _adjustViewportMeta: function _adjustViewportMeta() { if (this._isAdjustViewport && true) { this._setViewportMeta(__BrowserGetter.meta, false); this._isAdjustViewport = false; } }, adjustViewportMeta: function adjustViewportMeta(enabled) { this._isAdjustViewport = enabled; }, enableRetina: function enableRetina(enabled) { this._retinaEnabled = !!enabled; }, isRetinaEnabled: function isRetinaEnabled() { return this._retinaEnabled; }, enableAntiAlias: function enableAntiAlias(enabled) { cc.warnID(9200); if (this._antiAliasEnabled === enabled) return; this._antiAliasEnabled = enabled; if (cc.game.renderType === cc.game.RENDER_TYPE_WEBGL) { var cache = cc.assetManager.assets; cache.forEach((function(asset) { if (asset instanceof cc.Texture2D) { var Filter = cc.Texture2D.Filter; enabled ? asset.setFilters(Filter.LINEAR, Filter.LINEAR) : asset.setFilters(Filter.NEAREST, Filter.NEAREST); } })); } else if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { var ctx = cc.game.canvas.getContext("2d"); ctx.imageSmoothingEnabled = enabled; ctx.mozImageSmoothingEnabled = enabled; } }, isAntiAliasEnabled: function isAntiAliasEnabled() { return this._antiAliasEnabled; }, enableAutoFullScreen: function enableAutoFullScreen(enabled) { if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile) { this._autoFullScreen = true; cc.screen.autoFullScreen(cc.game.frame); } else { this._autoFullScreen = false; cc.screen.disableAutoFullScreen(cc.game.frame); } }, isAutoFullScreenEnabled: function isAutoFullScreenEnabled() { return this._autoFullScreen; }, setCanvasSize: function setCanvasSize(width, height) { var canvas = cc.game.canvas; var container = cc.game.container; canvas.width = width * this._devicePixelRatio; canvas.height = height * this._devicePixelRatio; canvas.style.width = width + "px"; canvas.style.height = height + "px"; container.style.width = width + "px"; container.style.height = height + "px"; this._resizeEvent(); }, getCanvasSize: function getCanvasSize() { return cc.size(cc.game.canvas.width, cc.game.canvas.height); }, getFrameSize: function getFrameSize() { return cc.size(this._frameSize.width, this._frameSize.height); }, setFrameSize: function setFrameSize(width, height) { this._frameSize.width = width; this._frameSize.height = height; cc.game.frame.style.width = width + "px"; cc.game.frame.style.height = height + "px"; this._resizeEvent(true); }, getVisibleSize: function getVisibleSize() { return cc.size(this._visibleRect.width, this._visibleRect.height); }, getVisibleSizeInPixel: function getVisibleSizeInPixel() { return cc.size(this._visibleRect.width * this._scaleX, this._visibleRect.height * this._scaleY); }, getVisibleOrigin: function getVisibleOrigin() { return cc.v2(this._visibleRect.x, this._visibleRect.y); }, getVisibleOriginInPixel: function getVisibleOriginInPixel() { return cc.v2(this._visibleRect.x * this._scaleX, this._visibleRect.y * this._scaleY); }, getResolutionPolicy: function getResolutionPolicy() { return this._resolutionPolicy; }, setResolutionPolicy: function setResolutionPolicy(resolutionPolicy) { var _t = this; if (resolutionPolicy instanceof cc.ResolutionPolicy) _t._resolutionPolicy = resolutionPolicy; else { var _locPolicy = cc.ResolutionPolicy; resolutionPolicy === _locPolicy.EXACT_FIT && (_t._resolutionPolicy = _t._rpExactFit); resolutionPolicy === _locPolicy.SHOW_ALL && (_t._resolutionPolicy = _t._rpShowAll); resolutionPolicy === _locPolicy.NO_BORDER && (_t._resolutionPolicy = _t._rpNoBorder); resolutionPolicy === _locPolicy.FIXED_HEIGHT && (_t._resolutionPolicy = _t._rpFixedHeight); resolutionPolicy === _locPolicy.FIXED_WIDTH && (_t._resolutionPolicy = _t._rpFixedWidth); } }, setDesignResolutionSize: function setDesignResolutionSize(width, height, resolutionPolicy) { if (!(width > 0 && height > 0)) { cc.errorID(2200); return; } this.setResolutionPolicy(resolutionPolicy); var policy = this._resolutionPolicy; policy && policy.preApply(this); cc.sys.isMobile && this._adjustViewportMeta(); this._orientationChanging = true; this._resizing || this._initFrameSize(); if (!policy) { cc.logID(2201); return; } this._originalDesignResolutionSize.width = this._designResolutionSize.width = width; this._originalDesignResolutionSize.height = this._designResolutionSize.height = height; var result = policy.apply(this, this._designResolutionSize); if (result.scale && 2 === result.scale.length) { this._scaleX = result.scale[0]; this._scaleY = result.scale[1]; } if (result.viewport) { var vp = this._viewportRect, vb = this._visibleRect, rv = result.viewport; vp.x = rv.x; vp.y = rv.y; vp.width = rv.width; vp.height = rv.height; vb.x = 0; vb.y = 0; vb.width = rv.width / this._scaleX; vb.height = rv.height / this._scaleY; } policy.postApply(this); cc.winSize.width = this._visibleRect.width; cc.winSize.height = this._visibleRect.height; cc.visibleRect && cc.visibleRect.init(this._visibleRect); renderer.updateCameraViewport(); cc.internal.inputManager._updateCanvasBoundingRect(); this.emit("design-resolution-changed"); }, getDesignResolutionSize: function getDesignResolutionSize() { return cc.size(this._designResolutionSize.width, this._designResolutionSize.height); }, setRealPixelResolution: function setRealPixelResolution(width, height, resolutionPolicy) { true, true; this._setViewportMeta({ width: width }, true); document.documentElement.style.width = width + "px"; document.body.style.width = width + "px"; document.body.style.left = "0px"; document.body.style.top = "0px"; this.setDesignResolutionSize(width, height, resolutionPolicy); }, setViewportInPoints: function setViewportInPoints(x, y, w, h) { var locScaleX = this._scaleX, locScaleY = this._scaleY; cc.game._renderContext.viewport(x * locScaleX + this._viewportRect.x, y * locScaleY + this._viewportRect.y, w * locScaleX, h * locScaleY); }, setScissorInPoints: function setScissorInPoints(x, y, w, h) { var scaleX = this._scaleX, scaleY = this._scaleY; var sx = Math.ceil(x * scaleX + this._viewportRect.x); var sy = Math.ceil(y * scaleY + this._viewportRect.y); var sw = Math.ceil(w * scaleX); var sh = Math.ceil(h * scaleY); var gl = cc.game._renderContext; if (!_scissorRect) { var boxArr = gl.getParameter(gl.SCISSOR_BOX); _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); } if (_scissorRect.x !== sx || _scissorRect.y !== sy || _scissorRect.width !== sw || _scissorRect.height !== sh) { _scissorRect.x = sx; _scissorRect.y = sy; _scissorRect.width = sw; _scissorRect.height = sh; gl.scissor(sx, sy, sw, sh); } }, isScissorEnabled: function isScissorEnabled() { return cc.game._renderContext.isEnabled(gl.SCISSOR_TEST); }, getScissorRect: function getScissorRect() { if (!_scissorRect) { var boxArr = gl.getParameter(gl.SCISSOR_BOX); _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); } var scaleXFactor = 1 / this._scaleX; var scaleYFactor = 1 / this._scaleY; return cc.rect((_scissorRect.x - this._viewportRect.x) * scaleXFactor, (_scissorRect.y - this._viewportRect.y) * scaleYFactor, _scissorRect.width * scaleXFactor, _scissorRect.height * scaleYFactor); }, getViewportRect: function getViewportRect() { return this._viewportRect; }, getScaleX: function getScaleX() { return this._scaleX; }, getScaleY: function getScaleY() { return this._scaleY; }, getDevicePixelRatio: function getDevicePixelRatio() { return this._devicePixelRatio; }, convertToLocationInView: function convertToLocationInView(tx, ty, relatedPos, out) { var result = out || cc.v2(); var posLeft = relatedPos.adjustedLeft ? relatedPos.adjustedLeft : relatedPos.left; var posTop = relatedPos.adjustedTop ? relatedPos.adjustedTop : relatedPos.top; var x = this._devicePixelRatio * (tx - posLeft); var y = this._devicePixelRatio * (posTop + relatedPos.height - ty); if (this._isRotated) { result.x = cc.game.canvas.width - y; result.y = x; } else { result.x = x; result.y = y; } return result; }, _convertMouseToLocationInView: function _convertMouseToLocationInView(in_out_point, relatedPos) { var viewport = this._viewportRect, _t = this; in_out_point.x = (_t._devicePixelRatio * (in_out_point.x - relatedPos.left) - viewport.x) / _t._scaleX; in_out_point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y) - viewport.y) / _t._scaleY; }, _convertPointWithScale: function _convertPointWithScale(point) { var viewport = this._viewportRect; point.x = (point.x - viewport.x) / this._scaleX; point.y = (point.y - viewport.y) / this._scaleY; }, _convertTouchesWithScale: function _convertTouchesWithScale(touches) { var viewport = this._viewportRect, scaleX = this._scaleX, scaleY = this._scaleY, selTouch, selPoint, selPrePoint; for (var i = 0; i < touches.length; i++) { selTouch = touches[i]; selPoint = selTouch._point; selPrePoint = selTouch._prevPoint; selPoint.x = (selPoint.x - viewport.x) / scaleX; selPoint.y = (selPoint.y - viewport.y) / scaleY; selPrePoint.x = (selPrePoint.x - viewport.x) / scaleX; selPrePoint.y = (selPrePoint.y - viewport.y) / scaleY; } } }); cc.ContainerStrategy = cc.Class({ name: "ContainerStrategy", preApply: function preApply(view) {}, apply: function apply(view, designedResolution) {}, postApply: function postApply(view) {}, _setupContainer: function _setupContainer(view, w, h) { var locCanvas = cc.game.canvas; this._setupStyle(view, w, h); var devicePixelRatio = view._devicePixelRatio = 1; false; view.isRetinaEnabled() && (devicePixelRatio = view._devicePixelRatio = Math.min(view._maxPixelRatio, window.devicePixelRatio || 1)); locCanvas.width = w * devicePixelRatio; locCanvas.height = h * devicePixelRatio; }, _setupStyle: function _setupStyle(view, w, h) { var locCanvas = cc.game.canvas; var locContainer = cc.game.container; if (cc.sys.os === cc.sys.OS_ANDROID) { document.body.style.width = (view._isRotated ? h : w) + "px"; document.body.style.height = (view._isRotated ? w : h) + "px"; } locContainer.style.width = locCanvas.style.width = w + "px"; locContainer.style.height = locCanvas.style.height = h + "px"; }, _fixContainer: function _fixContainer() { document.body.insertBefore(cc.game.container, document.body.firstChild); var bs = document.body.style; bs.width = window.innerWidth + "px"; bs.height = window.innerHeight + "px"; bs.overflow = "hidden"; var contStyle = cc.game.container.style; contStyle.position = "fixed"; contStyle.left = contStyle.top = "0px"; document.body.scrollTop = 0; } }); cc.ContentStrategy = cc.Class({ name: "ContentStrategy", ctor: function ctor() { this._result = { scale: [ 1, 1 ], viewport: null }; }, _buildResult: function _buildResult(containerW, containerH, contentW, contentH, scaleX, scaleY) { Math.abs(containerW - contentW) < 2 && (contentW = containerW); Math.abs(containerH - contentH) < 2 && (contentH = containerH); var viewport = cc.rect((containerW - contentW) / 2, (containerH - contentH) / 2, contentW, contentH); cc.game.renderType === cc.game.RENDER_TYPE_CANVAS; this._result.scale = [ scaleX, scaleY ]; this._result.viewport = viewport; return this._result; }, preApply: function preApply(view) {}, apply: function apply(view, designedResolution) { return { scale: [ 1, 1 ] }; }, postApply: function postApply(view) {} }); (function() { var EqualToFrame = cc.Class({ name: "EqualToFrame", extends: cc.ContainerStrategy, apply: function apply(view) { var frameH = view._frameSize.height, containerStyle = cc.game.container.style; this._setupContainer(view, view._frameSize.width, view._frameSize.height); view._isRotated ? containerStyle.margin = "0 0 0 " + frameH + "px" : containerStyle.margin = "0px"; containerStyle.padding = "0px"; } }); var ProportionalToFrame = cc.Class({ name: "ProportionalToFrame", extends: cc.ContainerStrategy, apply: function apply(view, designedResolution) { var frameW = view._frameSize.width, frameH = view._frameSize.height, containerStyle = cc.game.container.style, designW = designedResolution.width, designH = designedResolution.height, scaleX = frameW / designW, scaleY = frameH / designH, containerW, containerH; scaleX < scaleY ? (containerW = frameW, containerH = designH * scaleX) : (containerW = designW * scaleY, containerH = frameH); var offx = Math.round((frameW - containerW) / 2); var offy = Math.round((frameH - containerH) / 2); containerW = frameW - 2 * offx; containerH = frameH - 2 * offy; this._setupContainer(view, containerW, containerH); true; view._isRotated ? containerStyle.margin = "0 0 0 " + frameH + "px" : containerStyle.margin = "0px"; containerStyle.paddingLeft = offx + "px"; containerStyle.paddingRight = offx + "px"; containerStyle.paddingTop = offy + "px"; containerStyle.paddingBottom = offy + "px"; } }); var EqualToWindow = cc.Class({ name: "EqualToWindow", extends: EqualToFrame, preApply: function preApply(view) { this._super(view); cc.game.frame = document.documentElement; }, apply: function apply(view) { this._super(view); this._fixContainer(); } }); var ProportionalToWindow = cc.Class({ name: "ProportionalToWindow", extends: ProportionalToFrame, preApply: function preApply(view) { this._super(view); cc.game.frame = document.documentElement; }, apply: function apply(view, designedResolution) { this._super(view, designedResolution); this._fixContainer(); } }); var OriginalContainer = cc.Class({ name: "OriginalContainer", extends: cc.ContainerStrategy, apply: function apply(view) { this._setupContainer(view, cc.game.canvas.width, cc.game.canvas.height); } }); var _global = "undefined" === typeof window ? global : window; var globalAdapter = _global.__globalAdapter; if (globalAdapter) { globalAdapter.adaptContainerStrategy && globalAdapter.adaptContainerStrategy(cc.ContainerStrategy.prototype); globalAdapter.adaptView && globalAdapter.adaptView(View.prototype); } cc.ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame(); cc.ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame(); cc.ContainerStrategy.ORIGINAL_CONTAINER = new OriginalContainer(); var ExactFit = cc.Class({ name: "ExactFit", extends: cc.ContentStrategy, apply: function apply(view, designedResolution) { var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, scaleX = containerW / designedResolution.width, scaleY = containerH / designedResolution.height; return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY); } }); var ShowAll = cc.Class({ name: "ShowAll", extends: cc.ContentStrategy, apply: function apply(view, designedResolution) { var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, designH = designedResolution.height, scaleX = containerW / designW, scaleY = containerH / designH, scale = 0, contentW, contentH; scaleX < scaleY ? (scale = scaleX, contentW = containerW, contentH = designH * scale) : (scale = scaleY, contentW = designW * scale, contentH = containerH); return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); } }); var NoBorder = cc.Class({ name: "NoBorder", extends: cc.ContentStrategy, apply: function apply(view, designedResolution) { var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, designH = designedResolution.height, scaleX = containerW / designW, scaleY = containerH / designH, scale, contentW, contentH; scaleX < scaleY ? (scale = scaleY, contentW = designW * scale, contentH = containerH) : (scale = scaleX, contentW = containerW, contentH = designH * scale); return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); } }); var FixedHeight = cc.Class({ name: "FixedHeight", extends: cc.ContentStrategy, apply: function apply(view, designedResolution) { var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designH = designedResolution.height, scale = containerH / designH, contentW = containerW, contentH = containerH; return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); } }); var FixedWidth = cc.Class({ name: "FixedWidth", extends: cc.ContentStrategy, apply: function apply(view, designedResolution) { var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, scale = containerW / designW, contentW = containerW, contentH = containerH; return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); } }); cc.ContentStrategy.EXACT_FIT = new ExactFit(); cc.ContentStrategy.SHOW_ALL = new ShowAll(); cc.ContentStrategy.NO_BORDER = new NoBorder(); cc.ContentStrategy.FIXED_HEIGHT = new FixedHeight(); cc.ContentStrategy.FIXED_WIDTH = new FixedWidth(); })(); cc.ResolutionPolicy = cc.Class({ name: "cc.ResolutionPolicy", ctor: function ctor(containerStg, contentStg) { this._containerStrategy = null; this._contentStrategy = null; this.setContainerStrategy(containerStg); this.setContentStrategy(contentStg); }, preApply: function preApply(view) { this._containerStrategy.preApply(view); this._contentStrategy.preApply(view); }, apply: function apply(view, designedResolution) { this._containerStrategy.apply(view, designedResolution); return this._contentStrategy.apply(view, designedResolution); }, postApply: function postApply(view) { this._containerStrategy.postApply(view); this._contentStrategy.postApply(view); }, setContainerStrategy: function setContainerStrategy(containerStg) { containerStg instanceof cc.ContainerStrategy && (this._containerStrategy = containerStg); }, setContentStrategy: function setContentStrategy(contentStg) { contentStg instanceof cc.ContentStrategy && (this._contentStrategy = contentStg); } }); js.get(cc.ResolutionPolicy.prototype, "canvasSize", (function() { return cc.v2(cc.game.canvas.width, cc.game.canvas.height); })); cc.ResolutionPolicy.EXACT_FIT = 0; cc.ResolutionPolicy.NO_BORDER = 1; cc.ResolutionPolicy.SHOW_ALL = 2; cc.ResolutionPolicy.FIXED_HEIGHT = 3; cc.ResolutionPolicy.FIXED_WIDTH = 4; cc.ResolutionPolicy.UNKNOWN = 5; cc.view = new View(); cc.winSize = cc.size(); module.exports = cc.view; }), { "../event/event-target": 119, "../platform/CCClass": 129, "../platform/js": 150, "../renderer": 160 } ], 140: [ (function(require, module, exports) { "use strict"; cc.visibleRect = { topLeft: cc.v2(0, 0), topRight: cc.v2(0, 0), top: cc.v2(0, 0), bottomLeft: cc.v2(0, 0), bottomRight: cc.v2(0, 0), bottom: cc.v2(0, 0), center: cc.v2(0, 0), left: cc.v2(0, 0), right: cc.v2(0, 0), width: 0, height: 0, init: function init(visibleRect) { var w = this.width = visibleRect.width; var h = this.height = visibleRect.height; var l = visibleRect.x, b = visibleRect.y, t = b + h, r = l + w; this.topLeft.x = l; this.topLeft.y = t; this.topRight.x = r; this.topRight.y = t; this.top.x = l + w / 2; this.top.y = t; this.bottomLeft.x = l; this.bottomLeft.y = b; this.bottomRight.x = r; this.bottomRight.y = b; this.bottom.x = l + w / 2; this.bottom.y = b; this.center.x = l + w / 2; this.center.y = b + h / 2; this.left.x = l; this.left.y = b + h / 2; this.right.x = r; this.right.y = b + h / 2; } }; }), {} ], 141: [ (function(require, module, exports) { "use strict"; var js = require("./js"); var isPlainEmptyObj = require("./utils").isPlainEmptyObj_DEV; var DELIMETER = "$_$"; function createAttrsSingle(owner, superAttrs) { var attrs = superAttrs ? Object.create(superAttrs) : {}; js.value(owner, "__attrs__", attrs); return attrs; } function createAttrs(subclass) { if ("function" !== typeof subclass) { var instance = subclass; return createAttrsSingle(instance, getClassAttrs(instance.constructor)); } var superClass; var chains = cc.Class.getInheritanceChain(subclass); for (var i = chains.length - 1; i >= 0; i--) { var cls = chains[i]; var attrs = cls.hasOwnProperty("__attrs__") && cls.__attrs__; if (!attrs) { superClass = chains[i + 1]; createAttrsSingle(cls, superClass && superClass.__attrs__); } } superClass = chains[0]; createAttrsSingle(subclass, superClass && superClass.__attrs__); return subclass.__attrs__; } function attr(ctor, propName, newAttrs) { var attrs = getClassAttrs(ctor); var _key; true; var prefix = propName + DELIMETER; var ret = {}; for (var key in attrs) key.startsWith(prefix) && (ret[key.slice(prefix.length)] = attrs[key]); return ret; } function getClassAttrs(ctor) { return ctor.hasOwnProperty("__attrs__") && ctor.__attrs__ || createAttrs(ctor); } function setClassAttr(ctor, propName, key, value) { getClassAttrs(ctor)[propName + DELIMETER + key] = value; } function PrimitiveType(name, def) { this.name = name; this["default"] = def; } PrimitiveType.prototype.toString = function() { return this.name; }; cc.Integer = new PrimitiveType("Integer", 0); cc.Float = new PrimitiveType("Float", 0); false; cc.Boolean = new PrimitiveType("Boolean", false); cc.String = new PrimitiveType("String", ""); function getTypeChecker(type, attrName) { return function(constructor, mainPropName) { var propInfo = '"' + js.getClassName(constructor) + "." + mainPropName + '"'; var mainPropAttrs = attr(constructor, mainPropName); var mainPropAttrsType = mainPropAttrs.type; mainPropAttrsType === cc.Integer || mainPropAttrsType === cc.Float ? mainPropAttrsType = "Number" : mainPropAttrsType !== cc.String && mainPropAttrsType !== cc.Boolean || (mainPropAttrsType = "" + mainPropAttrsType); if (mainPropAttrsType !== type) { cc.warnID(3604, propInfo); return; } if (!mainPropAttrs.hasOwnProperty("default")) return; var defaultVal = mainPropAttrs["default"]; if ("undefined" === typeof defaultVal) return; var isContainer = Array.isArray(defaultVal) || isPlainEmptyObj(defaultVal); if (isContainer) return; var defaultType = typeof defaultVal; var type_lowerCase = type.toLowerCase(); if (defaultType === type_lowerCase) if ("object" === type_lowerCase) { if (!defaultVal || defaultVal instanceof mainPropAttrs.ctor) return; cc.warnID(3605, propInfo, js.getClassName(mainPropAttrs.ctor)); } else "Number" !== type && cc.warnID(3606, attrName, propInfo, type); else { if ("function" === defaultType) return; type === cc.String && null == defaultVal ? cc.warnID(3607, propInfo) : cc.warnID(3611, attrName, propInfo, defaultType); } delete mainPropAttrs.type; }; } function getObjTypeChecker(typeCtor) { return function(classCtor, mainPropName) { getTypeChecker("Object", "type")(classCtor, mainPropName); var defaultDef = getClassAttrs(classCtor)[mainPropName + DELIMETER + "default"]; var defaultVal = require("./CCClass").getDefault(defaultDef); if (!Array.isArray(defaultVal) && js.isChildClassOf(typeCtor, cc.ValueType)) { var typename = js.getClassName(typeCtor); var info = cc.js.formatStr('No need to specify the "type" of "%s.%s" because %s is a child class of ValueType.', js.getClassName(classCtor), mainPropName, typename); defaultDef ? cc.log(info) : cc.warnID(3612, info, typename, js.getClassName(classCtor), mainPropName, typename); } }; } module.exports = { PrimitiveType: PrimitiveType, attr: attr, getClassAttrs: getClassAttrs, setClassAttr: setClassAttr, DELIMETER: DELIMETER, getTypeChecker_ET: (false, false) && getTypeChecker, getObjTypeChecker_ET: (false, false) && getObjTypeChecker, ScriptUuid: {} }; }), { "./CCClass": 129, "./js": 150, "./utils": 153 } ], 142: [ (function(require, module, exports) { "use strict"; var js = require("./js"); var fastRemoveAt = js.array.fastRemoveAt; function empty() {} function CallbackInfo() { this.callback = empty; this.target = void 0; this.once = false; } CallbackInfo.prototype.set = function(callback, target, once) { this.callback = callback; this.target = target; this.once = !!once; }; var callbackInfoPool = new js.Pool(function(info) { info.callback = empty; info.target = void 0; info.once = false; return true; }, 32); callbackInfoPool.get = function() { return this._get() || new CallbackInfo(); }; function CallbackList() { this.callbackInfos = []; this.isInvoking = false; this.containCanceled = false; } var proto = CallbackList.prototype; proto.removeByCallback = function(cb) { for (var i = 0; i < this.callbackInfos.length; ++i) { var info = this.callbackInfos[i]; if (info && info.callback === cb) { callbackInfoPool.put(info); fastRemoveAt(this.callbackInfos, i); --i; } } }; proto.removeByTarget = function(target) { for (var i = 0; i < this.callbackInfos.length; ++i) { var info = this.callbackInfos[i]; if (info && info.target === target) { callbackInfoPool.put(info); fastRemoveAt(this.callbackInfos, i); --i; } } }; proto.cancel = function(index) { var info = this.callbackInfos[index]; if (info) { callbackInfoPool.put(info); this.callbackInfos[index] = null; } this.containCanceled = true; }; proto.cancelAll = function() { for (var i = 0; i < this.callbackInfos.length; i++) { var info = this.callbackInfos[i]; if (info) { callbackInfoPool.put(info); this.callbackInfos[i] = null; } } this.containCanceled = true; }; proto.purgeCanceled = function() { for (var i = this.callbackInfos.length - 1; i >= 0; --i) { var info = this.callbackInfos[i]; info || fastRemoveAt(this.callbackInfos, i); } this.containCanceled = false; }; proto.clear = function() { this.cancelAll(); this.callbackInfos.length = 0; this.isInvoking = false; this.containCanceled = false; }; var MAX_SIZE = 16; var callbackListPool = new js.Pool(function(info) { info.callbackInfos = []; info.isInvoking = false; info.containCanceled = false; return true; }, MAX_SIZE); callbackListPool.get = function() { return this._get() || new CallbackList(); }; function CallbacksInvoker() { this._callbackTable = js.createMap(true); } proto = CallbacksInvoker.prototype; proto.on = function(key, callback, target, once) { var list = this._callbackTable[key]; list || (list = this._callbackTable[key] = callbackListPool.get()); var info = callbackInfoPool.get(); info.set(callback, target, once); list.callbackInfos.push(info); }; proto.hasEventListener = function(key, callback, target) { var list = this._callbackTable[key]; if (!list) return false; var infos = list.callbackInfos; if (!callback) { if (list.isInvoking) { for (var i = 0; i < infos.length; ++i) if (infos[i]) return true; return false; } return infos.length > 0; } for (var _i = 0; _i < infos.length; ++_i) { var info = infos[_i]; if (info && info.callback === callback && info.target === target) return true; } return false; }; proto.removeAll = function(keyOrTarget) { if ("string" === typeof keyOrTarget) { var list = this._callbackTable[keyOrTarget]; if (list) if (list.isInvoking) list.cancelAll(); else { list.clear(); callbackListPool.put(list); delete this._callbackTable[keyOrTarget]; } } else if (keyOrTarget) for (var key in this._callbackTable) { var _list = this._callbackTable[key]; if (_list.isInvoking) { var infos = _list.callbackInfos; for (var i = 0; i < infos.length; ++i) { var info = infos[i]; info && info.target === keyOrTarget && _list.cancel(i); } } else _list.removeByTarget(keyOrTarget); } }; proto.off = function(key, callback, target) { var list = this._callbackTable[key]; if (list) { var infos = list.callbackInfos; for (var i = 0; i < infos.length; ++i) { var info = infos[i]; if (info && info.callback === callback && info.target === target) { if (list.isInvoking) list.cancel(i); else { fastRemoveAt(infos, i); callbackInfoPool.put(info); } break; } } } }; proto.emit = function(key, arg1, arg2, arg3, arg4, arg5) { var list = this._callbackTable[key]; if (list) { var rootInvoker = !list.isInvoking; list.isInvoking = true; var infos = list.callbackInfos; for (var i = 0, len = infos.length; i < len; ++i) { var info = infos[i]; if (info) { var target = info.target; var callback = info.callback; info.once && this.off(key, callback, target); target ? callback.call(target, arg1, arg2, arg3, arg4, arg5) : callback(arg1, arg2, arg3, arg4, arg5); } } if (rootInvoker) { list.isInvoking = false; list.containCanceled && list.purgeCanceled(); } } }; false; module.exports = CallbacksInvoker; }), { "./js": 150 } ], 143: [ (function(require, module, exports) { "use strict"; function deepFlatten(strList, array) { for (var i = 0; i < array.length; i++) { var item = array[i]; Array.isArray(item) ? deepFlatten(strList, item) : strList.push(item); } } function flattenCodeArray(array) { var separator = ""; var strList = []; deepFlatten(strList, array); return strList.join(separator); } module.exports = { flattenCodeArray: flattenCodeArray }; }), {} ], 144: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = deserialize; exports.getDependUuidList = getDependUuidList; exports.hasNativeDep = hasNativeDep; exports.packCustomObjData = packCustomObjData; exports.unpackJSONs = unpackJSONs; var _js = _interopRequireDefault(require("./js")); var _vec = _interopRequireDefault(require("../value-types/vec2")); var _vec2 = _interopRequireDefault(require("../value-types/vec3")); var _vec3 = _interopRequireDefault(require("../value-types/vec4")); var _color = _interopRequireDefault(require("../value-types/color")); var _size = _interopRequireDefault(require("../value-types/size")); var _rect = _interopRequireDefault(require("../value-types/rect")); var _quat = _interopRequireDefault(require("../value-types/quat")); var _mat = _interopRequireDefault(require("../value-types/mat4")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SUPPORT_MIN_FORMAT_VERSION = 1; var EMPTY_PLACEHOLDER = 0; var BuiltinValueTypes = [ _vec["default"], _vec2["default"], _vec3["default"], _quat["default"], _color["default"], _size["default"], _rect["default"], _mat["default"] ]; function BuiltinValueTypeParsers_xyzw(obj, data) { obj.x = data[1]; obj.y = data[2]; obj.z = data[3]; obj.w = data[4]; } var BuiltinValueTypeSetters = [ function(obj, data) { obj.x = data[1]; obj.y = data[2]; }, function(obj, data) { obj.x = data[1]; obj.y = data[2]; obj.z = data[3]; }, BuiltinValueTypeParsers_xyzw, BuiltinValueTypeParsers_xyzw, function(obj, data) { obj._val = data[1]; }, function(obj, data) { obj.width = data[1]; obj.height = data[2]; }, function(obj, data) { obj.x = data[1]; obj.y = data[2]; obj.width = data[3]; obj.height = data[4]; }, function(obj, data) { _mat["default"].fromArray(obj, data, 1); } ]; function serializeBuiltinValueTypes(obj) { var ctor = obj.constructor; var typeId = BuiltinValueTypes.indexOf(ctor); switch (ctor) { case _vec["default"]: return [ typeId, obj.x, obj.y ]; case _vec2["default"]: return [ typeId, obj.x, obj.y, obj.z ]; case _vec3["default"]: case _quat["default"]: return [ typeId, obj.x, obj.y, obj.z, obj.w ]; case _color["default"]: return [ typeId, obj._val ]; case _size["default"]: return [ typeId, obj.width, obj.height ]; case _rect["default"]: return [ typeId, obj.x, obj.y, obj.width, obj.height ]; case _mat["default"]: var res = new Array(17); res[0] = typeId; _mat["default"].toArray(res, obj, 1); return res; default: return null; } } var DataTypeID = { SimpleType: 0, InstanceRef: 1, Array_InstanceRef: 2, Array_AssetRefByInnerObj: 3, Class: 4, ValueTypeCreated: 5, AssetRefByInnerObj: 6, TRS: 7, ValueType: 8, Array_Class: 9, CustomizedClass: 10, Dict: 11, Array: 12, ARRAY_LENGTH: 13 }; var CLASS_TYPE = 0; var CLASS_KEYS = 1; var CLASS_PROP_TYPE_OFFSET = 2; var MASK_CLASS = 0; var OBJ_DATA_MASK = 0; var CUSTOM_OBJ_DATA_CLASS = 0; var CUSTOM_OBJ_DATA_CONTENT = 1; var VALUETYPE_SETTER = 0; var DICT_JSON_LAYOUT = 0; var ARRAY_ITEM_VALUES = 0; var Refs = { EACH_RECORD_LENGTH: 3, OWNER_OFFSET: 0, KEY_OFFSET: 1, TARGET_OFFSET: 2 }; var File = { Version: 0, Context: 0, SharedUuids: 1, SharedStrings: 2, SharedClasses: 3, SharedMasks: 4, Instances: 5, InstanceTypes: 6, Refs: 7, DependObjs: 8, DependKeys: 9, DependUuidIndices: 10, ARRAY_LENGTH: 11 }; var PACKED_SECTIONS = 5; var Details = (function() { function Details() { this.uuidObjList = null; this.uuidPropList = null; this.uuidList = null; } var _proto = Details.prototype; _proto.init = function init(data) { this.uuidObjList = data[8]; this.uuidPropList = data[9]; this.uuidList = data[10]; }; _proto.reset = function reset() { this.uuidList = null; this.uuidObjList = null; this.uuidPropList = null; }; _proto.push = function push(obj, propName, uuid) { this.uuidObjList.push(obj); this.uuidPropList.push(propName); this.uuidList.push(uuid); }; return Details; })(); Details.pool = new _js["default"].Pool(function(obj) { obj.reset(); }, 5); Details.pool.get = function() { return this._get() || new Details(); }; false, false; function dereference(refs, instances, strings) { var dataLength = refs.length - 1; var i = 0; var instanceOffset = 3 * refs[dataLength]; for (;i < instanceOffset; i += 3) { var _owner = refs[i]; var target = instances[refs[i + 2]]; var keyIndex = refs[i + 1]; keyIndex >= 0 ? _owner[strings[keyIndex]] = target : _owner[~keyIndex] = target; } for (;i < dataLength; i += 3) { var _owner2 = instances[refs[i]]; var _target = instances[refs[i + 2]]; var _keyIndex = refs[i + 1]; _keyIndex >= 0 ? _owner2[strings[_keyIndex]] = _target : _owner2[~_keyIndex] = _target; } } function deserializeCCObject(data, objectData) { var mask = data[4][objectData[0]]; var clazz = mask[0]; var ctor = clazz[0]; var obj = new ctor(); var keys = clazz[1]; var classTypeOffset = clazz[2]; var maskTypeOffset = mask[mask.length - 1]; var i = 1; for (;i < maskTypeOffset; ++i) { var _key = keys[mask[i]]; obj[_key] = objectData[i]; } for (;i < objectData.length; ++i) { var _key2 = keys[mask[i]]; var _type = clazz[mask[i] + classTypeOffset]; var op = ASSIGNMENTS[_type]; op(data, obj, _key2, objectData[i]); } return obj; } function deserializeCustomCCObject(data, ctor, value) { var obj = new ctor(); obj._deserialize ? obj._deserialize(value, data[0]) : cc.errorID(5303, _js["default"].getClassName(ctor)); return obj; } function assignSimple(data, owner, key, value) { owner[key] = value; } function assignInstanceRef(data, owner, key, value) { value >= 0 ? owner[key] = data[5][value] : data[7][3 * ~value] = owner; } function genArrayParser(parser) { return function(data, owner, key, value) { owner[key] = value; for (var i = 0; i < value.length; ++i) parser(data, value, i, value[i]); }; } function parseAssetRefByInnerObj(data, owner, key, value) { owner[key] = null; data[8][value] = owner; } function parseClass(data, owner, key, value) { owner[key] = deserializeCCObject(data, value); } function parseCustomClass(data, owner, key, value) { var ctor = data[3][value[0]]; owner[key] = deserializeCustomCCObject(data, ctor, value[1]); } function parseValueTypeCreated(data, owner, key, value) { BuiltinValueTypeSetters[value[0]](owner[key], value); } function parseValueType(data, owner, key, value) { var val = new BuiltinValueTypes[value[0]](); BuiltinValueTypeSetters[value[0]](val, value); owner[key] = val; } function parseTRS(data, owner, key, value) { var typedArray = owner[key]; typedArray.set(value); } function parseDict(data, owner, key, value) { var dict = value[0]; owner[key] = dict; for (var i = 1; i < value.length; i += 3) { var _key3 = value[i]; var _type2 = value[i + 1]; var subValue = value[i + 2]; var op = ASSIGNMENTS[_type2]; op(data, dict, _key3, subValue); } } function parseArray(data, owner, key, value) { var array = value[0]; owner[key] = array; for (var i = 0; i < array.length; ++i) { var subValue = array[i]; var _type3 = value[i + 1]; if (0 !== _type3) { var op = ASSIGNMENTS[_type3]; op(data, array, i, subValue); } } } var ASSIGNMENTS = new Array(13); ASSIGNMENTS[0] = assignSimple; ASSIGNMENTS[1] = assignInstanceRef; ASSIGNMENTS[2] = genArrayParser(assignInstanceRef); ASSIGNMENTS[3] = genArrayParser(parseAssetRefByInnerObj); ASSIGNMENTS[4] = parseClass; ASSIGNMENTS[5] = parseValueTypeCreated; ASSIGNMENTS[6] = parseAssetRefByInnerObj; ASSIGNMENTS[7] = parseTRS; ASSIGNMENTS[8] = parseValueType; ASSIGNMENTS[9] = genArrayParser(parseClass); ASSIGNMENTS[10] = parseCustomClass; ASSIGNMENTS[11] = parseDict; ASSIGNMENTS[12] = parseArray; function parseInstances(data) { var instances = data[5]; var instanceTypes = data[6]; var instanceTypesLen = 0 === instanceTypes ? 0 : instanceTypes.length; var rootIndex = instances[instances.length - 1]; var normalObjectCount = instances.length - instanceTypesLen; if ("number" !== typeof rootIndex) rootIndex = 0; else { rootIndex < 0 && (rootIndex = ~rootIndex); --normalObjectCount; } var insIndex = 0; for (;insIndex < normalObjectCount; ++insIndex) instances[insIndex] = deserializeCCObject(data, instances[insIndex]); var classes = data[3]; for (var typeIndex = 0; typeIndex < instanceTypesLen; ++typeIndex, ++insIndex) { var _type4 = instanceTypes[typeIndex]; var eachData = instances[insIndex]; if (_type4 >= 0) { var ctor = classes[_type4]; instances[insIndex] = deserializeCustomCCObject(data, ctor, eachData); } else { _type4 = ~_type4; var op = ASSIGNMENTS[_type4]; op(data, instances, insIndex, eachData); } } return rootIndex; } function getMissingClass(hasCustomFinder, type) { hasCustomFinder || deserialize.reportMissingClass(type); return Object; } function doLookupClass(classFinder, type, container, index, silent, hasCustomFinder) { var klass = classFinder(type); if (!klass) { if (silent) { container[index] = (function(container, index, type) { return function proxy() { var klass = classFinder(type) || getMissingClass(hasCustomFinder, type); container[index] = klass; return new klass(); }; })(container, index, type); return; } klass = getMissingClass(hasCustomFinder, type); } container[index] = klass; } function lookupClasses(data, silent, customFinder) { var classFinder = customFinder || _js["default"]._getClassById; var classes = data[3]; for (var i = 0; i < classes.length; ++i) { var klassLayout = classes[i]; if ("string" !== typeof klassLayout) { true; if ("function" === typeof klassLayout[0]) throw new Error("Can not deserialize the same JSON data again."); var _type5 = klassLayout[0]; doLookupClass(classFinder, _type5, klassLayout, CLASS_TYPE, silent, customFinder); } else doLookupClass(classFinder, klassLayout, classes, i, silent, customFinder); } } function cacheMasks(data) { var masks = data[4]; if (masks) { var classes = data[3]; for (var i = 0; i < masks.length; ++i) { var mask = masks[i]; mask[0] = classes[mask[0]]; } } } function parseResult(data) { var instances = data[5]; var sharedStrings = data[2]; var dependSharedUuids = data[1]; var dependObjs = data[8]; var dependKeys = data[9]; var dependUuids = data[10]; for (var i = 0; i < dependObjs.length; ++i) { var _obj = dependObjs[i]; "number" === typeof _obj && (dependObjs[i] = instances[_obj]); var _key4 = dependKeys[i]; if ("number" === typeof _key4) { _key4 = _key4 >= 0 ? sharedStrings[_key4] : ~_key4; dependKeys[i] = _key4; } var uuid = dependUuids[i]; "number" === typeof uuid && (dependUuids[i] = dependSharedUuids[uuid]); } } function deserialize(data, details, options) { false; "string" === typeof data && (data = JSON.parse(data)); var borrowDetails = !details; details = details || Details.pool.get(); details.init(data); options = options || {}; var version = data[0]; var preprocessed = false; if ("object" === typeof version) { preprocessed = version.preprocessed; version = version.version; } if (version < 1) throw new Error(cc.debug.getError(5304, version)); options._version = version; options.result = details; data[0] = options; if (!preprocessed) { lookupClasses(data, false, options.classFinder); cacheMasks(data); } cc.game._isCloning = true; var instances = data[5]; var rootIndex = parseInstances(data); cc.game._isCloning = false; data[7] && dereference(data[7], instances, data[2]); parseResult(data); borrowDetails && Details.pool.put(details); return instances[rootIndex]; } deserialize.Details = Details; var FileInfo = function FileInfo(version) { this.preprocessed = true; this.version = version; }; function unpackJSONs(data, classFinder) { if (data[0] < 1) throw new Error(cc.debug.getError(5304, data[0])); lookupClasses(data, true, classFinder); cacheMasks(data); var version = new FileInfo(data[0]); var sharedUuids = data[1]; var sharedStrings = data[2]; var sharedClasses = data[3]; var sharedMasks = data[4]; var sections = data[PACKED_SECTIONS]; for (var i = 0; i < sections.length; ++i) sections[i].unshift(version, sharedUuids, sharedStrings, sharedClasses, sharedMasks); return sections; } function packCustomObjData(type, data, hasNativeDep) { return [ 1, EMPTY_PLACEHOLDER, EMPTY_PLACEHOLDER, [ type ], EMPTY_PLACEHOLDER, hasNativeDep ? [ data, -1 ] : [ data ], [ 0 ], EMPTY_PLACEHOLDER, [], [], [] ]; } function hasNativeDep(data) { var instances = data[5]; var rootInfo = instances[instances.length - 1]; return "number" === typeof rootInfo && rootInfo < 0; } false; function getDependUuidList(json) { var sharedUuids = json[1]; return json[10].map((function(index) { return sharedUuids[index]; })); } false, false; false; }), { "../value-types/color": 231, "../value-types/mat4": 234, "../value-types/quat": 235, "../value-types/rect": 236, "../value-types/size": 237, "../value-types/vec2": 241, "../value-types/vec3": 242, "../value-types/vec4": 243, "./js": 150 } ], 145: [ (function(require, module, exports) { "use strict"; var _deserializeCompiled = _interopRequireDefault(require("./deserialize-compiled")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _deserializeCompiled["default"].reportMissingClass = function(id) { false; cc.warnID(5302, id); }; var deserializeForEditor; true; cc.deserialize = _deserializeCompiled["default"]; }), { "./deserialize-compiled": 144, "./deserialize-editor": void 0 } ], 146: [ (function(require, module, exports) { "use strict"; var NonUuidMark = "."; function IdGenerater(category) { this.id = 0 | 998 * Math.random(); this.prefix = category ? category + NonUuidMark : ""; } IdGenerater.prototype.getNewId = function() { return this.prefix + ++this.id; }; IdGenerater.global = new IdGenerater("global"); module.exports = IdGenerater; }), {} ], 147: [ (function(require, module, exports) { "use strict"; require("./js"); require("./CCClass"); require("./CCClassDecorator"); require("./CCEnum"); require("./CCObject"); require("./callbacks-invoker"); require("./deserialize"); require("./instantiate"); require("./instantiate-jit"); require("./requiring-frame"); require("./CCSys"); require("./CCMacro"); true; require("./CCVisibleRect"); }), { "./CCClass": 129, "./CCClassDecorator": 130, "./CCEnum": 131, "./CCMacro": 134, "./CCObject": 135, "./CCSys": 138, "./CCVisibleRect": 140, "./callbacks-invoker": 142, "./deserialize": 145, "./instantiate": 149, "./instantiate-jit": 148, "./js": 150, "./requiring-frame": 152 } ], 148: [ (function(require, module, exports) { "use strict"; var CCObject = require("./CCObject"); var Destroyed = CCObject.Flags.Destroyed; var PersistentMask = CCObject.Flags.PersistentMask; var Attr = require("./attribute"); var js = require("./js"); var CCClass = require("./CCClass"); var Compiler = require("./compiler"); var DEFAULT = Attr.DELIMETER + "default"; var IDENTIFIER_RE = CCClass.IDENTIFIER_RE; var escapeForJS = CCClass.escapeForJS; var VAR = "var "; var LOCAL_OBJ = "o"; var LOCAL_TEMP_OBJ = "t"; var LOCAL_ARRAY = "a"; var LINE_INDEX_OF_NEW_OBJ = 0; var DEFAULT_MODULE_CACHE = { "cc.Node": "cc.Node", "cc.Sprite": "cc.Sprite", "cc.Label": "cc.Label", "cc.Button": "cc.Button", "cc.Widget": "cc.Widget", "cc.Animation": "cc.Animation", "cc.ClickEvent": false, "cc.PrefabInfo": false }; try { !Float32Array.name && (Float32Array.name = "Float32Array"); !Float64Array.name && (Float64Array.name = "Float64Array"); !Int8Array.name && (Int8Array.name = "Int8Array"); !Int16Array.name && (Int16Array.name = "Int16Array"); !Int32Array.name && (Int32Array.name = "Int32Array"); !Uint8Array.name && (Uint8Array.name = "Uint8Array"); !Uint16Array.name && (Uint16Array.name = "Uint16Array"); !Uint32Array.name && (Uint32Array.name = "Uint32Array"); !Uint8ClampedArray.name && (Uint8ClampedArray.name = "Uint8ClampedArray"); } catch (e) {} function getTypedArrayName(constructor) { if (constructor === Float32Array) return "Float32Array"; if (constructor === Float64Array) return "Float64Array"; if (constructor === Int8Array) return "Int8Array"; if (constructor === Int16Array) return "Int16Array"; if (constructor === Int32Array) return "Int32Array"; if (constructor === Uint8Array) return "Uint8Array"; if (constructor === Uint16Array) return "Uint16Array"; if (constructor === Uint32Array) return "Uint32Array"; if (constructor === Uint8ClampedArray) return "Uint8ClampedArray"; throw new Error("Unknown TypedArray to instantiate: " + constructor); } function Declaration(varName, expression) { this.varName = varName; this.expression = expression; } Declaration.prototype.toString = function() { return VAR + this.varName + "=" + this.expression + ";"; }; function mergeDeclaration(statement, expression) { return expression instanceof Declaration ? new Declaration(expression.varName, statement + expression.expression) : statement + expression; } function writeAssignment(codeArray, statement, expression) { if (Array.isArray(expression)) { expression[0] = mergeDeclaration(statement, expression[0]); codeArray.push(expression); } else codeArray.push(mergeDeclaration(statement, expression) + ";"); } function Assignments(targetExpression) { this._exps = []; this._targetExp = targetExpression; } Assignments.prototype.append = function(key, expression) { this._exps.push([ key, expression ]); }; Assignments.prototype.writeCode = function(codeArray) { var targetVar; if (this._exps.length > 1) { codeArray.push(LOCAL_TEMP_OBJ + "=" + this._targetExp + ";"); targetVar = LOCAL_TEMP_OBJ; } else { if (1 !== this._exps.length) return; targetVar = this._targetExp; } for (var i = 0; i < this._exps.length; i++) { var pair = this._exps[i]; writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + "=", pair[1]); } }; Assignments.pool = new js.Pool(function(obj) { obj._exps.length = 0; obj._targetExp = null; }, 1); Assignments.pool.get = function(targetExpression) { var cache = this._get() || new Assignments(); cache._targetExp = targetExpression; return cache; }; function equalsToDefault(def, value) { if ("function" === typeof def) try { def = def(); } catch (e) { return false; } if (def === value) return true; if (def && value && "object" === typeof def && "object" === typeof value && def.constructor === value.constructor) if (def instanceof cc.ValueType) { if (def.equals(value)) return true; } else { if (Array.isArray(def)) return 0 === def.length && 0 === value.length; if (def.constructor === Object) return js.isEmptyObject(def) && js.isEmptyObject(value); } return false; } function getPropAccessor(key) { return IDENTIFIER_RE.test(key) ? "." + key : "[" + escapeForJS(key) + "]"; } function Parser(obj, parent) { this.parent = parent; this.objsToClear_iN$t = []; this.codeArray = []; this.objs = []; this.funcs = []; this.funcModuleCache = js.createMap(); js.mixin(this.funcModuleCache, DEFAULT_MODULE_CACHE); this.globalVariables = []; this.globalVariableId = 0; this.localVariableId = 0; this.codeArray.push(VAR + LOCAL_OBJ + "," + LOCAL_TEMP_OBJ + ";", "if(R){", LOCAL_OBJ + "=R;", "}else{", LOCAL_OBJ + "=R=new " + this.getFuncModule(obj.constructor, true) + "();", "}"); js.value(obj, "_iN$t", { globalVar: "R" }, true); this.objsToClear_iN$t.push(obj); this.enumerateObject(this.codeArray, obj); var globalVariablesDeclaration; this.globalVariables.length > 0 && (globalVariablesDeclaration = VAR + this.globalVariables.join(",") + ";"); var code = Compiler.flattenCodeArray([ "return (function(R){", globalVariablesDeclaration || [], this.codeArray, "return o;", "})" ]); this.result = Function("O", "F", code)(this.objs, this.funcs); for (var i = 0, len = this.objsToClear_iN$t.length; i < len; ++i) this.objsToClear_iN$t[i]._iN$t = null; this.objsToClear_iN$t.length = 0; } var proto = Parser.prototype; proto.getFuncModule = function(func, usedInNew) { var clsName = js.getClassName(func); if (clsName) { var cache = this.funcModuleCache[clsName]; if (cache) return cache; if (void 0 === cache) { var clsNameIsModule = -1 !== clsName.indexOf("."); if (clsNameIsModule) try { clsNameIsModule = func === Function("return " + clsName)(); if (clsNameIsModule) { this.funcModuleCache[clsName] = clsName; return clsName; } } catch (e) {} } } var index = this.funcs.indexOf(func); if (index < 0) { index = this.funcs.length; this.funcs.push(func); } var res = "F[" + index + "]"; usedInNew && (res = "(" + res + ")"); this.funcModuleCache[clsName] = res; return res; }; proto.getObjRef = function(obj) { var index = this.objs.indexOf(obj); if (index < 0) { index = this.objs.length; this.objs.push(obj); } return "O[" + index + "]"; }; proto.setValueType = function(codeArray, defaultValue, srcValue, targetExpression) { var assignments = Assignments.pool.get(targetExpression); var fastDefinedProps = defaultValue.constructor.__props__; fastDefinedProps || (fastDefinedProps = Object.keys(defaultValue)); for (var i = 0; i < fastDefinedProps.length; i++) { var propName = fastDefinedProps[i]; var prop = srcValue[propName]; if (defaultValue[propName] === prop) continue; var expression = this.enumerateField(srcValue, propName, prop); assignments.append(propName, expression); } assignments.writeCode(codeArray); Assignments.pool.put(assignments); }; proto.enumerateCCClass = function(codeArray, obj, klass) { var props = klass.__values__; var attrs = Attr.getClassAttrs(klass); for (var p = 0; p < props.length; p++) { var key = props[p]; var val = obj[key]; var defaultValue = attrs[key + DEFAULT]; if (equalsToDefault(defaultValue, val)) continue; if ("object" === typeof val && val instanceof cc.ValueType) { defaultValue = CCClass.getDefault(defaultValue); if (defaultValue && defaultValue.constructor === val.constructor) { var targetExpression = LOCAL_OBJ + getPropAccessor(key); this.setValueType(codeArray, defaultValue, val, targetExpression); continue; } } this.setObjProp(codeArray, obj, key, val); } }; proto.instantiateArray = function(value) { if (0 === value.length) return "[]"; var arrayVar = LOCAL_ARRAY + ++this.localVariableId; var declaration = new Declaration(arrayVar, "new Array(" + value.length + ")"); var codeArray = [ declaration ]; js.value(value, "_iN$t", { globalVar: "", source: codeArray }, true); this.objsToClear_iN$t.push(value); for (var i = 0; i < value.length; ++i) { var statement = arrayVar + "[" + i + "]="; var expression = this.enumerateField(value, i, value[i]); writeAssignment(codeArray, statement, expression); } return codeArray; }; proto.instantiateTypedArray = function(value) { var type = value.constructor.name || getTypedArrayName(value.constructor); if (0 === value.length) return "new " + type; var arrayVar = LOCAL_ARRAY + ++this.localVariableId; var declaration = new Declaration(arrayVar, "new " + type + "(" + value.length + ")"); var codeArray = [ declaration ]; value._iN$t = { globalVar: "", source: codeArray }; this.objsToClear_iN$t.push(value); for (var i = 0; i < value.length; ++i) if (0 !== value[i]) { var statement = arrayVar + "[" + i + "]="; writeAssignment(codeArray, statement, value[i]); } return codeArray; }; proto.enumerateField = function(obj, key, value) { if ("object" === typeof value && value) { var _iN$t = value._iN$t; if (_iN$t) { var globalVar = _iN$t.globalVar; if (!globalVar) { globalVar = _iN$t.globalVar = "v" + ++this.globalVariableId; this.globalVariables.push(globalVar); var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ]; _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + "=", line); } return globalVar; } return ArrayBuffer.isView(value) ? this.instantiateTypedArray(value) : Array.isArray(value) ? this.instantiateArray(value) : this.instantiateObj(value); } if ("function" === typeof value) return this.getFuncModule(value); if ("string" === typeof value) return escapeForJS(value); "_objFlags" === key && obj instanceof CCObject && (value &= PersistentMask); return value; }; proto.setObjProp = function(codeArray, obj, key, value) { var statement = LOCAL_OBJ + getPropAccessor(key) + "="; var expression = this.enumerateField(obj, key, value); writeAssignment(codeArray, statement, expression); }; proto.enumerateObject = function(codeArray, obj) { var klass = obj.constructor; if (cc.Class._isCCClass(klass)) this.enumerateCCClass(codeArray, obj, klass); else for (var key in obj) { if (!obj.hasOwnProperty(key) || 95 === key.charCodeAt(0) && 95 === key.charCodeAt(1) && "__type__" !== key) continue; var value = obj[key]; if ("object" === typeof value && value && value === obj._iN$t) continue; this.setObjProp(codeArray, obj, key, value); } }; proto.instantiateObj = function(obj) { if (obj instanceof cc.ValueType) return CCClass.getNewValueTypeCode(obj); if (obj instanceof cc.Asset) return this.getObjRef(obj); if (obj._objFlags & Destroyed) return null; var createCode; var ctor = obj.constructor; if (cc.Class._isCCClass(ctor)) { if (this.parent) if (this.parent instanceof cc.Component) { if (obj instanceof cc._BaseNode || obj instanceof cc.Component) return this.getObjRef(obj); } else if (this.parent instanceof cc._BaseNode) if (obj instanceof cc._BaseNode) { if (!obj.isChildOf(this.parent)) return this.getObjRef(obj); } else if (obj instanceof cc.Component) { var _obj$node; if (!(null != (_obj$node = obj.node) && _obj$node.isChildOf(this.parent))) return this.getObjRef(obj); } createCode = new Declaration(LOCAL_OBJ, "new " + this.getFuncModule(ctor, true) + "()"); } else if (ctor === Object) createCode = new Declaration(LOCAL_OBJ, "{}"); else { if (ctor) return this.getObjRef(obj); createCode = new Declaration(LOCAL_OBJ, "Object.create(null)"); } var codeArray = [ createCode ]; js.value(obj, "_iN$t", { globalVar: "", source: codeArray }, true); this.objsToClear_iN$t.push(obj); this.enumerateObject(codeArray, obj); return [ "(function(){", codeArray, "return o;})();" ]; }; function compile(node) { var root = node instanceof cc._BaseNode && node; var parser = new Parser(node, root); return parser.result; } module.exports = { compile: compile, equalsToDefault: equalsToDefault }; false; }), { "./CCClass": 129, "./CCObject": 135, "./attribute": 141, "./compiler": 143, "./js": 150 } ], 149: [ (function(require, module, exports) { "use strict"; var CCObject = require("./CCObject"); var CCValueType = require("../value-types/value-type"); var Destroyed = CCObject.Flags.Destroyed; var PersistentMask = CCObject.Flags.PersistentMask; var _isDomNode = require("./utils").isDomNode; var js = require("./js"); function instantiate(original, internal_force) { if (!internal_force) { if ("object" !== typeof original || Array.isArray(original)) { false; return null; } if (!original) { false; return null; } if (!cc.isValid(original)) { false; return null; } false; } var clone; if (original instanceof CCObject) { if (original._instantiate) { cc.game._isCloning = true; clone = original._instantiate(null, true); cc.game._isCloning = false; return clone; } if (original instanceof cc.Asset) { false; return null; } } cc.game._isCloning = true; clone = doInstantiate(original); cc.game._isCloning = false; return clone; } var objsToClearTmpVar = []; function doInstantiate(obj, parent) { if (Array.isArray(obj)) { false; return null; } if (_isDomNode && _isDomNode(obj)) { false; return null; } var clone; if (obj._iN$t) clone = obj._iN$t; else if (obj.constructor) { var klass = obj.constructor; clone = new klass(); } else clone = Object.create(null); enumerateObject(obj, clone, parent); for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) objsToClearTmpVar[i]._iN$t = null; objsToClearTmpVar.length = 0; return clone; } function enumerateCCClass(klass, obj, clone, parent) { var props = klass.__values__; for (var p = 0; p < props.length; p++) { var key = props[p]; var value = obj[key]; if ("object" === typeof value && value) { var initValue = clone[key]; initValue instanceof CCValueType && initValue.constructor === value.constructor ? initValue.set(value) : clone[key] = value._iN$t || instantiateObj(value, parent); } else clone[key] = value; } } function enumerateObject(obj, clone, parent) { js.value(obj, "_iN$t", clone, true); objsToClearTmpVar.push(obj); var klass = obj.constructor; if (cc.Class._isCCClass(klass)) enumerateCCClass(klass, obj, clone, parent); else for (var key in obj) { if (!obj.hasOwnProperty(key) || 95 === key.charCodeAt(0) && 95 === key.charCodeAt(1) && "__type__" !== key) continue; var value = obj[key]; if ("object" === typeof value && value) { if (value === clone) continue; clone[key] = value._iN$t || instantiateObj(value, parent); } else clone[key] = value; } obj instanceof CCObject && (clone._objFlags &= PersistentMask); } function instantiateObj(obj, parent) { if (obj instanceof CCValueType) return obj.clone(); if (obj instanceof cc.Asset) return obj; var clone; if (ArrayBuffer.isView(obj)) { var len = obj.length; clone = new obj.constructor(len); obj._iN$t = clone; objsToClearTmpVar.push(obj); for (var i = 0; i < len; ++i) clone[i] = obj[i]; return clone; } if (Array.isArray(obj)) { var _len = obj.length; clone = new Array(_len); js.value(obj, "_iN$t", clone, true); objsToClearTmpVar.push(obj); for (var _i = 0; _i < _len; ++_i) { var value = obj[_i]; clone[_i] = "object" === typeof value && value ? value._iN$t || instantiateObj(value, parent) : value; } return clone; } if (obj._objFlags & Destroyed) return null; var ctor = obj.constructor; if (cc.Class._isCCClass(ctor)) { if (parent) if (parent instanceof cc.Component) { if (obj instanceof cc._BaseNode || obj instanceof cc.Component) return obj; } else if (parent instanceof cc._BaseNode) if (obj instanceof cc._BaseNode) { if (!obj.isChildOf(parent)) return obj; } else if (obj instanceof cc.Component) { var _obj$node; if (!(null != (_obj$node = obj.node) && _obj$node.isChildOf(parent))) return obj; } clone = new ctor(); } else if (ctor === Object) clone = {}; else { if (ctor) return obj; clone = Object.create(null); } enumerateObject(obj, clone, parent); return clone; } instantiate._clone = doInstantiate; cc.instantiate = instantiate; module.exports = instantiate; }), { "../value-types/value-type": 240, "./CCObject": 135, "./js": 150, "./utils": 153 } ], 150: [ (function(require, module, exports) { "use strict"; var tempCIDGenerater = new (require("./id-generater"))("TmpCId."); function _getPropertyDescriptor(obj, name) { while (obj) { var pd = Object.getOwnPropertyDescriptor(obj, name); if (pd) return pd; obj = Object.getPrototypeOf(obj); } return null; } function _copyprop(name, source, target) { var pd = _getPropertyDescriptor(source, name); Object.defineProperty(target, name, pd); } var js = { isNumber: function isNumber(obj) { return "number" === typeof obj || obj instanceof Number; }, isString: function isString(obj) { return "string" === typeof obj || obj instanceof String; }, addon: function addon(obj) { obj = obj || {}; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; if (source) { if ("object" !== typeof source) { cc.errorID(5402, source); continue; } for (var name in source) name in obj || _copyprop(name, source, obj); } } return obj; }, mixin: function mixin(obj) { obj = obj || {}; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; if (source) { if ("object" !== typeof source) { cc.errorID(5403, source); continue; } for (var name in source) _copyprop(name, source, obj); } } return obj; }, extend: function extend(cls, base) { false; for (var p in base) base.hasOwnProperty(p) && (cls[p] = base[p]); cls.prototype = Object.create(base.prototype, { constructor: { value: cls, writable: true, configurable: true } }); return cls; }, getSuper: function getSuper(ctor) { var proto = ctor.prototype; var dunderProto = proto && Object.getPrototypeOf(proto); return dunderProto && dunderProto.constructor; }, isChildClassOf: function isChildClassOf(subclass, superclass) { if (subclass && superclass) { if ("function" !== typeof subclass) return false; if ("function" !== typeof superclass) { false; return false; } if (subclass === superclass) return true; for (;;) { subclass = js.getSuper(subclass); if (!subclass) return false; if (subclass === superclass) return true; } } return false; }, clear: function clear(obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) delete obj[keys[i]]; }, isEmptyObject: function isEmptyObject(obj) { for (var key in obj) return false; return true; }, getPropertyDescriptor: _getPropertyDescriptor }; var tmpValueDesc = { value: void 0, enumerable: false, writable: false, configurable: true }; js.value = function(obj, prop, value, writable, enumerable) { tmpValueDesc.value = value; tmpValueDesc.writable = writable; tmpValueDesc.enumerable = enumerable; Object.defineProperty(obj, prop, tmpValueDesc); tmpValueDesc.value = void 0; }; var tmpGetSetDesc = { get: null, set: null, enumerable: false }; js.getset = function(obj, prop, getter, setter, enumerable, configurable) { if ("function" !== typeof setter) { enumerable = setter; setter = void 0; } tmpGetSetDesc.get = getter; tmpGetSetDesc.set = setter; tmpGetSetDesc.enumerable = enumerable; tmpGetSetDesc.configurable = configurable; Object.defineProperty(obj, prop, tmpGetSetDesc); tmpGetSetDesc.get = null; tmpGetSetDesc.set = null; }; var tmpGetDesc = { get: null, enumerable: false, configurable: false }; js.get = function(obj, prop, getter, enumerable, configurable) { tmpGetDesc.get = getter; tmpGetDesc.enumerable = enumerable; tmpGetDesc.configurable = configurable; Object.defineProperty(obj, prop, tmpGetDesc); tmpGetDesc.get = null; }; var tmpSetDesc = { set: null, enumerable: false, configurable: false }; js.set = function(obj, prop, setter, enumerable, configurable) { tmpSetDesc.set = setter; tmpSetDesc.enumerable = enumerable; tmpSetDesc.configurable = configurable; Object.defineProperty(obj, prop, tmpSetDesc); tmpSetDesc.set = null; }; js.getClassName = function(objOrCtor) { if ("function" === typeof objOrCtor) { var prototype = objOrCtor.prototype; if (prototype && prototype.hasOwnProperty("__classname__") && prototype.__classname__) return prototype.__classname__; var retval = ""; objOrCtor.name && (retval = objOrCtor.name); if (objOrCtor.toString) { var arr, str = objOrCtor.toString(); arr = "[" === str.charAt(0) ? str.match(/\[\w+\s*(\w+)\]/) : str.match(/function\s*(\w+)/); arr && 2 === arr.length && (retval = arr[1]); } return "Object" !== retval ? retval : ""; } if (objOrCtor && objOrCtor.constructor) return js.getClassName(objOrCtor.constructor); return ""; }; function isTempClassId(id) { return "string" !== typeof id || id.startsWith(tempCIDGenerater.prefix); } (function() { var _idToClass = {}; var _nameToClass = {}; function setup(key, publicName, table) { js.getset(js, publicName, (function() { return Object.assign({}, table); }), (function(value) { js.clear(table); Object.assign(table, value); })); return function(id, constructor) { constructor.prototype.hasOwnProperty(key) && delete table[constructor.prototype[key]]; js.value(constructor.prototype, key, id); if (id) { var registered = table[id]; if (registered && registered !== constructor) { var error = "A Class already exists with the same " + key + ' : "' + id + '".'; false; cc.error(error); } else table[id] = constructor; } }; } js._setClassId = setup("__cid__", "_registeredClassIds", _idToClass); var doSetClassName = setup("__classname__", "_registeredClassNames", _nameToClass); js.setClassName = function(className, constructor) { doSetClassName(className, constructor); if (!constructor.prototype.hasOwnProperty("__cid__")) { var id = className || tempCIDGenerater.getNewId(); id && js._setClassId(id, constructor); } }; js.unregisterClass = function() { for (var i = 0; i < arguments.length; i++) { var p = arguments[i].prototype; var classId = p.__cid__; classId && delete _idToClass[classId]; var classname = p.__classname__; classname && delete _nameToClass[classname]; } }; js._getClassById = function(classId) { return _idToClass[classId]; }; js.getClassByName = function(classname) { return _nameToClass[classname]; }; js._getClassId = function(obj, allowTempId) { allowTempId = "undefined" === typeof allowTempId || allowTempId; var res; if ("function" === typeof obj && obj.prototype.hasOwnProperty("__cid__")) { res = obj.prototype.__cid__; if (!allowTempId && (false, false) && isTempClassId(res)) return ""; return res; } if (obj && obj.constructor) { var prototype = obj.constructor.prototype; if (prototype && prototype.hasOwnProperty("__cid__")) { res = obj.__cid__; if (!allowTempId && (false, false) && isTempClassId(res)) return ""; return res; } } return ""; }; })(); js.obsolete = function(obj, obsoleted, newExpr, writable) { var extractPropName = /([^.]+)$/; var oldProp = extractPropName.exec(obsoleted)[0]; var newProp = extractPropName.exec(newExpr)[0]; function get() { false; return this[newProp]; } writable ? js.getset(obj, oldProp, get, (function(value) { false; this[newProp] = value; })) : js.get(obj, oldProp, get); }; js.obsoletes = function(obj, objName, props, writable) { for (var obsoleted in props) { var newName = props[obsoleted]; js.obsolete(obj, objName + "." + obsoleted, newName, writable); } }; var REGEXP_NUM_OR_STR = /(%d)|(%s)/; var REGEXP_STR = /%s/; js.formatStr = function() { var argLen = arguments.length; if (0 === argLen) return ""; var msg = arguments[0]; if (1 === argLen) return "" + msg; var hasSubstitution = "string" === typeof msg && REGEXP_NUM_OR_STR.test(msg); if (hasSubstitution) for (var i = 1; i < argLen; ++i) { var arg = arguments[i]; var regExpToTest = "number" === typeof arg ? REGEXP_NUM_OR_STR : REGEXP_STR; if (regExpToTest.test(msg)) { var notReplaceFunction = "" + arg; msg = msg.replace(regExpToTest, notReplaceFunction); } else msg += " " + arg; } else for (var _i = 1; _i < argLen; ++_i) msg += " " + arguments[_i]; return msg; }; js.shiftArguments = function() { var len = arguments.length - 1; var args = new Array(len); for (var i = 0; i < len; ++i) args[i] = arguments[i + 1]; return args; }; js.createMap = function(forceDictMode) { var map = Object.create(null); if (forceDictMode) { var INVALID_IDENTIFIER_1 = "."; var INVALID_IDENTIFIER_2 = "/"; map[INVALID_IDENTIFIER_1] = true; map[INVALID_IDENTIFIER_2] = true; delete map[INVALID_IDENTIFIER_1]; delete map[INVALID_IDENTIFIER_2]; } return map; }; function removeAt(array, index) { array.splice(index, 1); } function fastRemoveAt(array, index) { var length = array.length; if (index < 0 || index >= length) return; array[index] = array[length - 1]; array.length = length - 1; } function remove(array, value) { var index = array.indexOf(value); if (index >= 0) { removeAt(array, index); return true; } return false; } function fastRemove(array, value) { var index = array.indexOf(value); if (index >= 0) { array[index] = array[array.length - 1]; --array.length; } } function verifyType(array, type) { if (array && array.length > 0) for (var i = 0; i < array.length; i++) if (!(array[i] instanceof type)) { cc.logID(1300); return false; } return true; } function removeArray(array, minusArr) { for (var i = 0, l = minusArr.length; i < l; i++) remove(array, minusArr[i]); } function appendObjectsAt(array, addObjs, index) { array.splice.apply(array, [ index, 0 ].concat(addObjs)); return array; } function contains(array, value) { return array.indexOf(value) >= 0; } function copy(array) { var i, len = array.length, arr_clone = new Array(len); for (i = 0; i < len; i += 1) arr_clone[i] = array[i]; return arr_clone; } js.array = { remove: remove, fastRemove: fastRemove, removeAt: removeAt, fastRemoveAt: fastRemoveAt, contains: contains, verifyType: verifyType, removeArray: removeArray, appendObjectsAt: appendObjectsAt, copy: copy, MutableForwardIterator: require("../utils/mutable-forward-iterator") }; function Pool(cleanupFunc, size) { if (void 0 === size) { size = cleanupFunc; cleanupFunc = null; } this.get = null; this.count = 0; this._pool = new Array(size); this._cleanup = cleanupFunc; } Pool.prototype._get = function() { if (this.count > 0) { --this.count; var cache = this._pool[this.count]; this._pool[this.count] = null; return cache; } return null; }; Pool.prototype.put = function(obj) { var pool = this._pool; if (this.count < pool.length) { if (this._cleanup && false === this._cleanup(obj)) return; pool[this.count] = obj; ++this.count; } }; Pool.prototype.resize = function(length) { if (length >= 0) { this._pool.length = length; this.count > length && (this.count = length); } }; js.Pool = Pool; cc.js = js; module.exports = js; }), { "../utils/mutable-forward-iterator": 218, "./id-generater": 146 } ], 151: [ (function(require, module, exports) { "use strict"; var js = require("./js"); var Attrs = require("./attribute"); var SerializableAttrs = { default: {}, serializable: {}, editorOnly: {}, formerlySerializedAs: {} }; var TYPO_TO_CORRECT_DEV = false; function parseNotify(val, propName, notify, properties) { if (val.get || val.set) { false; return; } if (val.hasOwnProperty("default")) { var newKey = "_N$" + propName; val.get = function() { return this[newKey]; }; val.set = function(value) { var oldValue = this[newKey]; this[newKey] = value; notify.call(this, oldValue); }; false; var newValue = {}; properties[newKey] = newValue; for (var attr in SerializableAttrs) { var v = SerializableAttrs[attr]; if (val.hasOwnProperty(attr)) { newValue[attr] = val[attr]; v.canUsedInGet || delete val[attr]; } } } else false; } function parseType(val, type, className, propName) { var STATIC_CHECK = (false, false); if (Array.isArray(type)) { if (STATIC_CHECK && "default" in val) { var isArray = require("./CCClass").isArray; isArray(val["default"]) || cc.warnID(5507, className, propName); } if (!(type.length > 0)) return cc.errorID(5508, className, propName); val.type = type = type[0]; } if ("function" === typeof type) { if (type === String) { val.type = cc.String; STATIC_CHECK && cc.warnID(3608, '"' + className + "." + propName + '"'); } else if (type === Boolean) { val.type = cc.Boolean; STATIC_CHECK && cc.warnID(3609, '"' + className + "." + propName + '"'); } else if (type === Number) { val.type = cc.Float; STATIC_CHECK && cc.warnID(3610, '"' + className + "." + propName + '"'); } } else if (STATIC_CHECK) switch (type) { case "Number": cc.warnID(5510, className, propName); break; case "String": cc.warn('The type of "' + className + "." + propName + '" must be cc.String, not "String".'); break; case "Boolean": cc.warn('The type of "' + className + "." + propName + '" must be cc.Boolean, not "Boolean".'); break; case "Float": cc.warn('The type of "' + className + "." + propName + '" must be cc.Float, not "Float".'); break; case "Integer": cc.warn('The type of "' + className + "." + propName + '" must be cc.Integer, not "Integer".'); break; case null: cc.warnID(5511, className, propName); } false; } function getBaseClassWherePropertyDefined_DEV(propName, cls) { var res; false; } function _wrapOptions(isES6Getset, _default, type) { var res = isES6Getset ? { _short: true } : { _short: true, default: _default }; type && (res.type = type); return res; } exports.getFullFormOfProperty = function(options, isES6Getset) { var isLiteral = options && options.constructor === Object; if (isLiteral) return null; return Array.isArray(options) && options.length > 0 ? _wrapOptions(isES6Getset, [], options) : "function" === typeof options ? _wrapOptions(isES6Getset, js.isChildClassOf(options, cc.ValueType) ? new options() : null, options) : options instanceof Attrs.PrimitiveType ? _wrapOptions(isES6Getset, options["default"]) : _wrapOptions(isES6Getset, options); }; exports.preprocessAttrs = function(properties, className, cls, es6) { for (var propName in properties) { var val = properties[propName]; var fullForm = exports.getFullFormOfProperty(val, false); fullForm && (val = properties[propName] = fullForm); if (val) { var maybeTypeScript; false; var baseClass; false; var notify = val.notify; if (notify) { false; parseNotify(val, propName, notify, properties); } "type" in val && parseType(val, val.type, className, propName); } } }; var CALL_SUPER_DESTROY_REG_DEV; false; exports.validateMethodWithProps = function(func, funcName, className, cls, base) { false; if ("function" !== typeof func && null !== func) { var overrided; var baseFuc; var subFuc; var correct; false; return false; } false; return true; }; }), { "./CCClass": 129, "./attribute": 141, "./js": 150 } ], 152: [ (function(require, module, exports) { "use strict"; var requiringFrames = []; cc._RF = { push: function push(module, uuid, script) { if (void 0 === script) { script = uuid; uuid = ""; } requiringFrames.push({ uuid: uuid, script: script, module: module, exports: module.exports, beh: null }); }, pop: function pop() { var frameInfo = requiringFrames.pop(); var module = frameInfo.module; var exports = module.exports; if (exports === frameInfo.exports) { for (var anyKey in exports) return; module.exports = exports = frameInfo.cls; } }, peek: function peek() { return requiringFrames[requiringFrames.length - 1]; } }; false; }), {} ], 153: [ (function(require, module, exports) { "use strict"; var js = require("./js"); module.exports = { contains: function contains(refNode, otherNode) { if ("function" == typeof refNode.contains) return refNode.contains(otherNode); if ("function" == typeof refNode.compareDocumentPosition) return !!(16 & refNode.compareDocumentPosition(otherNode)); var node = otherNode.parentNode; if (node) do { if (node === refNode) return true; node = node.parentNode; } while (null !== node); return false; }, isDomNode: "object" === typeof window && ("function" === typeof Node ? function(obj) { return obj instanceof Node; } : function(obj) { return obj && "object" === typeof obj && "number" === typeof obj.nodeType && "string" === typeof obj.nodeName; }), callInNextTick: function(callback, p1, p2) { callback && setTimeout((function() { callback(p1, p2); }), 0); } }; false; false; }), { "./js": 150 } ], 154: [ (function(require, module, exports) { "use strict"; require("./platform/js"); require("./value-types"); require("./utils"); require("./platform/CCInputManager"); require("./platform/CCInputExtension"); require("./event"); require("./platform/CCSys"); require("./platform/CCMacro"); require("./asset-manager"); require("./CCDirector"); require("./renderer"); true; require("./platform/CCView"); require("./platform/CCScreen"); require("./CCScheduler"); require("./event-manager"); }), { "./CCDirector": 22, "./CCScheduler": 27, "./asset-manager": 45, "./event": 121, "./event-manager": 117, "./platform/CCInputExtension": 132, "./platform/CCInputManager": 133, "./platform/CCMacro": 134, "./platform/CCScreen": 137, "./platform/CCSys": 138, "./platform/CCView": 139, "./platform/js": 150, "./renderer": 160, "./utils": 216, "./value-types": 232 } ], 155: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler = _interopRequireDefault(require("./assembler")); var _manager = _interopRequireDefault(require("./utils/dynamic-atlas/manager")); var _renderData = _interopRequireDefault(require("./webgl/render-data")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _assertThisInitialized(self) { if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Assembler2D = (function(_Assembler) { _inheritsLoose(Assembler2D, _Assembler); function Assembler2D() { var _this; _this = _Assembler.call(this) || this; _this._renderData = new _renderData["default"](); _this._renderData.init(_assertThisInitialized(_this)); _this.initData(); _this.initLocal(); return _this; } var _proto = Assembler2D.prototype; _proto.initData = function initData() { var data = this._renderData; data.createQuadData(0, this.verticesFloats, this.indicesCount); }; _proto.initLocal = function initLocal() { this._local = []; this._local.length = 4; }; _proto.updateColor = function updateColor(comp, color) { var uintVerts = this._renderData.uintVDatas[0]; if (!uintVerts) return; color = null != color ? color : comp.node.color._val; var floatsPerVert = this.floatsPerVert; var colorOffset = this.colorOffset; for (var i = colorOffset, l = uintVerts.length; i < l; i += floatsPerVert) uintVerts[i] = color; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle._meshBuffer; }; _proto.updateWorldVerts = function updateWorldVerts(comp) { var local = this._local; var verts = this._renderData.vDatas[0]; var matrix = comp.node._worldMatrix; var matrixm = matrix.m, a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5], tx = matrixm[12], ty = matrixm[13]; var vl = local[0], vr = local[2], vb = local[1], vt = local[3]; var floatsPerVert = this.floatsPerVert; var vertexOffset = 0; var justTranslate = 1 === a && 0 === b && 0 === c && 1 === d; if (justTranslate) { verts[vertexOffset] = vl + tx; verts[vertexOffset + 1] = vb + ty; vertexOffset += floatsPerVert; verts[vertexOffset] = vr + tx; verts[vertexOffset + 1] = vb + ty; vertexOffset += floatsPerVert; verts[vertexOffset] = vl + tx; verts[vertexOffset + 1] = vt + ty; vertexOffset += floatsPerVert; verts[vertexOffset] = vr + tx; verts[vertexOffset + 1] = vt + ty; } else { var al = a * vl, ar = a * vr, bl = b * vl, br = b * vr, cb = c * vb, ct = c * vt, db = d * vb, dt = d * vt; verts[vertexOffset] = al + cb + tx; verts[vertexOffset + 1] = bl + db + ty; vertexOffset += floatsPerVert; verts[vertexOffset] = ar + cb + tx; verts[vertexOffset + 1] = br + db + ty; vertexOffset += floatsPerVert; verts[vertexOffset] = al + ct + tx; verts[vertexOffset + 1] = bl + dt + ty; vertexOffset += floatsPerVert; verts[vertexOffset] = ar + ct + tx; verts[vertexOffset + 1] = br + dt + ty; } }; _proto.fillBuffers = function fillBuffers(comp, renderer) { renderer.worldMatDirty && this.updateWorldVerts(comp); var renderData = this._renderData; var vData = renderData.vDatas[0]; var iData = renderData.iDatas[0]; var buffer = this.getBuffer(renderer); var offsetInfo = buffer.request(this.verticesCount, this.indicesCount); var vertexOffset = offsetInfo.byteOffset >> 2, vbuf = buffer._vData; vData.length + vertexOffset > vbuf.length ? vbuf.set(vData.subarray(0, vbuf.length - vertexOffset), vertexOffset) : vbuf.set(vData, vertexOffset); var ibuf = buffer._iData, indiceOffset = offsetInfo.indiceOffset, vertexId = offsetInfo.vertexOffset; for (var i = 0, l = iData.length; i < l; i++) ibuf[indiceOffset++] = vertexId + iData[i]; }; _proto.updateTexId = function updateTexId(comp) { var texId = comp._texId; var texIdOffset = this.texIdOffset; var floatsPerVert = this.floatsPerVert; var verts = this._renderData.vDatas[0]; for (var i = 0, l = verts.length; i < l; i++) verts[floatsPerVert * i + texIdOffset] = texId; }; _createClass(Assembler2D, [ { key: "verticesFloats", get: function get() { return this.verticesCount * this.floatsPerVert; } } ]); return Assembler2D; })(_assembler["default"]); exports["default"] = Assembler2D; cc.js.addon(Assembler2D.prototype, { floatsPerVert: 5, verticesCount: 4, indicesCount: 6, uvOffset: 2, colorOffset: 4, isMulti: false }); cc.Assembler2D = Assembler2D; module.exports = exports["default"]; }), { "./assembler": 157, "./utils/dynamic-atlas/manager": 162, "./webgl/render-data": 200 } ], 156: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _pool3 = _interopRequireDefault(require("../utils/pool")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _assemblerId = 0; function getAssemblerId(assemblerCtor) { Object.getOwnPropertyDescriptor(assemblerCtor, "__assemblerId__") || (assemblerCtor.__assemblerId__ = ++_assemblerId); return assemblerCtor.__assemblerId__; } var AssemblerPool = (function(_Pool) { _inheritsLoose(AssemblerPool, _Pool); function AssemblerPool() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; _this = _Pool.call.apply(_Pool, [ this ].concat(args)) || this; _this._pool = {}; return _this; } var _proto = AssemblerPool.prototype; _proto.put = function put(assembler) { if (!assembler) return; if (!this.enabled) { false; return; } var id = getAssemblerId(assembler.constructor); var pool = this._pool; pool[id] || (pool[id] = []); if (this.count > this.maxSize) return; this._clean(assembler); pool[id].push(assembler); this.count++; }; _proto.get = function get(assemblerCtor) { var assembler; if (this.enabled) { var _pool = this._pool; var id = getAssemblerId(assemblerCtor); assembler = _pool[id] && _pool[id].pop(); } assembler ? this.count-- : assembler = new assemblerCtor(); return assembler; }; _proto.clear = function clear() { var _pool2; var name; var assemblers; var i; false; this._pool = {}; this.count = 0; }; _proto._clean = function _clean(assembler) { false; assembler._renderComp = null; }; return AssemblerPool; })(_pool3["default"]); var pool = new AssemblerPool(); _pool3["default"].register("assembler", pool); var _default = pool; exports["default"] = _default; module.exports = exports["default"]; }), { "../utils/pool": 219 } ], 157: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _vertexFormat = require("./webgl/vertex-format"); var _assemblerPool = _interopRequireDefault(require("./assembler-pool")); var _manager = _interopRequireDefault(require("./utils/dynamic-atlas/manager")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Assembler = (function() { function Assembler() { this._extendNative && this._extendNative(); } var _proto = Assembler.prototype; _proto.init = function init(renderComp) { this._renderComp = renderComp; }; _proto.updateRenderData = function updateRenderData(comp) {}; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(comp) {}; _proto.fillBuffers = function fillBuffers(comp, renderer) {}; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColor; }; _proto.packDynamicAtlasAndCheckMaterial = function packDynamicAtlasAndCheckMaterial(comp, frame) { false; var allowDynamicAtlas = comp.allowDynamicAtlas; if ((cc.sp.allowDynamicAtlas && 0 === allowDynamicAtlas || 1 === allowDynamicAtlas) && !frame._original && _manager["default"] && frame._texture.packable && frame._texture.loaded) { var packedFrame = _manager["default"].insertSpriteFrame(frame); packedFrame && frame._setDynamicAtlasFrame(packedFrame); } var material = comp._materials[0]; if (!material) return false; if (this.checkAndSwitchMaterial(comp, frame._texture, material)) return true; if (material.material.isMultiSupport()) comp._texIdDirty = true; else if (material.getProperty("texture") !== frame._texture._texture) { comp._vertsDirty = true; comp._updateMaterial(); } return false; }; _proto.checkAndSwitchMaterial = function checkAndSwitchMaterial(comp, texture, material) { var autoSwitchMaterial = comp.autoSwitchMaterial; if ((cc.sp.autoSwitchMaterial && 0 === autoSwitchMaterial || 1 === autoSwitchMaterial) && texture._multiMaterial && material.material !== texture._multiMaterial) { false; comp.setMaterial(0, texture._multiMaterial); false; if (!this.isMulti) { comp._assembler && comp._assembler.updateRenderDataForSwitchMaterial(comp); return true; } } }; return Assembler; })(); exports["default"] = Assembler; Assembler.register = function(renderCompCtor, assembler) { renderCompCtor.__assembler__ = assembler; }; Assembler.init = function(renderComp) { var renderCompCtor = renderComp.constructor; var assemblerCtor = renderCompCtor.__assembler__; while (!assemblerCtor) { renderCompCtor = renderCompCtor.$super; if (!renderCompCtor) { cc.warn("Can not find assembler for render component : [" + cc.js.getClassName(renderComp) + "]"); return; } assemblerCtor = renderCompCtor.__assembler__; } assemblerCtor.getConstructor && (assemblerCtor = assemblerCtor.getConstructor(renderComp)); if (!renderComp._assembler || renderComp._assembler.constructor !== assemblerCtor) { var assembler = _assemblerPool["default"].get(assemblerCtor); assembler.init(renderComp); renderComp._assembler = assembler; } }; cc.Assembler = Assembler; module.exports = exports["default"]; }), { "./assembler-pool": 156, "./utils/dynamic-atlas/manager": 162, "./webgl/vertex-format": 202 } ], 158: [ (function(require, module, exports) { "use strict"; var Device = function Device(canvasEL) { var ctx; try { ctx = canvasEL.getContext("2d"); } catch (err) { console.error(err); return; } this._canvas = canvasEL; this._ctx = ctx; this._caps = {}; this._stats = { drawcalls: 0 }; this._vx = this._vy = this._vw = this._vh = 0; this._sx = this._sy = this._sw = this._sh = 0; }; Device.prototype._restoreTexture = function _restoreTexture(unit) {}; Device.prototype.setViewport = function setViewport(x, y, w, h) { if (this._vx !== x || this._vy !== y || this._vw !== w || this._vh !== h) { this._vx = x; this._vy = y; this._vw = w; this._vh = h; } }; Device.prototype.setScissor = function setScissor(x, y, w, h) { if (this._sx !== x || this._sy !== y || this._sw !== w || this._sh !== h) { this._sx = x; this._sy = y; this._sw = w; this._sh = h; } }; Device.prototype.clear = function clear(color) { var ctx = this._ctx; ctx.clearRect(this._vx, this._vy, this._vw, this._vh); if (color && (0 !== color[0] || 0 !== color[1] || 0 !== color[2])) { ctx.fillStyle = "rgb(" + color[0] + "," + color[1] + "," + color[2] + ")"; ctx.globalAlpha = color[3]; ctx.fillRect(this._vx, this._vy, this._vw, this._vh); } }; Device.prototype.resetDrawCalls = function() { this._stats.drawcalls = 0; }; Device.prototype.getDrawCalls = function() { return this._stats.drawcalls; }; module.exports = Device; }), {} ], 159: [ (function(require, module, exports) { "use strict"; var Texture2D = function Texture2D(device, options) { this._device = device; this._width = 4; this._height = 4; this._image = null; if (options) { void 0 !== options.width && (this._width = options.width); void 0 !== options.height && (this._height = options.height); this.updateImage(options); } }; Texture2D.prototype.update = function update(options) { this.updateImage(options); }; Texture2D.prototype.updateImage = function updateImage(options) { if (options.images && options.images[0]) { var image = options.images[0]; image && image !== this._image && (this._image = image); } }; Texture2D.prototype.destroy = function destroy() { this._image = null; }; module.exports = Texture2D; }), {} ], 160: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _gfx = _interopRequireDefault(require("../../renderer/gfx")); var _inputAssembler = _interopRequireDefault(require("../../renderer/core/input-assembler")); var _pass = _interopRequireDefault(require("../../renderer/core/pass")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _initBuiltins(device) { var defaultTexture = new _gfx["default"].Texture2D(device, { images: [], width: 128, height: 128, wrapS: _gfx["default"].WRAP_REPEAT, wrapT: _gfx["default"].WRAP_REPEAT, format: _gfx["default"].TEXTURE_FMT_RGB8, genMipmaps: false }); return { defaultTexture: defaultTexture, programTemplates: [], programChunks: {} }; } var _default = cc.renderer = { Texture2D: null, InputAssembler: _inputAssembler["default"], Pass: _pass["default"], renderEngine: null, canvas: null, device: null, scene: null, drawCalls: 0, _handle: null, _cameraNode: null, _camera: null, _forward: null, _flow: null, initWebGL: function initWebGL(canvas, opts) { require("./webgl/assemblers"); var ModelBatcher = require("./webgl/model-batcher"); this.Texture2D = _gfx["default"].Texture2D; this.canvas = canvas; this._flow = cc.RenderFlow; var builtins; var nativeFlow; false; var Scene = require("../../renderer/scene/scene"); var ForwardRenderer = require("../../renderer/renderers/forward-renderer"); this.device = new _gfx["default"].Device(canvas, opts); this.scene = new Scene(); var _builtins = _initBuiltins(this.device); this._forward = new ForwardRenderer(this.device, _builtins); this._handle = new ModelBatcher(this.device, this.scene); this._flow.init(this._handle, this._forward); }, initCanvas: function initCanvas(canvas) { var canvasRenderer = require("./canvas"); var Texture2D = require("./canvas/Texture2D"); var Device = require("./canvas/Device"); this.Device = Device; this.Texture2D = Texture2D; this.canvas = canvas; this.device = new Device(canvas); this._camera = { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 }; this._handle = new canvasRenderer.RenderComponentHandle(this.device, this._camera); this._forward = new canvasRenderer.ForwardRenderer(); this._flow = cc.RenderFlow; this._flow.init(this._handle, this._forward); }, updateCameraViewport: function updateCameraViewport() { if (true, cc.director) { var ecScene = cc.director.getScene(); ecScene && ecScene.setScale(1, 1, 1); } if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { var vp = cc.view.getViewportRect(); this.device.setViewport(vp.x, vp.y, vp.width, vp.height); this._camera.a = cc.view.getScaleX(); this._camera.d = cc.view.getScaleY(); this._camera.tx = vp.x; this._camera.ty = vp.y + vp.height; } }, render: function render(ecScene, dt) { this.device.resetDrawCalls(); if (ecScene) { this._flow.render(ecScene, dt); this.drawCalls = this.device.getDrawCalls(); } }, clear: function clear() { this._handle.reset(); this._forward.clear(); } }; exports["default"] = _default; module.exports = exports["default"]; }), { "../../renderer/core/input-assembler": 249, "../../renderer/core/pass": 250, "../../renderer/gfx": 259, "../../renderer/renderers/forward-renderer": 278, "../../renderer/scene/scene": 281, "./canvas": void 0, "./canvas/Device": 158, "./canvas/Texture2D": 159, "./webgl/assemblers": 172, "./webgl/model-batcher": 198 } ], 161: [ (function(require, module, exports) { "use strict"; var FlagOfset = 0; var DONOTHING = 1 << FlagOfset++; var BREAK_FLOW = 1 << FlagOfset++; var LOCAL_TRANSFORM = 1 << FlagOfset++; var WORLD_TRANSFORM = 1 << FlagOfset++; var TRANSFORM = LOCAL_TRANSFORM | WORLD_TRANSFORM; var UPDATE_RENDER_DATA = 1 << FlagOfset++; var OPACITY = 1 << FlagOfset++; var COLOR = 1 << FlagOfset++; var OPACITY_COLOR = OPACITY | COLOR; var RENDER = 1 << FlagOfset++; var CHILDREN = 1 << FlagOfset++; var POST_RENDER = 1 << FlagOfset++; var FINAL = 1 << FlagOfset++; var _batcher, _forward; var _cullingMask = 0; function RenderFlow() { this._func = init; this._next = null; } var _proto = RenderFlow.prototype; _proto._doNothing = function() {}; _proto._localTransform = function(node) { node._updateLocalMatrix(); node._renderFlag &= ~LOCAL_TRANSFORM; this._next._func(node); }; _proto._worldTransform = function(node) { _batcher.worldMatDirty++; var t = node._matrix; var trs = node._trs; var tm = t.m; tm[12] = trs[0]; tm[13] = trs[1]; tm[14] = trs[2]; node._mulMat(node._worldMatrix, node._parent._worldMatrix, t); node._renderFlag &= ~WORLD_TRANSFORM; this._next._func(node); _batcher.worldMatDirty--; }; _proto._updateRenderData = function(node) { var comp = node._renderComponent; comp._assembler.updateRenderData(comp); node._renderFlag &= ~UPDATE_RENDER_DATA; this._next._func(node); }; _proto._opacity = function(node) { _batcher.parentOpacityDirty++; this._next._func(node); node._renderFlag &= ~OPACITY; _batcher.parentOpacityDirty--; }; _proto._color = function(node) { var comp = node._renderComponent; comp && comp._updateColor(); node._renderFlag &= ~COLOR; this._next._func(node); }; _proto._render = function(node) { var comp = node._renderComponent; comp._checkBacth(_batcher, node._cullingMask); comp._assembler.fillBuffers(comp, _batcher); this._next._func(node); }; _proto._children = function(node) { var cullingMask = _cullingMask; var batcher = _batcher; var parentOpacity = batcher.parentOpacity; var opacity = batcher.parentOpacity *= node._opacity / 255; var worldTransformFlag = batcher.worldMatDirty ? WORLD_TRANSFORM : 0; var worldOpacityFlag = batcher.parentOpacityDirty ? OPACITY_COLOR : 0; var worldDirtyFlag = worldTransformFlag | worldOpacityFlag; var children = node._children; for (var i = 0, l = children.length; i < l; i++) { var c = children[i]; c._renderFlag |= worldDirtyFlag; if (!c._activeInHierarchy || 0 === c._opacity) continue; _cullingMask = c._cullingMask = 0 === c.groupIndex ? cullingMask : 1 << c.groupIndex; var colorVal = c._color._val; c._color._fastSetA(c._opacity * opacity); flows[c._renderFlag]._func(c); c._color._val = colorVal; } batcher.parentOpacity = parentOpacity; this._next._func(node); }; _proto._postRender = function(node) { var comp = node._renderComponent; comp._checkBacth(_batcher, node._cullingMask); comp._assembler.postFillBuffers(comp, _batcher); this._next._func(node); }; var EMPTY_FLOW = new RenderFlow(); EMPTY_FLOW._func = EMPTY_FLOW._doNothing; EMPTY_FLOW._next = EMPTY_FLOW; var flows = {}; function createFlow(flag, next) { if (flag === DONOTHING || flag === BREAK_FLOW) return EMPTY_FLOW; var flow = new RenderFlow(); flow._next = next || EMPTY_FLOW; switch (flag) { case LOCAL_TRANSFORM: flow._func = flow._localTransform; break; case WORLD_TRANSFORM: flow._func = flow._worldTransform; break; case UPDATE_RENDER_DATA: flow._func = flow._updateRenderData; break; case OPACITY: flow._func = flow._opacity; break; case COLOR: flow._func = flow._color; break; case RENDER: flow._func = flow._render; break; case CHILDREN: flow._func = flow._children; break; case POST_RENDER: flow._func = flow._postRender; } return flow; } function getFlow(flag) { var flow = null; var tFlag = FINAL; while (tFlag > 0) { tFlag & flag && (flow = createFlow(tFlag, flow)); tFlag >>= 1; } return flow; } function init(node) { var flag = node._renderFlag; var r = flows[flag] = getFlow(flag); r._func(node); } RenderFlow.flows = flows; RenderFlow.createFlow = createFlow; var _validateList = []; RenderFlow.registerValidate = function(renderComp) { if (renderComp._inValidateList) return; _validateList.push(renderComp); renderComp._inValidateList = true; }; RenderFlow.validateRenderers = function() { for (var i = 0, l = _validateList.length; i < l; i++) { var renderComp = _validateList[i]; if (!renderComp.isValid) continue; renderComp.enabledInHierarchy ? renderComp._validateRender() : renderComp.disableRender(); renderComp._inValidateList = false; } _validateList.length = 0; }; RenderFlow.visitRootNode = function(rootNode) { RenderFlow.validateRenderers(); var preCullingMask = _cullingMask; _cullingMask = rootNode._cullingMask; if (rootNode._renderFlag & WORLD_TRANSFORM) { _batcher.worldMatDirty++; rootNode._calculWorldMatrix(); rootNode._renderFlag &= ~WORLD_TRANSFORM; flows[rootNode._renderFlag]._func(rootNode); _batcher.worldMatDirty--; } else flows[rootNode._renderFlag]._func(rootNode); _cullingMask = preCullingMask; }; RenderFlow.render = function(rootNode, dt) { _batcher.reset(); _batcher.walking = true; RenderFlow.visitRootNode(rootNode); _batcher.terminate(); _batcher.walking = false; _forward.render(_batcher._renderScene, dt); }; RenderFlow.renderCamera = function(camera, rootNode) { _batcher.reset(); _batcher.walking = true; RenderFlow.visitRootNode(rootNode); _batcher.terminate(); _batcher.walking = false; _forward.renderCamera(camera, _batcher._renderScene); }; RenderFlow.init = function(batcher, forwardRenderer) { _batcher = batcher; _forward = forwardRenderer; flows[0] = EMPTY_FLOW; for (var i = 1; i < FINAL; i++) flows[i] = new RenderFlow(); }; RenderFlow.getBachther = function() { return _batcher; }; RenderFlow.FLAG_DONOTHING = DONOTHING; RenderFlow.FLAG_BREAK_FLOW = BREAK_FLOW; RenderFlow.FLAG_LOCAL_TRANSFORM = LOCAL_TRANSFORM; RenderFlow.FLAG_WORLD_TRANSFORM = WORLD_TRANSFORM; RenderFlow.FLAG_TRANSFORM = TRANSFORM; RenderFlow.FLAG_UPDATE_RENDER_DATA = UPDATE_RENDER_DATA; RenderFlow.FLAG_OPACITY = OPACITY; RenderFlow.FLAG_COLOR = COLOR; RenderFlow.FLAG_OPACITY_COLOR = OPACITY_COLOR; RenderFlow.FLAG_RENDER = RENDER; RenderFlow.FLAG_CHILDREN = CHILDREN; RenderFlow.FLAG_POST_RENDER = POST_RENDER; RenderFlow.FLAG_FINAL = FINAL; module.exports = cc.RenderFlow = RenderFlow; }), {} ], 162: [ (function(require, module, exports) { "use strict"; var _reusableAtlas = require("./reusable-atlas"); var _atlases = []; var _atlasIndex = -1; var _maxAtlasCount = -1; var _textureSize = 2048; var _maxFrameSize = 512; var _textureBleeding = true; var _autoMultiBatch = true; var _autoResetBeforeSceneLoad = true; var _debugNode = null; function newAtlas() { var atlas = _atlases[++_atlasIndex]; if (!atlas) { atlas = new _reusableAtlas.Atlas(_textureSize, _textureSize); _atlases.push(atlas); dynamicAtlasManager.autoMultiBatch && cc.sp.multiBatcher.requsetMaterial(atlas._texture); } return atlas; } function beforeSceneLoad() { _autoResetBeforeSceneLoad && dynamicAtlasManager.reset(); } var _enabled = false; var dynamicAtlasManager = { Atlas: _reusableAtlas.Atlas, Rect: _reusableAtlas.Rect, get enabled() { return _enabled; }, set enabled(value) { if (_enabled === value) return; if (value) { this.reset(); cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, beforeSceneLoad); } else cc.director.off(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, beforeSceneLoad); _enabled = value; }, get maxAtlasCount() { return _maxAtlasCount; }, set maxAtlasCount(value) { _maxAtlasCount = value; }, get atlasCount() { return _atlases.length; }, get textureBleeding() { return _textureBleeding; }, set textureBleeding(enable) { _textureBleeding = enable; }, get textureSize() { return _textureSize; }, set textureSize(value) { _textureSize = value; }, get maxFrameSize() { return _maxFrameSize; }, set maxFrameSize(value) { _maxFrameSize = value; }, get autoMultiBatch() { return _autoMultiBatch; }, set autoMultiBatch(enable) { if (_autoMultiBatch === enable) return; if (enable) for (var i = 0, l = _atlases.length; i < l; i++) cc.sp.multiBatcher.requsetMaterial(_atlases[i]._texture); _autoMultiBatch = enable; }, get autoResetBeforeSceneLoad() { return _autoResetBeforeSceneLoad; }, set autoResetBeforeSceneLoad(enable) { if (_autoResetBeforeSceneLoad === enable) return; _autoResetBeforeSceneLoad = enable; }, get atlases() { return _atlases; }, rects: Object.create(null), insertSpriteFrame: function insertSpriteFrame(spriteFrame) { false; if (!_enabled || !spriteFrame || spriteFrame._original) return null; var atlas, frame; var rect = spriteFrame._rect, texture = spriteFrame._texture, info = this.rects[texture._uuid]; var sx = rect.x, sy = rect.y; if (info) { sx += info.x; sy += info.y; info.spriteFrames.push(spriteFrame); frame = { x: sx, y: sy, texture: info.atlas._texture }; return frame; } for (var i = 0; i <= _atlasIndex; i++) { atlas = _atlases[i]; frame = atlas.insertSpriteFrame(spriteFrame); if (frame) return frame; } if (_atlasIndex + 1 < _maxAtlasCount) { atlas = newAtlas(); return atlas.insertSpriteFrame(spriteFrame); } return frame; }, deleteSpriteFrame: function deleteSpriteFrame(spriteFrame) { if (spriteFrame && true && spriteFrame._original) { this.deleteAtlasSpriteFrame(spriteFrame); spriteFrame._resetDynamicAtlasFrame(); } }, deleteTexture: function deleteTexture(texture) { this.deleteAtlasTexture(texture); }, reset: function reset() { for (var i = 0, l = _atlases.length; i < l; i++) _atlases[i].destroy(); _atlases.length = 0; _atlasIndex = -1; }, deleteAtlasSpriteFrame: function deleteAtlasSpriteFrame(spriteFrame) { if (!spriteFrame._original) return; var texture = spriteFrame._original._texture; for (var i = _atlases.length - 1; i >= 0; i--) if (_atlases[i].deleteSpriteFrame(texture, spriteFrame)) return; }, deleteAtlasTexture: function deleteAtlasTexture(texture) { if (texture) for (var i = _atlases.length - 1; i >= 0; i--) if (_atlases[i].deleteInnerTexture(texture, true)) return; }, showDebug: function showDebug(show) { if (show) { if (!_debugNode || !_debugNode.isValid) { var width = cc.visibleRect.width; var height = cc.visibleRect.height; _debugNode = new cc.Node("DYNAMIC_ATLAS_DEBUG_NODE"); _debugNode.width = width; _debugNode.height = height; _debugNode.x = width / 2; _debugNode.y = height / 2; _debugNode.zIndex = cc.macro.MAX_ZINDEX; _debugNode.parent = cc.director.getScene(); _debugNode.groupIndex = cc.Node.BuiltinGroupIndex.DEBUG; cc.Camera._setupDebugCamera(); var scroll = _debugNode.addComponent(cc.ScrollView); var content = new cc.Node("CONTENT"); var layout = content.addComponent(cc.Layout); layout.type = cc.Layout.Type.VERTICAL; layout.resizeMode = cc.Layout.ResizeMode.CONTAINER; content.parent = _debugNode; content.width = _textureSize; content.anchorY = 1; content.x = _textureSize; scroll.content = content; for (var i = 0; i <= _atlasIndex; i++) { var node = new cc.Node("ATLAS"); var texture = _atlases[i]._texture; var spriteFrame = new cc.SpriteFrame(); spriteFrame.setTexture(_atlases[i]._texture); var sprite = node.addComponent(cc.Sprite); sprite.spriteFrame = spriteFrame; node.parent = content; } } return _debugNode; } if (_debugNode) { _debugNode.parent = null; _debugNode = null; } }, update: function update() { if (!this.enabled) return; for (var i = 0; i <= _atlasIndex; i++) _atlases[i].update(); } }; module.exports = cc.dynamicAtlasManager = dynamicAtlasManager; }), { "./reusable-atlas": 163 } ], 163: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.Rect = exports.Atlas = void 0; function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = "undefined" !== typeof Symbol && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && "number" === typeof o.length) { it && (o = it); var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if ("string" === typeof o) return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); "Object" === n && o.constructor && (n = o.constructor.name); if ("Map" === n || "Set" === n) return Array.from(o); if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { (null == len || len > arr.length) && (len = arr.length); for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var RenderTexture = require("../../../assets/CCRenderTexture"); var Rect = (function() { Rect.reuse = function reuse(atlas, width, height, x, y) { if (0 === this.pointer) { for (var i = 0; i < 128; i++) Rect.pool[i] = new Rect(atlas, 0, 0, 0, 0); this.pointer += 128; } this.pointer--; var rect = this.pool[this.pointer]; rect.atlas = atlas; rect.width = width; rect.height = height; rect.x = x; rect.y = y; return rect; }; Rect.recycle = function recycle(rect) { rect.atlas = void 0; rect.uuid = ""; rect.spriteFrames.length = 0; rect.parentRect = void 0; rect.subRectA = void 0; rect.subRectB = void 0; rect.subRectC = void 0; rect.cacheIndex = -1; this.pool[this.pointer] = rect; this.pointer++; }; function Rect(atlas, width, height, x, y) { this.atlas = void 0; this.width = 0; this.height = 0; this.x = 0; this.y = 0; this.cacheIndex = -1; this.uuid = ""; this.spriteFrames = []; this.parentRect = void 0; this.subRectA = void 0; this.subRectB = void 0; this.subRectC = void 0; this.used = 0; this.atlas = atlas; this.width = width; this.height = height; this.x = x; this.y = y; } _createClass(Rect, [ { key: "sizes", get: function get() { return this.width * this.height; } } ]); return Rect; })(); exports.Rect = Rect; Rect.pool = []; Rect.pointer = 0; var Atlas = (function() { function Atlas(width, height, padding, border) { void 0 === padding && (padding = 2); void 0 === border && (border = 2); this.width = 0; this.height = 0; this.padding = 0; this.border = 0; this.rootRect = void 0; this.freeRects = []; this._count = 0; this._texture = void 0; this._dirty = false; var texture = new RenderTexture(); texture.initWithSize(width, height); texture.update(); this._texture = texture; this.width = width; this.height = height; this.padding = padding; this.border = border; this.rootRect = Rect.reuse(this, this.width + this.padding - 2 * this.border, this.height + this.padding - 2 * this.border, this.border, this.border); this.pushFreeRect(this.rootRect); } var _proto = Atlas.prototype; _proto.pushFreeRect = function pushFreeRect(rect) { var i = this.freeRects.push(rect) - 1; rect.cacheIndex = i; }; _proto.removeFreeRect = function removeFreeRect(index) { var temp = this.freeRects[index]; var temp2 = this.freeRects[this.freeRects.length - 1]; temp2.cacheIndex = index; temp.cacheIndex = -1; this.freeRects[index] = temp2; this.freeRects.pop(); }; _proto.replaceFreeRect = function replaceFreeRect(index, rect) { this.freeRects[index].cacheIndex = -1; rect.cacheIndex = index; this.freeRects[index] = rect; }; _proto.insertSpriteFrame = function insertSpriteFrame(spriteFrame) { var rect = spriteFrame._rect, texture = spriteFrame._texture; var sx = rect.x, sy = rect.y; var width = texture.width, height = texture.height; var result = this.insert(texture); if (!result) return null; if (cc.dynamicAtlasManager.textureBleeding) { if (width <= 8 || height <= 8) { this._texture.drawTextureAt(texture, result.x - 1, result.y - 1); this._texture.drawTextureAt(texture, result.x - 1, result.y + 1); this._texture.drawTextureAt(texture, result.x + 1, result.y - 1); this._texture.drawTextureAt(texture, result.x + 1, result.y + 1); } this._texture.drawTextureAt(texture, result.x - 1, result.y); this._texture.drawTextureAt(texture, result.x + 1, result.y); this._texture.drawTextureAt(texture, result.x, result.y - 1); this._texture.drawTextureAt(texture, result.x, result.y + 1); } this._texture.drawTextureAt(texture, result.x, result.y); this._count++; sx += result.x; sy += result.y; result.spriteFrames.push(spriteFrame); this._dirty = true; var frame = { x: sx, y: sy, texture: this._texture }; return frame; }; _proto.insert = function insert(texture) { var width = texture.width + this.padding, height = texture.height + this.padding; var score = Number.MAX_VALUE; var areaFit = 0; var original = void 0; var originalIndex = 0; for (var i = 0; i < this.freeRects.length; i++) { var rect = this.freeRects[i]; if (rect.width >= width && rect.height >= height) { areaFit = rect.sizes - width * height; if (areaFit < score) { original = rect; originalIndex = i; score = areaFit; } } } if (original) { if (original.width === width && original.height === height) { original.uuid = texture._uuid; original.used++; original.parentRect && original.parentRect.used++; cc.dynamicAtlasManager.rects[texture._uuid] = original; this.removeFreeRect(originalIndex); return original; } var best = Rect.reuse(this, width, height, original.x, original.y); var tmp; if (best.y + best.height < original.y + original.height) { tmp = Rect.reuse(this, original.width, original.y + original.height - (best.y + best.height), original.x, best.y + best.height); tmp.parentRect = original; original.subRectB = tmp; if (tmp.width > Atlas.ignoreRectSize && tmp.height > Atlas.ignoreRectSize) { this.replaceFreeRect(originalIndex, tmp); originalIndex = -1; } } if (best.x + best.width < original.x + original.width) { tmp = Rect.reuse(this, original.x + original.width - (best.x + best.width), original.height - (original.y + original.height - (best.y + best.height)), best.x + best.width, original.y); tmp.parentRect = original; original.subRectC = tmp; if (tmp.width > Atlas.ignoreRectSize && tmp.height > Atlas.ignoreRectSize) if (-1 !== originalIndex) { this.replaceFreeRect(originalIndex, tmp); originalIndex = -1; } else this.pushFreeRect(tmp); } -1 !== originalIndex && this.removeFreeRect(originalIndex); best.parentRect = original; original.subRectA = best; best.used++; original.used++; 1 === original.used && original.parentRect && original.parentRect.used++; best.uuid = texture._uuid; cc.dynamicAtlasManager.rects[texture._uuid] = best; return best; } return; }; _proto.update = function update() { if (!this._dirty) return; this._texture.update(); this._dirty = false; }; _proto.deleteSpriteFrame = function deleteSpriteFrame(texture, frame) { if (texture) { var rect = cc.dynamicAtlasManager.rects[texture._uuid]; if (rect) { var index = rect.spriteFrames.indexOf(frame); if (-1 !== index) { rect.spriteFrames.splice(index, 1); 0 === rect.spriteFrames.length && rect.atlas.deleteInnerRect(rect); } else cc.warn("[Dynamic Atlas] can't find spriteFrame in Rect."); return true; } } return false; }; _proto.deleteInnerRect = function deleteInnerRect(rect) { delete cc.dynamicAtlasManager.rects[rect.uuid]; rect.uuid = ""; this._count--; for (var _iterator = _createForOfIteratorHelperLoose(rect.spriteFrames), _step; !(_step = _iterator()).done; ) { var spriteFrame = _step.value; spriteFrame.isValid && spriteFrame._resetDynamicAtlasFrame(); } rect.spriteFrames.length = 0; this.tryMergeRecycle(rect); }; _proto.deleteInnerTexture = function deleteInnerTexture(texture) { if (texture) { var rect = cc.dynamicAtlasManager.rects[texture._uuid]; if (rect) { rect.atlas.deleteInnerRect(rect); return true; } } return false; }; _proto.tryMergeRecycle = function tryMergeRecycle(rect) { var old = void 0; var parent = rect; while (parent) { parent.used--; if (0 === parent.used) { if (parent.subRectA) { var i = parent.subRectA.cacheIndex; -1 !== i && this.removeFreeRect(i); Rect.recycle(parent.subRectA); parent.subRectA = void 0; } if (parent.subRectB) { var _i = parent.subRectB.cacheIndex; -1 !== _i && this.removeFreeRect(_i); Rect.recycle(parent.subRectB); parent.subRectB = void 0; } if (parent.subRectC) { var _i2 = parent.subRectC.cacheIndex; -1 !== _i2 && this.removeFreeRect(_i2); Rect.recycle(parent.subRectC); parent.subRectC = void 0; } old = parent; parent = parent.parentRect; } else { old && old.width > Atlas.ignoreRectSize && old.height > Atlas.ignoreRectSize && this.pushFreeRect(old); old = parent; parent = void 0; } } old === this.rootRect && 0 === old.used && this.pushFreeRect(old); }; _proto.isEmpty = function isEmpty() { return this._count <= 0; }; _proto.reset = function reset() { var rects = cc.dynamicAtlasManager.rects; for (var key in rects) { var rect = rects[key]; if (rect.atlas === this) { delete rects[key]; for (var _iterator2 = _createForOfIteratorHelperLoose(rect.spriteFrames), _step2; !(_step2 = _iterator2()).done; ) { var spriteFrame = _step2.value; spriteFrame.isValid && spriteFrame._resetDynamicAtlasFrame(); } Rect.recycle(rect); } } for (var _iterator3 = _createForOfIteratorHelperLoose(this.freeRects), _step3; !(_step3 = _iterator3()).done; ) { var _rect = _step3.value; Rect.recycle(_rect); } this.freeRects.length = 0; this._count = 0; this.rootRect = Rect.reuse(this, this.width + this.padding - 2 * this.border, this.height + this.padding - 2 * this.border, this.border, this.border); this.pushFreeRect(this.rootRect); }; _proto.destroy = function destroy() { this.reset(); this._texture.destroy(); }; return Atlas; })(); exports.Atlas = Atlas; Atlas.ignoreRectSize = 10; Atlas.DEFAULT_HASH = new RenderTexture()._getHash(); }), { "../../../assets/CCRenderTexture": 65 } ], 164: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var textUtils = require("../../../utils/text-utils"); var macro = require("../../../platform/CCMacro"); var Label = require("../../../components/CCLabel"); var Overflow = Label.Overflow; var shareLabelInfo = require("../utils").shareLabelInfo; var LetterInfo = function LetterInfo() { this["char"] = ""; this.valid = true; this.x = 0; this.y = 0; this.line = 0; this.hash = ""; }; var _tmpRect = cc.rect(); var _comp = null; var _horizontalKernings = []; var _lettersInfo = []; var _linesWidth = []; var _linesOffsetX = []; var _fntConfig = null; var _numberOfLines = 0; var _textDesiredHeight = 0; var _letterOffsetY = 0; var _tailoredTopY = 0; var _tailoredBottomY = 0; var _bmfontScale = 1; var _lineBreakWithoutSpaces = false; var _spriteFrame = null; var _lineSpacing = 0; var _contentSize = cc.size(); var _string = ""; var _fontSize = 0; var _originFontSize = 0; var _hAlign = 0; var _vAlign = 0; var _spacingX = 0; var _lineHeight = 0; var _overflow = 0; var _isWrapText = false; var _labelWidth = 0; var _labelHeight = 0; var _maxLineWidth = 0; var _isRetina = false; var _retinaScale = 1; var BmfontAssembler = (function(_Assembler2D) { _inheritsLoose(BmfontAssembler, _Assembler2D); function BmfontAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = BmfontAssembler.prototype; _proto.updateRenderData = function updateRenderData(comp) { if (!comp._vertsDirty) return; if (_comp === comp) return; _comp = comp; this._reserveQuads(comp, comp.string.toString().length); var assemblerChanged = this._updateFontFamily(comp); assemblerChanged || this._aftUpdateRenderData(comp); return assemblerChanged; }; _proto._preUpdateRenderData = function _preUpdateRenderData(comp) { _comp = comp; this._reserveQuads(comp, comp.string.toString().length); var fontAsset = comp.font; _spriteFrame = fontAsset.spriteFrame; _fntConfig = fontAsset._fntConfig; shareLabelInfo.fontAtlas = fontAsset._fontDefDictionary; }; _proto._aftUpdateRenderData = function _aftUpdateRenderData(comp) { this._updateProperties(comp); this._updateLabelInfo(comp); this._updateContent(); this.updateWorldVerts(comp); if (_isRetina) { _contentSize.width /= _retinaScale; _contentSize.height /= _retinaScale; _fontSize /= _retinaScale; } _comp._actualFontSize = _fontSize; _comp.node.setContentSize(_contentSize); _comp._vertsDirty = false; _comp = null; this._resetProperties(); }; _proto._updateFontScale = function _updateFontScale() { _bmfontScale = _fontSize / _originFontSize; }; _proto._updateFontFamily = function _updateFontFamily(comp) { var fontAsset = comp.font; _spriteFrame = fontAsset.spriteFrame; _fntConfig = fontAsset._fntConfig; shareLabelInfo.fontAtlas = fontAsset._fontDefDictionary; return this.packDynamicAtlasAndCheckMaterial(comp, _spriteFrame); }; _proto._updateLabelInfo = function _updateLabelInfo() { shareLabelInfo.hash = ""; shareLabelInfo.margin = 0; }; _proto.getTTFTextureSizeScale = function getTTFTextureSizeScale() { return _isRetina ? _retinaScale : 1; }; _proto._updateProperties = function _updateProperties(comp) { _string = comp.string.toString(); _isRetina = !(comp.font instanceof cc.BitmapFont) && cc.sp.enableLabelRetina && 0 === comp.enableRetina || 1 === comp.enableRetina; _retinaScale = cc.sp.labelRetinaScale; _fontSize = comp.fontSize; _originFontSize = _fntConfig ? _fntConfig.fontSize : comp.fontSize; _hAlign = comp.horizontalAlign; _vAlign = comp.verticalAlign; _spacingX = comp.spacingX; _overflow = comp.overflow; _lineHeight = comp._lineHeight; _contentSize.width = comp.node.width; _contentSize.height = comp.node.height; if (_isRetina) { _fontSize *= _retinaScale; _fntConfig || (_originFontSize *= _retinaScale); _contentSize.width *= _retinaScale; _contentSize.height *= _retinaScale; _lineHeight *= _retinaScale; shareLabelInfo.margin *= _retinaScale; } if (_overflow === Overflow.NONE) { _isWrapText = false; _contentSize.width += 2 * shareLabelInfo.margin; _contentSize.height += 2 * shareLabelInfo.margin; } else if (_overflow === Overflow.RESIZE_HEIGHT) { _isWrapText = true; _contentSize.height += 2 * shareLabelInfo.margin; } else _isWrapText = comp.enableWrapText; shareLabelInfo.lineHeight = _lineHeight; shareLabelInfo.fontSize = _fontSize; this._setupBMFontOverflowMetrics(); }; _proto._resetProperties = function _resetProperties() { _fntConfig = null; _spriteFrame = null; shareLabelInfo.hash = ""; shareLabelInfo.margin = 0; }; _proto._updateContent = function _updateContent() { this._updateFontScale(); this._computeHorizontalKerningForText(); this._alignText(); }; _proto._computeHorizontalKerningForText = function _computeHorizontalKerningForText() { var string = _string; var stringLen = string.length; var horizontalKernings = _horizontalKernings; var kerningDict; _fntConfig && (kerningDict = _fntConfig.kerningDict); if (kerningDict && !cc.js.isEmptyObject(kerningDict)) { var prev = -1; for (var i = 0; i < stringLen; ++i) { var key = string.charCodeAt(i); var kerningAmount = kerningDict[prev << 16 | 65535 & key] || 0; horizontalKernings[i] = i < stringLen - 1 ? kerningAmount : 0; prev = key; } } else horizontalKernings.length = 0; }; _proto._multilineTextWrap = function _multilineTextWrap(nextTokenFunc) { var textLen = _string.length; var lineIndex = 0; var nextTokenX = 0; var nextTokenY = 0; var longestLine = 0; var letterRight = 0; var highestY = 0; var lowestY = 0; var letterDef = null; var letterPosition = cc.v2(0, 0); for (var index = 0; index < textLen; ) { var character = _string.charAt(index); if ("\n" === character) { _linesWidth.push(letterRight); letterRight = 0; lineIndex++; nextTokenX = 0; nextTokenY -= _lineHeight * this._getFontScale() + _lineSpacing; this._recordPlaceholderInfo(index, character); index++; continue; } var tokenLen = nextTokenFunc(_string, index, textLen); var tokenHighestY = highestY; var tokenLowestY = lowestY; var tokenRight = letterRight; var nextLetterX = nextTokenX; var newLine = false; for (var tmp = 0; tmp < tokenLen; ++tmp) { var letterIndex = index + tmp; character = _string.charAt(letterIndex); if ("\r" === character) { this._recordPlaceholderInfo(letterIndex, character); continue; } letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo); if (!letterDef) { this._recordPlaceholderInfo(letterIndex, character); var atlasName = ""; _fntConfig && (atlasName = _fntConfig.atlasName); console.log("Can't find letter definition in texture atlas " + atlasName + " for letter:" + character); continue; } var letterX = nextLetterX + letterDef.offsetX * _bmfontScale - shareLabelInfo.margin; if (_isWrapText && _maxLineWidth > 0 && nextTokenX > 0 && letterX + letterDef.w * _bmfontScale > _maxLineWidth && !textUtils.isUnicodeSpace(character)) { _linesWidth.push(letterRight); letterRight = 0; lineIndex++; nextTokenX = 0; nextTokenY -= _lineHeight * this._getFontScale() + _lineSpacing; newLine = true; break; } letterPosition.x = letterX; letterPosition.y = nextTokenY - letterDef.offsetY * _bmfontScale + shareLabelInfo.margin; this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex); letterIndex + 1 < _horizontalKernings.length && letterIndex < textLen - 1 && (nextLetterX += _horizontalKernings[letterIndex + 1]); nextLetterX += letterDef.xAdvance * _bmfontScale + _spacingX - 2 * shareLabelInfo.margin; tokenRight = letterPosition.x + letterDef.w * _bmfontScale - shareLabelInfo.margin; tokenHighestY < letterPosition.y && (tokenHighestY = letterPosition.y); tokenLowestY > letterPosition.y - letterDef.h * _bmfontScale && (tokenLowestY = letterPosition.y - letterDef.h * _bmfontScale); } if (newLine) continue; nextTokenX = nextLetterX; letterRight = tokenRight; highestY < tokenHighestY && (highestY = tokenHighestY); lowestY > tokenLowestY && (lowestY = tokenLowestY); longestLine < letterRight && (longestLine = letterRight); index += tokenLen; } this._finishMultilineTextWrap(); _linesWidth.push(letterRight); _numberOfLines = lineIndex + 1; _textDesiredHeight = _numberOfLines * _lineHeight * this._getFontScale(); _numberOfLines > 1 && (_textDesiredHeight += (_numberOfLines - 1) * _lineSpacing); _contentSize.width = _labelWidth; _contentSize.height = _labelHeight; _labelWidth <= 0 && (_contentSize.width = parseFloat(longestLine.toFixed(2)) + 2 * shareLabelInfo.margin); _labelHeight <= 0 && (_contentSize.height = parseFloat(_textDesiredHeight.toFixed(2)) + 2 * shareLabelInfo.margin); _tailoredTopY = _contentSize.height; _tailoredBottomY = 0; if (_overflow !== Overflow.CLAMP) { highestY > 0 && (_tailoredTopY = _contentSize.height + highestY); lowestY < -_textDesiredHeight && (_tailoredBottomY = _textDesiredHeight + lowestY); } return true; }; _proto._getFirstCharLen = function _getFirstCharLen() { return 1; }; _proto._getFontScale = function _getFontScale() { return _overflow === Overflow.SHRINK ? _bmfontScale : 1; }; _proto._getFirstWordLen = function _getFirstWordLen(text, startIndex, textLen) { var character = text.charAt(startIndex); if (textUtils.isUnicodeCJK(character) || "\n" === character || textUtils.isUnicodeSpace(character)) return 1; var len = 1; var letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo); if (!letterDef) return len; var nextLetterX = letterDef.xAdvance * _bmfontScale + _spacingX; var letterX; for (var index = startIndex + 1; index < textLen; ++index) { character = text.charAt(index); letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo); if (!letterDef) break; letterX = nextLetterX + letterDef.offsetX * _bmfontScale; if (letterX + letterDef.w * _bmfontScale > _maxLineWidth && !textUtils.isUnicodeSpace(character) && _maxLineWidth > 0) return len; nextLetterX += letterDef.xAdvance * _bmfontScale + _spacingX; if ("\n" === character || textUtils.isUnicodeSpace(character) || textUtils.isUnicodeCJK(character)) break; len++; } return len; }; _proto._multilineTextWrapByWord = function _multilineTextWrapByWord() { return this._multilineTextWrap(this._getFirstWordLen); }; _proto._multilineTextWrapByChar = function _multilineTextWrapByChar() { return this._multilineTextWrap(this._getFirstCharLen); }; _proto._recordPlaceholderInfo = function _recordPlaceholderInfo(letterIndex, _char) { if (letterIndex >= _lettersInfo.length) { var tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); } _lettersInfo[letterIndex]["char"] = _char; _lettersInfo[letterIndex].hash = _char.charCodeAt(0) + shareLabelInfo.hash; _lettersInfo[letterIndex].valid = false; }; _proto._recordLetterInfo = function _recordLetterInfo(letterPosition, character, letterIndex, lineIndex) { if (letterIndex >= _lettersInfo.length) { var tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); } var _char2 = character.charCodeAt(0); var key = _char2 + shareLabelInfo.hash; _lettersInfo[letterIndex].line = lineIndex; _lettersInfo[letterIndex]["char"] = character; _lettersInfo[letterIndex].hash = key; _lettersInfo[letterIndex].valid = shareLabelInfo.fontAtlas.getLetter(key).valid; _lettersInfo[letterIndex].x = letterPosition.x; _lettersInfo[letterIndex].y = letterPosition.y; }; _proto._alignText = function _alignText() { _textDesiredHeight = 0; _linesWidth.length = 0; _lineBreakWithoutSpaces ? this._multilineTextWrapByChar() : this._multilineTextWrapByWord(); this._computeAlignmentOffset(); _overflow === Overflow.SHRINK && _fontSize > 0 && this._isVerticalClamp() && this._shrinkLabelToContentSize(this._isVerticalClamp); this._updateQuads() || _overflow === Overflow.SHRINK && this._shrinkLabelToContentSize(this._isHorizontalClamp); }; _proto._scaleFontSizeDown = function _scaleFontSizeDown(fontSize) { var shouldUpdateContent = true; if (!fontSize) { fontSize = .1; shouldUpdateContent = false; } _fontSize = fontSize; shouldUpdateContent && this._updateContent(); }; _proto._shrinkLabelToContentSize = function _shrinkLabelToContentSize(lambda) { var fontSize = _fontSize; var left = 0, right = 0 | fontSize, mid = 0; while (left < right) { mid = left + right + 1 >> 1; var newFontSize = mid; if (newFontSize <= 0) break; _bmfontScale = newFontSize / _originFontSize; _lineBreakWithoutSpaces ? this._multilineTextWrapByChar() : this._multilineTextWrapByWord(); this._computeAlignmentOffset(); lambda() ? right = mid - 1 : left = mid; } var actualFontSize = left; actualFontSize >= 0 && this._scaleFontSizeDown(actualFontSize); }; _proto._isVerticalClamp = function _isVerticalClamp() { return _textDesiredHeight > _contentSize.height; }; _proto._isHorizontalClamp = function _isHorizontalClamp() { var letterClamp = false; for (var ctr = 0, l = _string.length; ctr < l; ++ctr) { var letterInfo = _lettersInfo[ctr]; if (letterInfo.valid) { var letterDef = shareLabelInfo.fontAtlas.getLetter(letterInfo.hash); var px = letterInfo.x + letterDef.w * _bmfontScale; var lineIndex = letterInfo.line; if (_labelWidth > 0) if (_isWrapText) { var wordWidth = _linesWidth[lineIndex]; if (wordWidth > _contentSize.width && (px > _contentSize.width || px < 0)) { letterClamp = true; break; } } else if (px > _contentSize.width) { letterClamp = true; break; } } } return letterClamp; }; _proto._isHorizontalClamped = function _isHorizontalClamped(px, lineIndex) { var wordWidth = _linesWidth[lineIndex]; var letterOverClamp = px > _contentSize.width || px < 0; return _isWrapText ? wordWidth > _contentSize.width && letterOverClamp : letterOverClamp; }; _proto._updateQuads = function _updateQuads() { var texture = _spriteFrame ? _spriteFrame._texture : shareLabelInfo.fontAtlas.getTexture(); var node = _comp.node; this.verticesCount = this.indicesCount = 0; this._renderData && (this._renderData.dataLength = 0); var contentSize = _contentSize, appx = node._anchorPoint.x * contentSize.width, appy = node._anchorPoint.y * contentSize.height; var ret = true; for (var ctr = 0, l = _string.length; ctr < l; ++ctr) { var letterInfo = _lettersInfo[ctr]; if (!letterInfo.valid) continue; var letterDef = shareLabelInfo.fontAtlas.getLetter(letterInfo.hash); _tmpRect.height = letterDef.h; _tmpRect.width = letterDef.w; _tmpRect.x = letterDef.u; _tmpRect.y = letterDef.v; var py = letterInfo.y + _letterOffsetY; if (_labelHeight > 0) { if (py > _tailoredTopY) { var clipTop = py - _tailoredTopY; _tmpRect.y += clipTop; _tmpRect.height -= clipTop; py -= clipTop; } py - letterDef.h * _bmfontScale < _tailoredBottomY && _overflow === Overflow.CLAMP && (_tmpRect.height = py < _tailoredBottomY ? 0 : (py - _tailoredBottomY) / _bmfontScale); } var lineIndex = letterInfo.line; var px = letterInfo.x + letterDef.w / 2 * _bmfontScale + _linesOffsetX[lineIndex]; if (_labelWidth > 0 && this._isHorizontalClamped(px, lineIndex)) if (_overflow === Overflow.CLAMP) _tmpRect.width = 0; else if (_overflow === Overflow.SHRINK) { if (_contentSize.width > letterDef.w) { ret = false; break; } _tmpRect.width = 0; } if (_tmpRect.height > 0 && _tmpRect.width > 0) { var isRotated = this._determineRect(_tmpRect); var letterPositionX = letterInfo.x + _linesOffsetX[letterInfo.line]; this.appendQuad(_comp, texture, _tmpRect, isRotated, letterPositionX - appx, py - appy, _bmfontScale, letterDef); } } this._quadsUpdated(_comp); return ret; }; _proto._determineRect = function _determineRect(tempRect) { var isRotated = _spriteFrame.isRotated(); var originalSize = _spriteFrame._originalSize; var rect = _spriteFrame._rect; var offset = _spriteFrame._offset; var trimmedLeft = offset.x + (originalSize.width - rect.width) / 2; var trimmedTop = offset.y - (originalSize.height - rect.height) / 2; if (isRotated) { var originalX = tempRect.x; tempRect.x = rect.x + rect.height - tempRect.y - tempRect.height - trimmedTop; tempRect.y = originalX + rect.y - trimmedLeft; tempRect.y < 0 && (tempRect.height = tempRect.height + trimmedTop); } else { tempRect.x += rect.x - trimmedLeft; tempRect.y += rect.y + trimmedTop; } return isRotated; }; _proto._computeAlignmentOffset = function _computeAlignmentOffset() { _linesOffsetX.length = 0; switch (_hAlign) { case macro.TextAlignment.LEFT: for (var i = 0; i < _numberOfLines; ++i) _linesOffsetX.push(0); break; case macro.TextAlignment.CENTER: for (var _i = 0, l = _linesWidth.length; _i < l; _i++) _linesOffsetX.push((_contentSize.width - _linesWidth[_i]) / 2); break; case macro.TextAlignment.RIGHT: for (var _i2 = 0, _l = _linesWidth.length; _i2 < _l; _i2++) _linesOffsetX.push(_contentSize.width - _linesWidth[_i2]); } _letterOffsetY = _contentSize.height; if (_vAlign !== macro.VerticalTextAlignment.TOP) { var blank = _contentSize.height - _textDesiredHeight + _lineHeight * this._getFontScale() - _originFontSize * _bmfontScale; _vAlign === macro.VerticalTextAlignment.BOTTOM ? _letterOffsetY -= blank : _letterOffsetY -= blank / 2; } }; _proto._setupBMFontOverflowMetrics = function _setupBMFontOverflowMetrics() { var newWidth = _contentSize.width, newHeight = _contentSize.height; _overflow === Overflow.RESIZE_HEIGHT && (newHeight = 0); if (_overflow === Overflow.NONE) { newWidth = 0; newHeight = 0; } _labelWidth = newWidth; _labelHeight = newHeight; _maxLineWidth = newWidth; }; _proto.updateWorldVerts = function updateWorldVerts() {}; _proto.appendQuad = function appendQuad(comp, texture, rect, rotated, x, y, scale, letter) {}; _proto._quadsUpdated = function _quadsUpdated(comp) {}; _proto._reserveQuads = function _reserveQuads() {}; _proto._finishMultilineTextWrap = function _finishMultilineTextWrap() {}; return BmfontAssembler; })(_assembler2d["default"]); exports["default"] = BmfontAssembler; module.exports = exports["default"]; }), { "../../../components/CCLabel": 94, "../../../platform/CCMacro": 134, "../../../utils/text-utils": 224, "../../assembler-2d": 155, "../utils": 168 } ], 165: [ (function(require, module, exports) { "use strict"; function LabelFrame() { this._rect = null; this.uv = []; this._texture = null; this._original = null; } LabelFrame.prototype = { constructor: LabelFrame, getRect: function getRect() { return cc.rect(this._rect); }, setRect: function setRect(rect) { this._rect = rect; this._texture && this._calculateUV(); }, _setDynamicAtlasFrame: function _setDynamicAtlasFrame(frame) { if (!frame) return; this._original = { _texture: this._texture, _x: this._rect.x, _y: this._rect.y }; this._texture = frame.texture; this._rect.x = frame.x; this._rect.y = frame.y; this._calculateUV(); }, _resetDynamicAtlasFrame: function _resetDynamicAtlasFrame() { if (!this._original) return; this._rect.x = this._original._x; this._rect.y = this._original._y; this._texture = this._original._texture; this._original = null; this._calculateUV(); }, _refreshTexture: function _refreshTexture(texture) { this._texture = texture; this._rect = cc.rect(0, 0, texture.width, texture.height); this._calculateUV(); }, _calculateUV: function _calculateUV() { var rect = this._rect, texture = this._texture, uv = this.uv, texw = texture.width, texh = texture.height; var l = 0 === texw ? 0 : rect.x / texw; var r = 0 === texw ? 0 : (rect.x + rect.width) / texw; var b = 0 === texh ? 0 : (rect.y + rect.height) / texh; var t = 0 === texh ? 0 : rect.y / texh; uv[0] = l; uv[1] = b; uv[2] = r; uv[3] = b; uv[4] = l; uv[5] = t; uv[6] = r; uv[7] = t; } }; module.exports = LabelFrame; }), {} ], 166: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _bmfont = _interopRequireDefault(require("../../webgl/assemblers/label/2d/bmfont")); var _vertexFormat = require("../../webgl/vertex-format"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = "undefined" !== typeof Symbol && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && "number" === typeof o.length) { it && (o = it); var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if ("string" === typeof o) return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); "Object" === n && o.constructor && (n = o.constructor.name); if ("Map" === n || "Set" === n) return Array.from(o); if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { (null == len || len > arr.length) && (len = arr.length); for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var Label = require("../../../components/CCLabel"); var LabelOutline = require("../../../components/CCLabelOutline"); var textUtils = require("../../../utils/text-utils"); var Component = require("../../../components/CCComponent"); var RenderTexture = require("../../../assets/CCRenderTexture"); var OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component); var getFontFamily = require("../utils").getFontFamily; var shareLabelInfo = require("../utils").shareLabelInfo; var FontLetterDefinition = cc.BitmapFont.FontLetterDefinition; var FontAtlas = cc.BitmapFont.FontAtlas; var WHITE = cc.Color.WHITE; var space = 0; var bleed = 2; var _invisibleAlpha = (1 / 255).toFixed(3); function LetterTexture(_char, labelInfo) { this._texture = null; this._labelInfo = labelInfo; this._char = _char; this._hash = null; this._data = null; this._canvas = null; this._context = null; this._width = 0; this._height = 0; this._offsetY = 0; this._hash = _char.charCodeAt(0) + labelInfo.hash; } LetterTexture.prototype = { constructor: LetterTexture, updateRenderData: function updateRenderData() { this._updateProperties(); this._updateTexture(); }, _updateProperties: function _updateProperties() { this._texture = new cc.Texture2D(); this._data = Label._canvasPool.get(); this._canvas = this._data.canvas; this._context = this._data.context; this._context.font = this._labelInfo.fontDesc; var width = textUtils.safeMeasureText(this._context, this._char, this._labelInfo.fontDesc); var blank = 2 * this._labelInfo.margin + bleed; this._width = parseFloat(width.toFixed(2)) + blank; this._height = (1 + textUtils.BASELINE_RATIO) * this._labelInfo.fontSize + blank; this._offsetY = -this._labelInfo.fontSize * textUtils.BASELINE_RATIO / 2; this._canvas.width !== this._width && (this._canvas.width = this._width); this._canvas.height !== this._height && (this._canvas.height = this._height); this._texture.initWithElement(this._canvas); }, _updateTexture: function _updateTexture() { var context = this._context; var labelInfo = this._labelInfo, width = this._canvas.width, height = this._canvas.height; var fontSize = this._labelInfo.fontSize; var startX = width / 2; var startY = height / 2 + fontSize * textUtils.MIDDLE_RATIO + fontSize * textUtils.BASELINE_OFFSET; var color = labelInfo.color; context.lineJoin = "round"; context.textAlign = "center"; context.clearRect(0, 0, width, height); context.fillStyle = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + _invisibleAlpha + ")"; context.fillRect(0, 0, width, height); context.font = labelInfo.fontDesc; context.fillStyle = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)"; if (labelInfo.isOutlined && labelInfo.margin > 0) { var strokeColor = labelInfo.out || WHITE; context.strokeStyle = "rgba(" + strokeColor.r + ", " + strokeColor.g + ", " + strokeColor.b + ", " + strokeColor.a / 255 + ")"; context.lineWidth = 2 * labelInfo.margin; context.strokeText(this._char, startX, startY); } context.fillText(this._char, startX, startY); this._texture.handleLoadedTexture(); }, destroy: function destroy() { this._texture._packable = false; this._texture.destroy(); this._texture = null; Label._canvasPool.put(this._data); } }; function LetterAtlas(atlases, width, height) { var texture = new RenderTexture(); texture.initWithSize(width, height); texture.update(); this._atlases = atlases; this._texture = texture; this._id = 0; this._tmpId = -1; this._x = space; this._y = space; this._nexty = space; this.frees = []; this.waitCleans = []; this._width = width; this._height = height; } cc.js.mixin(LetterAtlas.prototype, { insertLetterTexture: function insertLetterTexture(letterTexture) { var texture = letterTexture._texture; var width = texture.width, height = texture.height; if (this.frees.length > 0) { var score = Number.MAX_VALUE; var areaFit = 0; var original = null; var originalIndex = 0; for (var i = 0; i < this.frees.length; i++) { var freeLetter = this.frees[i]; if (freeLetter._width === width && freeLetter._height === height) { areaFit = freeLetter._width * freeLetter._height - width * height; if (areaFit < score) { original = freeLetter; originalIndex = i; score = areaFit; } } } if (original) { original._hash = letterTexture._hash; original.w = letterTexture._width - bleed; original.h = letterTexture._height - bleed; original.xAdvance = original.w; original.offsetY = letterTexture._offsetY; this._texture.drawTextureAt(texture, original.u - bleed / 2, original.v - bleed / 2); this._dirty = true; this.removeFreeLetter(originalIndex); this._atlases._fontDefDictionary.addLetterDefinitions(letterTexture._hash, original); return original; } } var oldx = this._x, oldy = this._y, oldnexty = this._nexty; if (this._x + width + space > this._width) { this._x = space; this._y = this._nexty; } this._y + height > this._nexty && (this._nexty = this._y + height + space); if (this._nexty > this._height) { this._x = oldx; this._y = oldy; this._nexty = oldnexty; if (this.waitCleans.length > 0) { for (var _iterator = _createForOfIteratorHelperLoose(this.waitCleans), _step; !(_step = _iterator()).done; ) { var _letter = _step.value; _letter._inCleans = false; if (0 === _letter.ref) { delete this._atlases._fontDefDictionary._letterDefinitions[_letter._hash]; this.frees.push(_letter); } } this.waitCleans.length = 0; return this.insertLetterTexture(letterTexture); } return null; } this._texture.drawTextureAt(texture, this._x, this._y); this._dirty = true; var letter = new FontLetterDefinition(); letter.u = this._x + bleed / 2; letter.v = this._y + bleed / 2; letter.texture = this._texture; letter.atlas = this; letter.ref = 0; letter.valid = true; letter.w = letterTexture._width - bleed; letter.h = letterTexture._height - bleed; letter._inCleans = false; letter._hash = letterTexture._hash; letter._width = width; letter._height = height; letter.xAdvance = letter.w; letter.offsetY = letterTexture._offsetY; this._x += width + space; this._atlases._fontDefDictionary.addLetterDefinitions(letterTexture._hash, letter); return letter; }, pushFreeLetter: function pushFreeLetter(letter) { var i = this.frees.push(letter) - 1; }, removeFreeLetter: function removeFreeLetter(index) { var temp = this.frees[index]; var temp2 = this.frees[this.frees.length - 1]; this.frees[index] = temp2; this.frees.pop(); }, update: function update() { if (!this._dirty) return; this._texture.update(); this._dirty = false; }, reset: function reset() { this._x = space; this._y = space; this._nexty = space; var defs = this._atlases._fontDefDictionary._letterDefinitions; for (var key in defs) { var def = defs[key]; def.atlas === this && delete defs[key]; } this.frees.length = 0; this.waitCleans.length = 0; }, destroy: function destroy() { this.reset(); var handler = this._atlases.material.getMultiHandler(); handler.removeTexture(this._texture); this._texture.destroy(); this._texture = null; } }); var LetterAtlases = (function() { function LetterAtlases() { this.atlases = []; this.material = null; this.fakeMaterial = { material: null }; this._fontDefDictionary = new FontAtlas(null); var handler = new cc.sp.MultiHandler(); this.material = handler.material; this.fakeMaterial.material = this.material; cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); } var _proto = LetterAtlases.prototype; _proto.insertLetterTexture = function insertLetterTexture(letterTexture) { for (var _iterator2 = _createForOfIteratorHelperLoose(this.atlases), _step2; !(_step2 = _iterator2()).done; ) { var _atlas = _step2.value; var letter = _atlas.insertLetterTexture(letterTexture); if (letter) return letter; } if (this.atlases.length >= 8) return null; var atlas = new LetterAtlas(this, _atlasWidth, _atlasHeight); var len = this.atlases.push(atlas); atlas._id = len - 1; var handler = this.material.getMultiHandler(); handler.setTexture(atlas._id, atlas._texture); (true, cc.sp.charAtlasAutoBatchCount >= len) && cc.sp.multiBatcher.requsetMaterial(atlas._texture); return atlas.insertLetterTexture(letterTexture); }; _proto.deleteLetter = function deleteLetter(letter) { letter.ref--; if (0 === letter.ref && !letter._inCleans) { letter._inCleans = true; letter.atlas.waitCleans.push(letter); } }; _proto.update = function update() { for (var _iterator3 = _createForOfIteratorHelperLoose(this.atlases), _step3; !(_step3 = _iterator3()).done; ) { var atlas = _step3.value; atlas.update(); } }; _proto.reset = function reset() { this._fontDefDictionary.clear(); for (var _iterator4 = _createForOfIteratorHelperLoose(this.atlases), _step4; !(_step4 = _iterator4()).done; ) { var atlas = _step4.value; atlas.reset(); } }; _proto.destroy = function destroy() { this._fontDefDictionary.clear(); for (var _iterator5 = _createForOfIteratorHelperLoose(this.atlases), _step5; !(_step5 = _iterator5()).done; ) { var atlas = _step5.value; atlas.destroy(); } this.atlases.length = 0; }; _proto.beforeSceneLoad = function beforeSceneLoad() { cc.sp.charAtlasAutoResetBeforeSceneLoad && this.clearAllCache(); }; _proto.clearAllCache = function clearAllCache() { this.reset(); }; _proto.getTexture = function getTexture() { if (!_emptyTexture) { _emptyTexture = new RenderTexture(); _emptyTexture.initWithSize(_atlasWidth, _atlasHeight); _emptyTexture.update(); } return _emptyTexture; }; _proto.getLetter = function getLetter(key) { return this._fontDefDictionary._letterDefinitions[key]; }; _proto.getLetterDefinitionForChar = function getLetterDefinitionForChar(_char2, labelInfo) { var hash = _char2.charCodeAt(0) + labelInfo.hash; var letter = this._fontDefDictionary._letterDefinitions[hash]; if (!letter) { var temp = new LetterTexture(_char2, labelInfo); temp.updateRenderData(); letter = this.insertLetterTexture(temp); temp.destroy(); } if (letter && _firstTraverse) { letter.ref++; _assembler._letterRefs.push(letter); this.checkMaterialAndUpdateTexId(letter); } return letter; }; _proto.checkMaterialAndUpdateTexId = function checkMaterialAndUpdateTexId(letter) { var atlas = letter.atlas; var comp = _assembler._renderComp; if (!_usedMaterial) return; if (_needCheckMaterial) { _needCheckMaterial = false; if (_usedMaterial.material !== _shareAtlas.material) { _assembler.checkAndSwitchMaterial(comp, atlas._texture, _usedMaterial); _usedMaterial = comp._materials[0]; } } if (_usedMaterial.material !== _shareAtlas.material && -1 === atlas._tmpId) { var handler = _usedMaterial.material.getMultiHandler(); if (handler) { var index = handler.getIndex(atlas._texture.getImpl()); if (-1 !== index) { atlas._tmpId = index; return; } } comp.setMaterial(0, _shareAtlas.material); _usedMaterial = _shareAtlas.fakeMaterial; } }; return LetterAtlases; })(); function computeHash(labelInfo) { var hashData = "|"; var color = labelInfo.color.toHEX(); var out = ""; labelInfo.isOutlined && labelInfo.margin > 0 && (out = out + labelInfo.margin + labelInfo.out.toHEX()); return hashData + labelInfo.fontSize + labelInfo.fontFamily + color + out; } var _shareAtlas = null; var _atlasWidth = 2048; var _atlasHeight = 2048; var _isBold = false; var _usedMaterial = null; var _needCheckMaterial = false; var _firstTraverse = false; var _assembler = null; var _emptyTexture = null; var LetterFontAssembler = (function(_WebglBmfontAssembler) { _inheritsLoose(LetterFontAssembler, _WebglBmfontAssembler); function LetterFontAssembler() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; _this = _WebglBmfontAssembler.call.apply(_WebglBmfontAssembler, [ this ].concat(args)) || this; _this._letterRefs = []; return _this; } var _proto2 = LetterFontAssembler.prototype; _proto2.initData = function initData() { var data = this._renderData; data.createFlexData(0, this.verticesCount, this.indicesCount, this.getVfmt()); }; _proto2.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto2.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto2._getAssemblerData = function _getAssemblerData() { if (!_shareAtlas) { _shareAtlas = new LetterAtlases(); cc.Label._shareAtlas = _shareAtlas; } return _shareAtlas.getTexture(); }; _proto2._updateFontFamily = function _updateFontFamily(comp) { shareLabelInfo.fontAtlas = _shareAtlas; shareLabelInfo.fontFamily = getFontFamily(comp); var outline = OUTLINE_SUPPORTED && comp.getComponent(LabelOutline); if (outline && outline.enabled) { shareLabelInfo.isOutlined = true; shareLabelInfo.margin = outline.width; shareLabelInfo.out = outline.color.clone(); shareLabelInfo.out.a = outline.color.a * comp.node.color.a / 255; } else { shareLabelInfo.isOutlined = false; shareLabelInfo.margin = 0; } }; _proto2._updateLabelInfo = function _updateLabelInfo(comp) { shareLabelInfo.fontDesc = this._getFontDesc(); shareLabelInfo.color = comp.node.color; shareLabelInfo.hash = computeHash(shareLabelInfo); }; _proto2._getFontDesc = function _getFontDesc() { var fontDesc = shareLabelInfo.fontSize.toString() + "px "; fontDesc += shareLabelInfo.fontFamily; _isBold && (fontDesc = "bold " + fontDesc); return fontDesc; }; _proto2._computeHorizontalKerningForText = function _computeHorizontalKerningForText() {}; _proto2._determineRect = function _determineRect(tempRect) { return false; }; _proto2._aftUpdateRenderData = function _aftUpdateRenderData(comp) { _assembler = this; _usedMaterial = _assembler._renderComp._materials[0]; _needCheckMaterial = true; _firstTraverse = true; for (var _iterator6 = _createForOfIteratorHelperLoose(_shareAtlas.atlases), _step6; !(_step6 = _iterator6()).done; ) { var atlas = _step6.value; atlas._tmpId = -1; } this._recycleLetterRef(); _WebglBmfontAssembler.prototype._aftUpdateRenderData.call(this, comp); _usedMaterial = null; _assembler = null; }; _proto2._finishMultilineTextWrap = function _finishMultilineTextWrap() { _firstTraverse = false; }; _proto2._recycleLetterRef = function _recycleLetterRef() { for (var _iterator7 = _createForOfIteratorHelperLoose(this._letterRefs), _step7; !(_step7 = _iterator7()).done; ) { var letter = _step7.value; _shareAtlas.deleteLetter(letter); } this._letterRefs.length = 0; }; _proto2._resetAssemblerData = function _resetAssemblerData(assemblerData) { 0 !== this._letterRefs.length && this._recycleLetterRef(); }; _proto2.appendVerts = function appendVerts(comp, offset, l, r, b, t, letter) { _WebglBmfontAssembler.prototype.appendVerts.call(this, comp, offset, l, r, b, t, letter); var renderData = this._renderData; var verts = renderData.vDatas[0]; var floatsPerVert = this.floatsPerVert; var texIdOffset = offset + this.texIdOffset; var id = _usedMaterial ? _usedMaterial.material !== _shareAtlas.material ? letter.atlas._tmpId : letter.atlas._id : 0; verts[texIdOffset] = id; texIdOffset += floatsPerVert; verts[texIdOffset] = id; texIdOffset += floatsPerVert; verts[texIdOffset] = id; texIdOffset += floatsPerVert; verts[texIdOffset] = id; }; return LetterFontAssembler; })(_bmfont["default"]); exports["default"] = LetterFontAssembler; LetterFontAssembler.prototype.floatsPerVert = 6; LetterFontAssembler.prototype.texIdOffset = 5; LetterFontAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../assets/CCRenderTexture": 65, "../../../components/CCComponent": 92, "../../../components/CCLabel": 94, "../../../components/CCLabelOutline": 95, "../../../utils/text-utils": 224, "../../webgl/assemblers/label/2d/bmfont": 175, "../../webgl/vertex-format": 202, "../utils": 168 } ], 167: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var textUtils = require("../../../utils/text-utils"); var macro = require("../../../platform/CCMacro"); var Label = require("../../../components/CCLabel"); var LabelOutline = require("../../../components/CCLabelOutline"); var LabelShadow = require("../../../components/CCLabelShadow"); var Overflow = Label.Overflow; var deleteFromDynamicAtlas = require("../utils").deleteFromDynamicAtlas; var getFontFamily = require("../utils").getFontFamily; var _invisibleAlpha = (1 / 255).toFixed(3); var MAX_SIZE = 2048; var _context = null; var _canvas = null; var _texture = null; var _fontDesc = ""; var _string = ""; var _fontSize = 0; var _drawFontSize = 0; var _splitedStrings = []; var _canvasSize = cc.Size.ZERO; var _lineHeight = 0; var _hAlign = 0; var _vAlign = 0; var _color = null; var _fontFamily = ""; var _overflow = Overflow.NONE; var _isWrapText = false; var _premultiply = false; var _isRetina = false; var _retinaScale = 1; var _outlineComp = null; var _outlineColor = cc.Color.WHITE; var _shadowComp = null; var _shadowColor = cc.Color.BLACK; var _canvasPadding = cc.rect(); var _contentSizeExtend = cc.Size.ZERO; var _nodeContentSize = cc.Size.ZERO; var _enableBold = false; var _enableItalic = false; var _enableUnderline = false; var _underlineThickness = 0; var _drawUnderlinePos = cc.Vec2.ZERO; var _drawUnderlineWidth = 0; var _sharedLabelData; var Alignment = [ "left", "center", "right" ]; var TTFAssembler = (function(_Assembler2D) { _inheritsLoose(TTFAssembler, _Assembler2D); function TTFAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = TTFAssembler.prototype; _proto._getAssemblerData = function _getAssemblerData() { _sharedLabelData = Label._canvasPool.get(); _sharedLabelData.canvas.width = _sharedLabelData.canvas.height = 1; return _sharedLabelData; }; _proto._resetAssemblerData = function _resetAssemblerData(assemblerData) { assemblerData && Label._canvasPool.put(assemblerData); }; _proto.updateRenderData = function updateRenderData(comp) { _Assembler2D.prototype.updateRenderData.call(this, comp); if (!comp._vertsDirty) return false; this._updateProperties(comp); this._calculateLabelFont(); this._updateLabelDimensions(); this._updateTexture(comp); var assemblerChanged = this._calDynamicAtlas(comp); assemblerChanged || this._aftUpdateRenderData(comp); return assemblerChanged; }; _proto._aftUpdateRenderData = function _aftUpdateRenderData(comp) { if (_isRetina) { _fontSize /= _retinaScale; _nodeContentSize.width /= _retinaScale; _nodeContentSize.height /= _retinaScale; } comp._actualFontSize = _fontSize; comp.node.setContentSize(_nodeContentSize); this.updateVerts(comp); comp._vertsDirty = false; _context = null; _canvas = null; _texture = null; }; _proto.getTTFTextureSizeScale = function getTTFTextureSizeScale() { return _isRetina ? _retinaScale : 1; }; _proto.updateVerts = function updateVerts() {}; _proto._updatePaddingRect = function _updatePaddingRect() { var top = 0, bottom = 0, left = 0, right = 0; var outlineWidth = 0; _contentSizeExtend.width = _contentSizeExtend.height = 0; if (_outlineComp) { outlineWidth = _outlineComp.width; _isRetina && (outlineWidth *= _retinaScale); top = bottom = left = right = outlineWidth; _contentSizeExtend.width = _contentSizeExtend.height = 2 * outlineWidth; } if (_shadowComp) { var shadowWidth = _shadowComp.blur + outlineWidth; left = Math.max(left, -_shadowComp._offset.x + shadowWidth); right = Math.max(right, _shadowComp._offset.x + shadowWidth); top = Math.max(top, _shadowComp._offset.y + shadowWidth); bottom = Math.max(bottom, -_shadowComp._offset.y + shadowWidth); } if (_enableItalic) { var offset = _drawFontSize * Math.tan(.20943951); right += offset; _contentSizeExtend.width += offset; } _canvasPadding.x = left; _canvasPadding.y = top; _canvasPadding.width = left + right; _canvasPadding.height = top + bottom; }; _proto._updateProperties = function _updateProperties(comp) { var assemblerData = comp._assemblerData; _context = assemblerData.context; _canvas = assemblerData.canvas; _texture = comp._frame._original ? comp._frame._original._texture : comp._frame._texture; _isRetina = cc.sp.enableLabelRetina && 0 === comp.enableRetina || 1 === comp.enableRetina; _retinaScale = cc.sp.labelRetinaScale; _string = comp.string.toString(); _fontSize = comp._fontSize; _nodeContentSize = comp.node.getContentSize(); _lineHeight = comp._lineHeight; _drawFontSize = _fontSize; _underlineThickness = comp.underlineHeight || _drawFontSize / 8; if (_isRetina) { _fontSize *= _retinaScale; _nodeContentSize.width *= _retinaScale; _nodeContentSize.height *= _retinaScale; _lineHeight *= _retinaScale; comp.underlineHeight && (_underlineThickness *= _retinaScale); _drawFontSize = _fontSize; } _overflow = comp.overflow; _canvasSize.width = _nodeContentSize.width; _canvasSize.height = _nodeContentSize.height; _hAlign = comp.horizontalAlign; _vAlign = comp.verticalAlign; _color = comp.node.color; _enableBold = comp.enableBold; _enableItalic = comp.enableItalic; _enableUnderline = comp.enableUnderline; _fontFamily = getFontFamily(comp); _premultiply = comp.srcBlendFactor === cc.macro.BlendFactor.ONE; false; _isWrapText = _overflow !== Overflow.NONE && (_overflow === Overflow.RESIZE_HEIGHT || comp.enableWrapText); _outlineComp = LabelOutline && comp.getComponent(LabelOutline); _outlineComp = _outlineComp && _outlineComp.enabled && _outlineComp.width > 0 ? _outlineComp : null; _outlineComp && _outlineColor.set(_outlineComp.color); _shadowComp = LabelShadow && comp.getComponent(LabelShadow); _shadowComp = _shadowComp && _shadowComp.enabled ? _shadowComp : null; if (_shadowComp) { _shadowColor.set(_shadowComp.color); _shadowColor.a = _shadowColor.a * comp.node.color.a / 255; } this._updatePaddingRect(); }; _proto._calculateFillTextStartPosition = function _calculateFillTextStartPosition() { var labelX = 0; _hAlign === macro.TextAlignment.RIGHT ? labelX = _canvasSize.width - _canvasPadding.width : _hAlign === macro.TextAlignment.CENTER && (labelX = (_canvasSize.width - _canvasPadding.width) / 2); var lineHeight = this._getLineHeight(); var drawStartY = lineHeight * (_splitedStrings.length - 1); var firstLinelabelY = _fontSize * (1 - textUtils.BASELINE_RATIO / 2); if (_vAlign !== macro.VerticalTextAlignment.TOP) { var blank = drawStartY + _canvasPadding.height + _fontSize - _canvasSize.height; if (_vAlign === macro.VerticalTextAlignment.BOTTOM) { blank += textUtils.BASELINE_RATIO / 2 * _fontSize; firstLinelabelY -= blank; } else firstLinelabelY -= blank / 2; } firstLinelabelY += textUtils.BASELINE_OFFSET * _fontSize; return cc.v2(labelX + _canvasPadding.x, firstLinelabelY + _canvasPadding.y); }; _proto._setupOutline = function _setupOutline() { _context.strokeStyle = "rgba(" + _outlineColor.r + ", " + _outlineColor.g + ", " + _outlineColor.b + ", " + _outlineColor.a / 255 + ")"; _context.lineWidth = 2 * _outlineComp.width * (_isRetina ? _retinaScale : 1); }; _proto._setupShadow = function _setupShadow() { _context.shadowColor = "rgba(" + _shadowColor.r + ", " + _shadowColor.g + ", " + _shadowColor.b + ", " + _shadowColor.a / 255 + ")"; _context.shadowBlur = _shadowComp.blur * (_isRetina ? _retinaScale : 1); _context.shadowOffsetX = _shadowComp.offset.x * (_isRetina ? _retinaScale : 1); _context.shadowOffsetY = -_shadowComp.offset.y * (_isRetina ? _retinaScale : 1); }; _proto._drawTextEffect = function _drawTextEffect(startPosition, lineHeight) { if (!_shadowComp && !_outlineComp && !_enableUnderline) return; var isMultiple = _splitedStrings.length > 1 && _shadowComp; var measureText = this._measureText(_context, _fontDesc); var drawTextPosX = 0, drawTextPosY = 0; _shadowComp && this._setupShadow(); _outlineComp && this._setupOutline(); for (var i = 0; i < _splitedStrings.length; ++i) { drawTextPosX = startPosition.x; drawTextPosY = startPosition.y + i * lineHeight; if (isMultiple) { _outlineComp && _context.strokeText(_splitedStrings[i], drawTextPosX, drawTextPosY); _context.fillText(_splitedStrings[i], drawTextPosX, drawTextPosY); } if (_enableUnderline) { _drawUnderlineWidth = measureText(_splitedStrings[i]); _hAlign === macro.TextAlignment.RIGHT ? _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth : _hAlign === macro.TextAlignment.CENTER ? _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth / 2 : _drawUnderlinePos.x = startPosition.x; _drawUnderlinePos.y = drawTextPosY + _drawFontSize / 8; _context.fillRect(_drawUnderlinePos.x, _drawUnderlinePos.y, _drawUnderlineWidth, _underlineThickness); } } isMultiple && (_context.shadowColor = "transparent"); }; _proto._updateTexture = function _updateTexture() { _context.clearRect(0, 0, _canvas.width, _canvas.height); _context.lineJoin = "round"; if (_premultiply) _context.fillStyle = "rgba(" + _color.r + ", " + _color.g + ", " + _color.b + ", " + _color.a / 255 + ")"; else { var _fillColor = _outlineComp ? _outlineColor : _color; _context.fillStyle = "rgba(" + _fillColor.r + ", " + _fillColor.g + ", " + _fillColor.b + ", " + _invisibleAlpha + ")"; _context.fillRect(0, 0, _canvas.width, _canvas.height); _context.fillStyle = "rgba(" + _color.r + ", " + _color.g + ", " + _color.b + ", 1)"; } var startPosition = this._calculateFillTextStartPosition(); var lineHeight = this._getLineHeight(); var drawTextPosX = startPosition.x, drawTextPosY = 0; this._drawTextEffect(startPosition, lineHeight); for (var i = 0; i < _splitedStrings.length; ++i) { drawTextPosY = startPosition.y + i * lineHeight; _outlineComp && _context.strokeText(_splitedStrings[i], drawTextPosX, drawTextPosY); _context.fillText(_splitedStrings[i], drawTextPosX, drawTextPosY); } _shadowComp && (_context.shadowColor = "transparent"); _texture.handleLoadedTexture(); }; _proto._calDynamicAtlas = function _calDynamicAtlas(comp) { if (comp.cacheMode !== Label.CacheMode.BITMAP) return false; var frame = comp._frame; deleteFromDynamicAtlas(comp, frame); frame._original || frame.setRect(cc.rect(0, 0, _canvas.width, _canvas.height)); return this.packDynamicAtlasAndCheckMaterial(comp, frame); }; _proto.packDynamicAtlasAndCheckMaterial = function packDynamicAtlasAndCheckMaterial(comp, frame) { var allowDynamicAtlas = comp.allowDynamicAtlas; if (cc.sp.allowDynamicAtlas && 0 === allowDynamicAtlas || 1 === allowDynamicAtlas) { frame._texture._uuid = _fontDesc + _overflow + (_premultiply ? "P" : "NP") + (_enableUnderline ? "UL" : "NUL") + _string; _outlineComp && (frame._texture._uuid += _outlineComp.color.toHEX() + "," + _outlineComp.width + ","); _shadowComp && (frame._texture._uuid += _shadowComp.color.toHEX() + _shadowComp.offset.x + "," + _shadowComp.offset.y + "," + _shadowComp.blur); } return _Assembler2D.prototype.packDynamicAtlasAndCheckMaterial.call(this, comp, frame); }; _proto._updateLabelDimensions = function _updateLabelDimensions() { var maxTextureSize = cc.renderer.device.caps ? cc.renderer.device.caps.maxTextureSize : MAX_SIZE; (_canvasSize.width > maxTextureSize || _canvasSize.height > maxTextureSize) && cc.warn("The maximum texture size supported by the device is " + maxTextureSize); _canvasSize.width = Math.min(_canvasSize.width, maxTextureSize); _canvasSize.height = Math.min(_canvasSize.height, maxTextureSize); var recreate = false; if (_canvas.width !== _canvasSize.width) { _canvas.width = _canvasSize.width; recreate = true; } if (_canvas.height !== _canvasSize.height) { _canvas.height = _canvasSize.height; recreate = true; } recreate && (_context.font = _fontDesc); _context.textAlign = Alignment[_hAlign]; }; _proto._getFontDesc = function _getFontDesc() { var fontDesc = _fontSize.toString() + "px "; fontDesc += _fontFamily; _enableBold && (fontDesc = "bold " + fontDesc); _enableItalic && (fontDesc = "italic " + fontDesc); return fontDesc; }; _proto._getLineHeight = function _getLineHeight() { var nodeSpacingY = _lineHeight; nodeSpacingY = 0 === nodeSpacingY ? _fontSize : nodeSpacingY * _fontSize / _drawFontSize; return 0 | nodeSpacingY; }; _proto._calculateParagraphLength = function _calculateParagraphLength(paragraphedStrings, ctx) { var paragraphLength = []; for (var i = 0; i < paragraphedStrings.length; ++i) { var width = textUtils.safeMeasureText(ctx, paragraphedStrings[i], _fontDesc); paragraphLength.push(width); } return paragraphLength; }; _proto._measureText = function _measureText(ctx, fontDesc) { return function(string) { return textUtils.safeMeasureText(ctx, string, fontDesc); }; }; _proto._calculateShrinkFont = function _calculateShrinkFont(paragraphedStrings) { var paragraphLength = this._calculateParagraphLength(paragraphedStrings, _context); var i = 0; var totalHeight = 0; var maxLength = 0; if (_isWrapText) { var canvasWidthNoMargin = _nodeContentSize.width; var canvasHeightNoMargin = _nodeContentSize.height; if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) return; totalHeight = canvasHeightNoMargin + 1; var actualFontSize = _fontSize + 1; var textFragment = ""; var left = 0, right = 0 | actualFontSize, mid = 0; while (left < right) { mid = left + right + 1 >> 1; if (mid <= 0) { cc.logID(4003); break; } _fontSize = mid; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; var lineHeight = this._getLineHeight(); totalHeight = 0; for (i = 0; i < paragraphedStrings.length; ++i) { var allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i], _fontDesc); textFragment = textUtils.fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context, _fontDesc)); totalHeight += textFragment.length * lineHeight; } totalHeight > canvasHeightNoMargin ? right = mid - 1 : left = mid; } if (0 === left) cc.logID(4003); else { _fontSize = left; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; } } else { totalHeight = paragraphedStrings.length * this._getLineHeight(); for (i = 0; i < paragraphedStrings.length; ++i) maxLength < paragraphLength[i] && (maxLength = paragraphLength[i]); var scaleX = (_canvasSize.width - _canvasPadding.width) / maxLength; var scaleY = _canvasSize.height / totalHeight; _fontSize = _drawFontSize * Math.min(1, scaleX, scaleY) | 0; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; } }; _proto._calculateWrapText = function _calculateWrapText(paragraphedStrings) { if (!_isWrapText) return; _splitedStrings = []; var canvasWidthNoMargin = _nodeContentSize.width; for (var i = 0; i < paragraphedStrings.length; ++i) { var allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i], _fontDesc); var textFragment = textUtils.fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context, _fontDesc)); _splitedStrings = _splitedStrings.concat(textFragment); } }; _proto._calculateLabelFont = function _calculateLabelFont() { var paragraphedStrings = _string.split("\n"); _splitedStrings = paragraphedStrings; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; switch (_overflow) { case Overflow.NONE: var canvasSizeX = 0; var canvasSizeY = 0; for (var i = 0; i < paragraphedStrings.length; ++i) { var paraLength = textUtils.safeMeasureText(_context, paragraphedStrings[i], _fontDesc); canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength; } canvasSizeY = (_splitedStrings.length + textUtils.BASELINE_RATIO) * this._getLineHeight(); var rawWidth = parseFloat(canvasSizeX.toFixed(2)); var rawHeight = parseFloat(canvasSizeY.toFixed(2)); _canvasSize.width = rawWidth + _canvasPadding.width; _canvasSize.height = rawHeight + _canvasPadding.height; _nodeContentSize.width = rawWidth + _contentSizeExtend.width; _nodeContentSize.height = rawHeight + _contentSizeExtend.height; break; case Overflow.SHRINK: this._calculateShrinkFont(paragraphedStrings); this._calculateWrapText(paragraphedStrings); break; case Overflow.CLAMP: this._calculateWrapText(paragraphedStrings); break; case Overflow.RESIZE_HEIGHT: this._calculateWrapText(paragraphedStrings); var _rawHeight = (_splitedStrings.length + textUtils.BASELINE_RATIO) * this._getLineHeight(); _canvasSize.height = _rawHeight + _canvasPadding.height; _nodeContentSize.height = _rawHeight + _contentSizeExtend.height; } }; return TTFAssembler; })(_assembler2d["default"]); exports["default"] = TTFAssembler; module.exports = exports["default"]; }), { "../../../components/CCLabel": 94, "../../../components/CCLabelOutline": 95, "../../../components/CCLabelShadow": 96, "../../../platform/CCMacro": 134, "../../../utils/text-utils": 224, "../../assembler-2d": 155, "../utils": 168 } ], 168: [ (function(require, module, exports) { "use strict"; var dynamicAtlasManager = require("./dynamic-atlas/manager"); var WHITE = cc.Color.WHITE; var shareLabelInfo = { fontAtlas: null, fontSize: 0, lineHeight: 0, hAlign: 0, vAlign: 0, hash: "", fontFamily: "", fontDesc: "Arial", color: WHITE, isOutlined: false, out: WHITE, margin: 0 }; module.exports = { deleteFromDynamicAtlas: function deleteFromDynamicAtlas(comp, frame) { if (frame && true && frame._original && dynamicAtlasManager) { dynamicAtlasManager.deleteAtlasSpriteFrame(frame); frame._resetDynamicAtlasFrame(); } }, getFontFamily: function getFontFamily(comp) { if (comp.useSystemFont) return comp.fontFamily || "Arial"; if (comp.font) { if (comp.font._nativeAsset) return comp.font._nativeAsset; cc.assetManager.postLoadNative(comp.font, (function(err) { comp.isValid && comp.setVertsDirty(); })); return "Arial"; } return "Arial"; }, shareLabelInfo: shareLabelInfo }; }), { "./dynamic-atlas/manager": 162 } ], 169: [ (function(require, module, exports) { "use strict"; cc.Graphics.earcut = module.exports = earcut; function earcut(data, holeIndices, dim) { dim = dim || 2; var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = []; if (!outerNode) return triangles; var minX, minY, maxX, maxY, x, y, size; hasHoles && (outerNode = eliminateHoles(data, holeIndices, outerNode, dim)); if (data.length > 80 * dim) { minX = maxX = data[0]; minY = maxY = data[1]; for (var i = dim; i < outerLen; i += dim) { x = data[i]; y = data[i + 1]; x < minX && (minX = x); y < minY && (minY = y); x > maxX && (maxX = x); y > maxY && (maxY = y); } size = Math.max(maxX - minX, maxY - minY); } earcutLinked(outerNode, triangles, dim, minX, minY, size); return triangles; } function linkedList(data, start, end, dim, clockwise) { var i, last; if (clockwise === signedArea(data, start, end, dim) > 0) for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); else for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; } function filterPoints(start, end) { if (!start) return start; end || (end = start); var p = start, again; do { again = false; if (p.steiner || !equals(p, p.next) && 0 !== area(p.prev, p, p.next)) p = p.next; else { removeNode(p); p = end = p.prev; if (p === p.next) return null; again = true; } } while (again || p !== end); return end; } function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { if (!ear) return; !pass && size && indexCurve(ear, minX, minY, size); var stop = ear, prev, next; while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); removeNode(ear); ear = next.next; stop = next.next; continue; } ear = next; if (ear === stop) { if (pass) if (1 === pass) { ear = cureLocalIntersections(ear, triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, size, 2); } else 2 === pass && splitEarcut(ear, triangles, dim, minX, minY, size); else earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); break; } } } function isEar(ear) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; var p = ear.next.next; while (p !== ear.prev) { if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.next; } return true; } function isEarHashed(ear, minX, minY, size) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x, minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y, maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x, maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size); var p = ear.nextZ; while (p && p.z <= maxZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.nextZ; } p = ear.prevZ; while (p && p.z >= minZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.prevZ; } return true; } function cureLocalIntersections(start, triangles, dim) { var p = start; do { var a = p.prev, b = p.next.next; if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); removeNode(p); removeNode(p.next); p = start = b; } p = p.next; } while (p !== start); return p; } function splitEarcut(start, triangles, dim, minX, minY, size) { var a = start; do { var b = a.next.next; while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { var c = splitPolygon(a, b); a = filterPoints(a, a.next); c = filterPoints(c, c.next); earcutLinked(a, triangles, dim, minX, minY, size); earcutLinked(c, triangles, dim, minX, minY, size); return; } b = b.next; } a = a.next; } while (a !== start); } function eliminateHoles(data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); list === list.next && (list.steiner = true); queue.push(getLeftmost(list)); } queue.sort(compareX); for (i = 0; i < queue.length; i++) { eliminateHole(queue[i], outerNode); outerNode = filterPoints(outerNode, outerNode.next); } return outerNode; } function compareX(a, b) { return a.x - b.x; } function eliminateHole(hole, outerNode) { outerNode = findHoleBridge(hole, outerNode); if (outerNode) { var b = splitPolygon(outerNode, hole); filterPoints(b, b.next); } } function findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; do { if (hy <= p.y && hy >= p.next.y) { var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; if (x === hx) { if (hy === p.y) return p; if (hy === p.next.y) return p.next; } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while (p !== outerNode); if (!m) return null; if (hx === qx) return m.prev; var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m.next; while (p !== stop) { if (hx >= p.x && p.x >= mx && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { tan = Math.abs(hy - p.y) / (hx - p.x); if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) { m = p; tanMin = tan; } } p = p.next; } return m; } function indexCurve(start, minX, minY, size) { var p = start; do { null === p.z && (p.z = zOrder(p.x, p.y, minX, minY, size)); p.prevZ = p.prev; p.nextZ = p.next; p = p.next; } while (p !== start); p.prevZ.nextZ = null; p.prevZ = null; sortLinked(p); } function sortLinked(list) { var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; do { p = list; list = null; tail = null; numMerges = 0; while (p) { numMerges++; q = p; pSize = 0; for (i = 0; i < inSize; i++) { pSize++; q = q.nextZ; if (!q) break; } qSize = inSize; while (pSize > 0 || qSize > 0 && q) { if (0 === pSize) { e = q; q = q.nextZ; qSize--; } else if (0 !== qSize && q) if (p.z <= q.z) { e = p; p = p.nextZ; pSize--; } else { e = q; q = q.nextZ; qSize--; } else { e = p; p = p.nextZ; pSize--; } tail ? tail.nextZ = e : list = e; e.prevZ = tail; tail = e; } p = q; } tail.nextZ = null; inSize *= 2; } while (numMerges > 1); return list; } function zOrder(x, y, minX, minY, size) { x = 32767 * (x - minX) / size; y = 32767 * (y - minY) / size; x = 16711935 & (x | x << 8); x = 252645135 & (x | x << 4); x = 858993459 & (x | x << 2); x = 1431655765 & (x | x << 1); y = 16711935 & (y | y << 8); y = 252645135 & (y | y << 4); y = 858993459 & (y | y << 2); y = 1431655765 & (y | y << 1); return x | y << 1; } function getLeftmost(start) { var p = start, leftmost = start; do { p.x < leftmost.x && (leftmost = p); p = p.next; } while (p !== start); return leftmost; } function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; } function isValidDiagonal(a, b) { return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); } function area(p, q, r) { return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); } function equals(p1, p2) { return p1.x === p2.x && p1.y === p2.y; } function intersects(p1, q1, p2, q2) { if (equals(p1, q1) && equals(p2, q2) || equals(p1, q2) && equals(p2, q1)) return true; return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; } function intersectsPolygon(a, b) { var p = a; do { if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; p = p.next; } while (p !== a); return false; } function locallyInside(a, b) { return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; } function middleInside(a, b) { var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { p.y > py !== p.next.y > py && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x && (inside = !inside); p = p.next; } while (p !== a); return inside; } function splitPolygon(a, b) { var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev; a.next = b; b.prev = a; a2.next = an; an.prev = a2; b2.next = a2; a2.prev = b2; bp.next = b2; b2.prev = bp; return b2; } function insertNode(i, x, y, last) { var p = new Node(i, x, y); if (last) { p.next = last.next; p.prev = last; last.next.prev = p; last.next = p; } else { p.prev = p; p.next = p; } return p; } function removeNode(p) { p.next.prev = p.prev; p.prev.next = p.next; p.prevZ && (p.prevZ.nextZ = p.nextZ); p.nextZ && (p.nextZ.prevZ = p.prevZ); } function Node(i, x, y) { this.i = i; this.x = x; this.y = y; this.prev = null; this.next = null; this.z = null; this.prevZ = null; this.nextZ = null; this.steiner = false; } earcut.deviation = function(data, holeIndices, dim, triangles) { var hasHoles = holeIndices && holeIndices.length; var outerLen = hasHoles ? holeIndices[0] * dim : data.length; var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); if (hasHoles) for (var i = 0, len = holeIndices.length; i < len; i++) { var start = holeIndices[i] * dim; var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; polygonArea -= Math.abs(signedArea(data, start, end, dim)); } var trianglesArea = 0; for (i = 0; i < triangles.length; i += 3) { var a = triangles[i] * dim; var b = triangles[i + 1] * dim; var c = triangles[i + 2] * dim; trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); } return 0 === polygonArea && 0 === trianglesArea ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea); }; function signedArea(data, start, end, dim) { var sum = 0; for (var i = start, j = end - dim; i < end; i += dim) { sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); j = i; } return sum; } earcut.flatten = function(data) { var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0; for (var i = 0; i < data.length; i++) { for (var j = 0; j < data[i].length; j++) for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); if (i > 0) { holeIndex += data[i - 1].length; result.holes.push(holeIndex); } } return result; }; }), {} ], 170: [ (function(require, module, exports) { "use strict"; var Helper = require("../../../../graphics/helper"); var PointFlags = require("../../../../graphics/types").PointFlags; var Point = cc.Graphics.Point = cc.Class({ name: "cc.GraphicsPoint", extends: cc.Vec2, ctor: function ctor(x, y) { this.reset(); }, reset: function reset() { this.dx = 0; this.dy = 0; this.dmx = 0; this.dmy = 0; this.flags = 0; this.len = 0; } }); function Path() { this.reset(); } cc.js.mixin(Path.prototype, { reset: function reset() { this.closed = false; this.nbevel = 0; this.complex = true; this.points ? this.points.length = 0 : this.points = []; } }); function Impl(graphics) { this._tessTol = .25; this._distTol = .01; this._updatePathOffset = false; this._paths = null; this._pathLength = 0; this._pathOffset = 0; this._points = null; this._pointsOffset = 0; this._commandx = 0; this._commandy = 0; this._paths = []; this._points = []; } cc.js.mixin(Impl.prototype, { moveTo: function moveTo(x, y) { if (this._updatePathOffset) { this._pathOffset = this._pathLength; this._updatePathOffset = false; } this._addPath(); this._addPoint(x, y, PointFlags.PT_CORNER); this._commandx = x; this._commandy = y; }, lineTo: function lineTo(x, y) { this._addPoint(x, y, PointFlags.PT_CORNER); this._commandx = x; this._commandy = y; }, bezierCurveTo: function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) { var path = this._curPath; var last = path.points[path.points.length - 1]; if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) { this.lineTo(x, y); return; } Helper.tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER); this._commandx = x; this._commandy = y; }, quadraticCurveTo: function quadraticCurveTo(cx, cy, x, y) { var x0 = this._commandx; var y0 = this._commandy; this.bezierCurveTo(x0 + 2 / 3 * (cx - x0), y0 + 2 / 3 * (cy - y0), x + 2 / 3 * (cx - x), y + 2 / 3 * (cy - y), x, y); }, arc: function arc(cx, cy, r, startAngle, endAngle, counterclockwise) { Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); }, ellipse: function ellipse(cx, cy, rx, ry) { Helper.ellipse(this, cx, cy, rx, ry); this._curPath.complex = false; }, circle: function circle(cx, cy, r) { Helper.ellipse(this, cx, cy, r, r); this._curPath.complex = false; }, rect: function rect(x, y, w, h) { this.moveTo(x, y); this.lineTo(x, y + h); this.lineTo(x + w, y + h); this.lineTo(x + w, y); this.close(); this._curPath.complex = false; }, roundRect: function roundRect(x, y, w, h, r) { Helper.roundRect(this, x, y, w, h, r); this._curPath.complex = false; }, clear: function clear(clean) { this._pathLength = 0; this._pathOffset = 0; this._pointsOffset = 0; this._curPath = null; if (clean) { this._paths.length = 0; this._points.length = 0; } }, close: function close() { this._curPath.closed = true; }, _addPath: function _addPath() { var offset = this._pathLength; var path = this._paths[offset]; if (path) path.reset(); else { path = new Path(); this._paths.push(path); } this._pathLength++; this._curPath = path; return path; }, _addPoint: function _addPoint(x, y, flags) { var path = this._curPath; if (!path) return; var pt; var points = this._points; var pathPoints = path.points; var offset = this._pointsOffset++; pt = points[offset]; if (pt) { pt.x = x; pt.y = y; } else { pt = new Point(x, y); points.push(pt); } pt.flags = flags; pathPoints.push(pt); } }); cc.Graphics._Impl = Impl; module.exports = Impl; }), { "../../../../graphics/helper": 124, "../../../../graphics/types": 126 } ], 171: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler = _interopRequireDefault(require("../../../assembler")); var _inputAssembler = _interopRequireDefault(require("../../../../../renderer/core/input-assembler")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MeshBuffer = require("../../mesh-buffer"); var renderer = require("../../../index"); var Graphics = require("../../../../graphics/graphics"); var PointFlags = require("../../../../graphics/types").PointFlags; var LineJoin = Graphics.LineJoin; var LineCap = Graphics.LineCap; var Earcut = require("./earcut"); require("./impl"); var MAX_VERTEX = 65535; var MAX_INDICE = 2 * MAX_VERTEX; var PI = Math.PI; var min = Math.min; var max = Math.max; var ceil = Math.ceil; var acos = Math.acos; var cos = Math.cos; var sin = Math.sin; var atan2 = Math.atan2; function curveDivs(r, arc, tol) { var da = 2 * acos(r / (r + tol)); return max(2, ceil(arc / da)); } function clamp(v, min, max) { if (v < min) return min; if (v > max) return max; return v; } var gfx = cc.gfx; var vfmtPosColorSdf = new gfx.VertexFormat([ { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true }, { name: "a_dist", type: gfx.ATTR_TYPE_FLOAT32, num: 1 } ]); vfmtPosColorSdf.name = "vfmtPosColorSdf"; var GraphicsAssembler = (function(_Assembler) { _inheritsLoose(GraphicsAssembler, _Assembler); function GraphicsAssembler(graphics) { var _this; _this = _Assembler.call(this, graphics) || this; _this._buffer = null; _this._buffers = []; _this._bufferOffset = 0; return _this; } var _proto = GraphicsAssembler.prototype; _proto.getVfmt = function getVfmt() { return vfmtPosColorSdf; }; _proto.getVfmtFloatCount = function getVfmtFloatCount() { return 4; }; _proto.requestBuffer = function requestBuffer() { var buffer = { indiceStart: 0, vertexStart: 0 }; var meshbuffer = new MeshBuffer(renderer._handle, this.getVfmt()); buffer.meshbuffer = meshbuffer; var ia = new _inputAssembler["default"](meshbuffer._vb, meshbuffer._ib); buffer.ia = ia; this._buffers.push(buffer); return buffer; }; _proto.getBuffers = function getBuffers() { 0 === this._buffers.length && this.requestBuffer(); return this._buffers; }; _proto.clear = function clear(clean) { this._bufferOffset = 0; var datas = this._buffers; if (clean) { for (var i = 0, l = datas.length; i < l; i++) { var data = datas[i]; data.meshbuffer.destroy(); data.meshbuffer = null; } datas.length = 0; } else for (var _i = 0, _l = datas.length; _i < _l; _i++) { var _data = datas[_i]; _data.indiceStart = 0; _data.vertexStart = 0; var meshbuffer = _data.meshbuffer; meshbuffer.reset(); } }; _proto.fillBuffers = function fillBuffers(graphics, renderer) { renderer._flush(); renderer.node = graphics.node; renderer.material = graphics._materials[0]; var buffers = this.getBuffers(); for (var index = 0, length = buffers.length; index < length; index++) { var buffer = buffers[index]; var meshbuffer = buffer.meshbuffer; buffer.ia._count = buffer.indiceStart; renderer._flushIA(buffer.ia); meshbuffer.uploadData(); } }; _proto.genBuffer = function genBuffer(graphics, cverts) { var buffers = this.getBuffers(); var buffer = buffers[this._bufferOffset]; var meshbuffer = buffer.meshbuffer; var maxVertsCount = buffer.vertexStart + cverts; if (maxVertsCount > MAX_VERTEX || 3 * maxVertsCount > MAX_INDICE) { ++this._bufferOffset; maxVertsCount = cverts; if (this._bufferOffset < buffers.length) buffer = buffers[this._bufferOffset]; else { buffer = this.requestBuffer(graphics); buffers[this._bufferOffset] = buffer; } meshbuffer = buffer.meshbuffer; } maxVertsCount > meshbuffer.vertexOffset && meshbuffer.requestStatic(cverts, 3 * cverts); this._buffer = buffer; return buffer; }; _proto.stroke = function stroke(graphics) { this._curColor = graphics._strokeColor._val; this._flattenPaths(graphics._impl); this._expandStroke(graphics); graphics._impl._updatePathOffset = true; }; _proto.fill = function fill(graphics) { this._curColor = graphics._fillColor._val; this._expandFill(graphics); graphics._impl._updatePathOffset = true; }; _proto._expandStroke = function _expandStroke(graphics) { var w = .5 * graphics.lineWidth, lineCap = graphics.lineCap, lineJoin = graphics.lineJoin, miterLimit = graphics.miterLimit; var impl = graphics._impl; var ncap = curveDivs(w, PI, impl._tessTol); this._calculateJoins(impl, w, lineJoin, miterLimit); var paths = impl._paths; var cverts = 0; for (var i = impl._pathOffset, l = impl._pathLength; i < l; i++) { var path = paths[i]; var pointsLength = path.points.length; lineJoin === LineJoin.ROUND ? cverts += 2 * (pointsLength + path.nbevel * (ncap + 2) + 1) : cverts += 2 * (pointsLength + 5 * path.nbevel + 1); path.closed || (lineCap === LineCap.ROUND ? cverts += 2 * (2 * ncap + 2) : cverts += 12); } var buffer = this.genBuffer(graphics, cverts), meshbuffer = buffer.meshbuffer, vData = meshbuffer._vData, iData = meshbuffer._iData; for (var _i2 = impl._pathOffset, _l2 = impl._pathLength; _i2 < _l2; _i2++) { var _path = paths[_i2]; var pts = _path.points; var _pointsLength = pts.length; var offset = buffer.vertexStart; var p0 = void 0, p1 = void 0; var start = void 0, end = void 0, loop = void 0; loop = _path.closed; if (loop) { p0 = pts[_pointsLength - 1]; p1 = pts[0]; start = 0; end = _pointsLength; } else { p0 = pts[0]; p1 = pts[1]; start = 1; end = _pointsLength - 1; } p1 = p1 || p0; if (!loop) { var dPos = p1.sub(p0); dPos.normalizeSelf(); var dx = dPos.x; var dy = dPos.y; lineCap === LineCap.BUTT ? this._buttCapStart(p0, dx, dy, w, 0) : lineCap === LineCap.SQUARE ? this._buttCapStart(p0, dx, dy, w, w) : lineCap === LineCap.ROUND && this._roundCapStart(p0, dx, dy, w, ncap); } for (var j = start; j < end; ++j) { if (lineJoin === LineJoin.ROUND) this._roundJoin(p0, p1, w, w, ncap); else if (0 !== (p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL))) this._bevelJoin(p0, p1, w, w); else { this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w, 1); this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w, -1); } p0 = p1; p1 = pts[j + 1]; } if (loop) { var floatCount = this.getVfmtFloatCount(); var vDataoOfset = offset * floatCount; this._vset(vData[vDataoOfset], vData[vDataoOfset + 1], 1); this._vset(vData[vDataoOfset + floatCount], vData[vDataoOfset + floatCount + 1], -1); } else { var _dPos = p1.sub(p0); _dPos.normalizeSelf(); var _dx = _dPos.x; var _dy = _dPos.y; lineCap === LineCap.BUTT ? this._buttCapEnd(p1, _dx, _dy, w, 0) : lineCap === LineCap.SQUARE ? this._buttCapEnd(p1, _dx, _dy, w, w) : lineCap === LineCap.ROUND && this._roundCapEnd(p1, _dx, _dy, w, ncap); } var indicesOffset = buffer.indiceStart; for (var _start = offset + 2, _end = buffer.vertexStart; _start < _end; _start++) { iData[indicesOffset++] = _start - 2; iData[indicesOffset++] = _start - 1; iData[indicesOffset++] = _start; } buffer.indiceStart = indicesOffset; } }; _proto._expandFill = function _expandFill(graphics) { var impl = graphics._impl; var paths = impl._paths; var cverts = 0; for (var i = impl._pathOffset, l = impl._pathLength; i < l; i++) { var path = paths[i]; var pointsLength = path.points.length; cverts += pointsLength; } var buffer = this.genBuffer(graphics, cverts), meshbuffer = buffer.meshbuffer, vData = meshbuffer._vData, iData = meshbuffer._iData; for (var _i3 = impl._pathOffset, _l3 = impl._pathLength; _i3 < _l3; _i3++) { var _path2 = paths[_i3]; var pts = _path2.points; var _pointsLength2 = pts.length; if (0 === _pointsLength2) continue; var offset = buffer.vertexStart; for (var j = 0; j < _pointsLength2; ++j) this._vset(pts[j].x, pts[j].y); var indicesOffset = buffer.indiceStart; if (_path2.complex) { var earcutData = []; var floatCount = this.getVfmtFloatCount(); for (var _j = offset, end = buffer.vertexStart; _j < end; _j++) { var vDataOffset = _j * floatCount; earcutData.push(vData[vDataOffset]); earcutData.push(vData[vDataOffset + 1]); } var newIndices = Earcut(earcutData, null, 2); if (!newIndices || 0 === newIndices.length) continue; for (var _j2 = 0, nIndices = newIndices.length; _j2 < nIndices; _j2++) iData[indicesOffset++] = newIndices[_j2] + offset; } else { var first = offset; for (var start = offset + 2, _end2 = buffer.vertexStart; start < _end2; start++) { iData[indicesOffset++] = first; iData[indicesOffset++] = start - 1; iData[indicesOffset++] = start; } } buffer.indiceStart = indicesOffset; } }; _proto._calculateJoins = function _calculateJoins(impl, w, lineJoin, miterLimit) { var iw = 0; var w2 = w * w; w > 0 && (iw = 1 / w); var paths = impl._paths; for (var i = impl._pathOffset, l = impl._pathLength; i < l; i++) { var path = paths[i]; var pts = path.points; var ptsLength = pts.length; var p0 = pts[ptsLength - 1]; var p1 = pts[0]; var nleft = 0; path.nbevel = 0; for (var j = 0; j < ptsLength; j++) { var dmr2 = void 0, cross = void 0, limit = void 0; var dlx0 = p0.dy; var dly0 = -p0.dx; var dlx1 = p1.dy; var dly1 = -p1.dx; p1.dmx = .5 * (dlx0 + dlx1); p1.dmy = .5 * (dly0 + dly1); dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy; if (dmr2 > 1e-6) { var scale = 1 / dmr2; scale > 600 && (scale = 600); p1.dmx *= scale; p1.dmy *= scale; } cross = p1.dx * p0.dy - p0.dx * p1.dy; if (cross > 0) { nleft++; p1.flags |= PointFlags.PT_LEFT; } limit = max(11, min(p0.len, p1.len) * iw); dmr2 * limit * limit < 1 && (p1.flags |= PointFlags.PT_INNERBEVEL); var dmwx = p1.dmx * w; var dmwy = p1.dmy * w; var dmlen2 = dmwx * dmwx + dmwy * dmwy; dmlen2 > p1.len * p1.len + w2 && dmlen2 > p0.len * p0.len + w2 && (p1.flags |= PointFlags.PT_INNERBEVEL); p1.flags & PointFlags.PT_CORNER && (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) && (p1.flags |= PointFlags.PT_BEVEL); 0 !== (p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) && path.nbevel++; p0 = p1; p1 = pts[j + 1]; } } }; _proto._flattenPaths = function _flattenPaths(impl) { var paths = impl._paths; for (var i = impl._pathOffset, l = impl._pathLength; i < l; i++) { var path = paths[i]; var pts = path.points; var p0 = pts[pts.length - 1]; var p1 = pts[0]; if (pts.length > 2 && p0.equals(p1)) { path.closed = true; pts.pop(); p0 = pts[pts.length - 1]; } for (var j = 0, size = pts.length; j < size; j++) { var dPos = p1.sub(p0); p0.len = dPos.mag(); (dPos.x || dPos.y) && dPos.normalizeSelf(); p0.dx = dPos.x; p0.dy = dPos.y; p0 = p1; p1 = pts[j + 1]; } } }; _proto._chooseBevel = function _chooseBevel(bevel, p0, p1, w) { var x = p1.x; var y = p1.y; var x0, y0, x1, y1; if (0 !== bevel) { x0 = x + p0.dy * w; y0 = y - p0.dx * w; x1 = x + p1.dy * w; y1 = y - p1.dx * w; } else { x0 = x1 = x + p1.dmx * w; y0 = y1 = y + p1.dmy * w; } return [ x0, y0, x1, y1 ]; }; _proto._buttCapStart = function _buttCapStart(p, dx, dy, w, d) { var px = p.x - dx * d; var py = p.y - dy * d; var dlx = dy; var dly = -dx; this._vset(px + dlx * w, py + dly * w, 1); this._vset(px - dlx * w, py - dly * w, -1); }; _proto._buttCapEnd = function _buttCapEnd(p, dx, dy, w, d) { var px = p.x + dx * d; var py = p.y + dy * d; var dlx = dy; var dly = -dx; this._vset(px + dlx * w, py + dly * w, 1); this._vset(px - dlx * w, py - dly * w, -1); }; _proto._roundCapStart = function _roundCapStart(p, dx, dy, w, ncap) { var px = p.x; var py = p.y; var dlx = dy; var dly = -dx; for (var i = 0; i < ncap; i++) { var a = i / (ncap - 1) * PI; var ax = cos(a) * w, ay = sin(a) * w; this._vset(px - dlx * ax - dx * ay, py - dly * ax - dy * ay, 1); this._vset(px, py, 0); } this._vset(px + dlx * w, py + dly * w, 1); this._vset(px - dlx * w, py - dly * w, -1); }; _proto._roundCapEnd = function _roundCapEnd(p, dx, dy, w, ncap) { var px = p.x; var py = p.y; var dlx = dy; var dly = -dx; this._vset(px + dlx * w, py + dly * w, 1); this._vset(px - dlx * w, py - dly * w, -1); for (var i = 0; i < ncap; i++) { var a = i / (ncap - 1) * PI; var ax = cos(a) * w, ay = sin(a) * w; this._vset(px, py, 0); this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay, 1); } }; _proto._roundJoin = function _roundJoin(p0, p1, lw, rw, ncap) { var dlx0 = p0.dy; var dly0 = -p0.dx; var dlx1 = p1.dy; var dly1 = -p1.dx; var p1x = p1.x; var p1y = p1.y; if (0 !== (p1.flags & PointFlags.PT_LEFT)) { var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); var lx0 = out[0]; var ly0 = out[1]; var lx1 = out[2]; var ly1 = out[3]; var a0 = atan2(-dly0, -dlx0); var a1 = atan2(-dly1, -dlx1); a1 > a0 && (a1 -= 2 * PI); this._vset(lx0, ly0, 1); this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw, -1); var n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap); for (var i = 0; i < n; i++) { var u = i / (n - 1); var a = a0 + u * (a1 - a0); var rx = p1x + cos(a) * rw; var ry = p1y + sin(a) * rw; this._vset(p1x, p1y, 0); this._vset(rx, ry, -1); } this._vset(lx1, ly1, 1); this._vset(p1x - dlx1 * rw, p1y - dly1 * rw, -1); } else { var _out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); var rx0 = _out[0]; var ry0 = _out[1]; var rx1 = _out[2]; var ry1 = _out[3]; var _a = atan2(dly0, dlx0); var _a2 = atan2(dly1, dlx1); _a2 < _a && (_a2 += 2 * PI); this._vset(p1x + dlx0 * rw, p1y + dly0 * rw, 1); this._vset(rx0, ry0, -1); var _n = clamp(ceil((_a2 - _a) / PI) * ncap, 2, ncap); for (var _i4 = 0; _i4 < _n; _i4++) { var _u = _i4 / (_n - 1); var _a3 = _a + _u * (_a2 - _a); var lx = p1x + cos(_a3) * lw; var ly = p1y + sin(_a3) * lw; this._vset(lx, ly, 1); this._vset(p1x, p1y, 0); } this._vset(p1x + dlx1 * rw, p1y + dly1 * rw, 1); this._vset(rx1, ry1, -1); } }; _proto._bevelJoin = function _bevelJoin(p0, p1, lw, rw) { var rx0, ry0, rx1, ry1; var lx0, ly0, lx1, ly1; var dlx0 = p0.dy; var dly0 = -p0.dx; var dlx1 = p1.dy; var dly1 = -p1.dx; if (p1.flags & PointFlags.PT_LEFT) { var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); lx0 = out[0]; ly0 = out[1]; lx1 = out[2]; ly1 = out[3]; this._vset(lx0, ly0, 1); this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw, -1); this._vset(lx1, ly1, 1); this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw, -1); } else { var _out2 = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); rx0 = _out2[0]; ry0 = _out2[1]; rx1 = _out2[2]; ry1 = _out2[3]; this._vset(p1.x + dlx0 * lw, p1.y + dly0 * lw, 1); this._vset(rx0, ry0, -1); this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw, 1); this._vset(rx1, ry1, -1); } }; _proto._vset = function _vset(x, y, distance) { void 0 === distance && (distance = 0); var buffer = this._buffer; var meshbuffer = buffer.meshbuffer; var dataOffset = buffer.vertexStart * this.getVfmtFloatCount(); var vData = meshbuffer._vData; var uintVData = meshbuffer._uintVData; vData[dataOffset] = x; vData[dataOffset + 1] = y; uintVData[dataOffset + 2] = this._curColor; vData[dataOffset + 3] = distance; buffer.vertexStart++; meshbuffer._dirty = true; }; return GraphicsAssembler; })(_assembler["default"]); exports["default"] = GraphicsAssembler; _assembler["default"].register(cc.Graphics, GraphicsAssembler); module.exports = exports["default"]; }), { "../../../../../renderer/core/input-assembler": 249, "../../../../graphics/graphics": 123, "../../../../graphics/types": 126, "../../../assembler": 157, "../../../index": 160, "../../mesh-buffer": 197, "./earcut": 169, "./impl": 170 } ], 172: [ (function(require, module, exports) { "use strict"; cc.assemblers = {}; require("./sprite"); require("./mask-assembler"); require("./graphics"); require("./label"); require("./motion-streak"); require("./motion-streak-multi"); }), { "./graphics": 171, "./label": 179, "./mask-assembler": 180, "./motion-streak": 182, "./motion-streak-multi": 181, "./sprite": 195 } ], 173: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _bmfont = _interopRequireDefault(require("../2d/bmfont")); var _vertexFormat = require("../../../../webgl/vertex-format"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MultiWebglBmfontAssembler = (function(_WebglBmfontAssembler) { _inheritsLoose(MultiWebglBmfontAssembler, _WebglBmfontAssembler); function MultiWebglBmfontAssembler() { return _WebglBmfontAssembler.apply(this, arguments) || this; } var _proto = MultiWebglBmfontAssembler.prototype; _proto.initData = function initData() { var data = this._renderData; data.createFlexData(0, this.verticesCount, this.indicesCount, this.getVfmt()); }; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(comp) { _WebglBmfontAssembler.prototype.updateRenderData.call(this, comp); comp._texIdDirty && comp._updateMultiTexId(comp.getMaterial(0), comp._frame._texture); this.updateTexId(comp); comp._texIdDirty = false; }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(comp) { _WebglBmfontAssembler.prototype._preUpdateRenderData.call(this, comp); _WebglBmfontAssembler.prototype._aftUpdateRenderData.call(this, comp); comp._texIdDirty && comp._updateMultiTexId(comp.getMaterial(0), comp._frame._texture); this.updateTexId(comp); comp._texIdDirty = false; false; }; return MultiWebglBmfontAssembler; })(_bmfont["default"]); exports["default"] = MultiWebglBmfontAssembler; MultiWebglBmfontAssembler.prototype.floatsPerVert = 6; MultiWebglBmfontAssembler.prototype.texIdOffset = 5; MultiWebglBmfontAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/bmfont": 175 } ], 174: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _ttf = _interopRequireDefault(require("../2d/ttf")); var _vertexFormat = require("../../../../webgl/vertex-format"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MultiWebglTTFAssembler = (function(_WebglTTFAssembler) { _inheritsLoose(MultiWebglTTFAssembler, _WebglTTFAssembler); function MultiWebglTTFAssembler() { return _WebglTTFAssembler.apply(this, arguments) || this; } var _proto = MultiWebglTTFAssembler.prototype; _proto.initData = function initData() { var data = this._renderData; data.createFlexData(0, this.verticesCount, this.indicesCount, this.getVfmt()); var indices = data.iDatas[0]; data.initQuadIndices(indices); }; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(comp) { _WebglTTFAssembler.prototype.updateRenderData.call(this, comp); comp._texIdDirty && comp._updateMultiTexId(comp.getMaterial(0), comp._frame._texture); this.updateTexId(comp); comp._texIdDirty = false; }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(comp) { _WebglTTFAssembler.prototype._aftUpdateRenderData.call(this, comp); comp._texIdDirty && comp._updateMultiTexId(comp.getMaterial(0), comp._frame._texture); this.updateTexId(comp); comp._texIdDirty = false; false; }; return MultiWebglTTFAssembler; })(_ttf["default"]); exports["default"] = MultiWebglTTFAssembler; MultiWebglTTFAssembler.prototype.floatsPerVert = 6; MultiWebglTTFAssembler.prototype.texIdOffset = 5; MultiWebglTTFAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/ttf": 178 } ], 175: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _bmfont = _interopRequireDefault(require("../../../../utils/label/bmfont")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _dataOffset = 0; var WebglBmfontAssembler = (function(_BmfontAssembler) { _inheritsLoose(WebglBmfontAssembler, _BmfontAssembler); function WebglBmfontAssembler() { return _BmfontAssembler.apply(this, arguments) || this; } var _proto = WebglBmfontAssembler.prototype; _proto.initData = function initData() { this._renderData.createFlexData(0, 4, 6, this.getVfmt()); }; _proto._reserveQuads = function _reserveQuads(comp, count) { var verticesCount = 4 * count; var indicesCount = 6 * count; var flexBuffer = this._renderData._flexBuffer; flexBuffer.reserve(verticesCount, indicesCount); flexBuffer.used(verticesCount, indicesCount); var iData = this._renderData.iDatas[0]; for (var i = 0, vid = 0, l = indicesCount; i < l; i += 6, vid += 4) { iData[i] = vid; iData[i + 1] = vid + 1; iData[i + 2] = vid + 2; iData[i + 3] = vid + 1; iData[i + 4] = vid + 3; iData[i + 5] = vid + 2; } _dataOffset = 0; }; _proto._quadsUpdated = function _quadsUpdated(comp) { _dataOffset = 0; var flexBuffer = this._renderData._flexBuffer; flexBuffer.used(this.verticesCount, this.indicesCount); }; _proto._getColor = function _getColor(comp) { return comp.node._color._val; }; _proto.appendQuad = function appendQuad(comp, texture, rect, rotated, x, y, scale, letter) { var renderData = this._renderData; var verts = renderData.vDatas[0], uintVerts = renderData.uintVDatas[0]; this.verticesCount += 4; this.indicesCount = this.verticesCount / 2 * 3; var texw = texture.width, texh = texture.height, rectWidth = rect.width, rectHeight = rect.height, color = this._getColor(comp); var l, b, r, t; var floatsPerVert = this.floatsPerVert; var uvDataOffset = _dataOffset + this.uvOffset; if (rotated) { l = rect.x / texw; r = (rect.x + rectHeight) / texw; b = (rect.y + rectWidth) / texh; t = rect.y / texh; verts[uvDataOffset] = l; verts[uvDataOffset + 1] = t; uvDataOffset += floatsPerVert; verts[uvDataOffset] = l; verts[uvDataOffset + 1] = b; uvDataOffset += floatsPerVert; verts[uvDataOffset] = r; verts[uvDataOffset + 1] = t; uvDataOffset += floatsPerVert; verts[uvDataOffset] = r; verts[uvDataOffset + 1] = b; } else { l = rect.x / texw; r = (rect.x + rectWidth) / texw; b = (rect.y + rectHeight) / texh; t = rect.y / texh; verts[uvDataOffset] = l; verts[uvDataOffset + 1] = b; uvDataOffset += floatsPerVert; verts[uvDataOffset] = r; verts[uvDataOffset + 1] = b; uvDataOffset += floatsPerVert; verts[uvDataOffset] = l; verts[uvDataOffset + 1] = t; uvDataOffset += floatsPerVert; verts[uvDataOffset] = r; verts[uvDataOffset + 1] = t; } var retinaScale = this.getTTFTextureSizeScale(); x /= retinaScale; y /= retinaScale; rectWidth /= retinaScale; rectHeight /= retinaScale; l = x; r = x + rectWidth * scale; b = y - rectHeight * scale; t = y; this.appendVerts(comp, _dataOffset, l, r, b, t, letter); var colorOffset = _dataOffset + this.colorOffset; for (var i = 0; i < 4; i++) { uintVerts[colorOffset] = color; colorOffset += floatsPerVert; } _dataOffset += 4 * this.floatsPerVert; }; _proto.appendVerts = function appendVerts(comp, offset, l, r, b, t, letter) { var local = this._local; var floatsPerVert = this.floatsPerVert; local[offset] = l; local[offset + 1] = b; offset += floatsPerVert; local[offset] = r; local[offset + 1] = b; offset += floatsPerVert; local[offset] = l; local[offset + 1] = t; offset += floatsPerVert; local[offset] = r; local[offset + 1] = t; }; _proto.updateWorldVerts = function updateWorldVerts(comp) { var node = comp.node; var matrix = node._worldMatrix; var matrixm = matrix.m, a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5], tx = matrixm[12], ty = matrixm[13]; var local = this._local; var world = this._renderData.vDatas[0]; var floatsPerVert = this.floatsPerVert; for (var offset = 0; offset < local.length; offset += floatsPerVert) { var x = local[offset]; var y = local[offset + 1]; world[offset] = x * a + y * c + tx; world[offset + 1] = x * b + y * d + ty; } }; return WebglBmfontAssembler; })(_bmfont["default"]); exports["default"] = WebglBmfontAssembler; module.exports = exports["default"]; }), { "../../../../utils/label/bmfont": 164 } ], 176: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var js = require("../../../../../platform/js"); var WebglBmfontAssembler = require("./bmfont"); var LetterFontAssembler = require("../../../../utils/label/letter-font"); var WHITE = cc.color(255, 255, 255, 255); var WebglLetterFontAssembler = (function(_LetterFontAssembler) { _inheritsLoose(WebglLetterFontAssembler, _LetterFontAssembler); function WebglLetterFontAssembler() { return _LetterFontAssembler.apply(this, arguments) || this; } var _proto = WebglLetterFontAssembler.prototype; _proto.createData = function createData(comp) { return comp.requestRenderData(); }; _proto._getColor = function _getColor(comp) { WHITE._fastSetA(comp.node._color.a); return WHITE._val; }; _proto.updateColor = function updateColor(comp) { var color = this._getColor(comp); _LetterFontAssembler.prototype.updateColor.call(this, comp, color); }; return WebglLetterFontAssembler; })(LetterFontAssembler); exports["default"] = WebglLetterFontAssembler; module.exports = exports["default"]; }), { "../../../../../platform/js": 150, "../../../../utils/label/letter-font": 166, "./bmfont": 175 } ], 177: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _materialVariant = _interopRequireDefault(require("../../../../../assets/material/material-variant")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Label = require("../../../../../components/CCLabel"); var LabelShadow = require("../../../../../components/CCLabelShadow"); var LabelOutline = require("../../../../../components/CCLabelOutline"); var Material = require("../../../../../assets/material/CCMaterial"); var UPDATE_CONTENT = 1; var UPDATE_FONT = 2; var UPDATE_EFFECT = 4; var NativeTTF = (function() { function NativeTTF() {} var _proto = NativeTTF.prototype; _proto.init = function init(comp) { this.labelMaterial = null; this._label = this._renderComp = comp; renderer.CustomAssembler.prototype.ctor.call(this); comp.node._proxy.setAssembler(this); this._layout = new jsb.LabelRenderer(); this._layout.init(comp); this._cfg = new DataView(this._layout._cfg); this._layoutInfo = new DataView(this._layout._layout); this._cfgFields = jsb.LabelRenderer._cfgFields; this._layoutFields = jsb.LabelRenderer._layoutFields; this._layout.bindNodeProxy(comp.node._proxy); this._bindMaterial(comp); }; _proto._setBufferFlag = function _setBufferFlag(dv, offset, size, type, flag) { if ("int8" == type && 1 == size) { var v = dv.getInt8(offset); dv.setInt8(offset, flag | v); } else if ("int32" == type && 4 == size) { var _v = dv.getInt32(offset, jsb.__isLittleEndian__); dv.setInt32(offset, flag | _v, jsb.__isLittleEndian__); } else cc.warn("flag storage type should be int8/int32 only, type/size -> " + type + "/" + size + "."); }; _proto._updateCfgFlag = function _updateCfgFlag(flag) { var field = this._cfgFields.updateFlags; this._setBufferFlag(this._cfg, field.offset, field.size, field.type, flag); }; _proto._setBufferValue = function _setBufferValue(dv, offset, size, type, value) { if ("float" == type && 4 == size) dv.setFloat32(offset, value, jsb.__isLittleEndian__); else if ("int32" == type && 4 == size) dv.setInt32(offset, value, jsb.__isLittleEndian__); else if ("bool" == type && 1 == size) dv.setInt8(offset, !value ? 0 : 1, jsb.__isLittleEndian__); else if ("Color4B" == type && 4 == size) { dv.setUint8(offset, value.r); dv.setUint8(offset + 1, value.g); dv.setUint8(offset + 2, value.b); dv.setUint8(offset + 3, value.a); } else "int8" == type && 1 == size ? dv.setUint8(offset, value) : cc.warn("dont know how to set value to buffer, type/size -> " + type + "/" + size + "."); }; _proto._setFieldValue = function _setFieldValue(dv, desc, field_name, value) { var field = desc[field_name]; this._setBufferValue(dv, field.offset, field.size, field.type, value); }; _proto._getBufferValue = function _getBufferValue(dv, offset, size, type) { if ("float" == type && 4 == size) return dv.getFloat32(offset, jsb.__isLittleEndian__); if ("int32" == type && 4 == size) return dv.getInt32(offset, jsb.__isLittleEndian__); if ("bool" == type && 1 == size) return 0 != dv.getInt8(offset, jsb.__isLittleEndian__); if ("Color4B" == type && 4 == size) { var r = dv.getUint8(offset); var g = dv.getUint8(offset + 1); var b = dv.getUint8(offset + 2); var a = dv.getUint8(offset + 3); return { r: r, g: g, b: b, a: a }; } if ("int8" == type && 1 == size) return dv.getUint8(offset); cc.warn("dont know how to get value from buffer, type/size -> " + type + "/" + size + "."); return; }; _proto._getFieldValue = function _getFieldValue(dv, desc, field_name) { var field = desc[field_name]; return this._getBufferValue(dv, field.offset, field.size, field.type); }; _proto._getLayoutValue = function _getLayoutValue(field_name) { return this._getFieldValue(this._layoutInfo, this._layoutFields, field_name); }; _proto._setLayoutValue = function _setLayoutValue(field_name, value) { return this._setFieldValue(this._layoutInfo, this._layoutFields, field_name, value); }; _proto._updateCfgFlag_Content = function _updateCfgFlag_Content() { this._updateCfgFlag(UPDATE_CONTENT); }; _proto._updateCfgFlag_Font = function _updateCfgFlag_Font() { this._updateCfgFlag(UPDATE_FONT); }; _proto._colorEqual = function _colorEqual(a, b) { return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a; }; _proto._colorToObj = function _colorToObj(r, g, b, a) { return { r: r, g: g, b: b, a: a }; }; _proto.setString = function setString(str) { if (str != this._layout.string) { this._layout.string = str; this._updateCfgFlag_Content(); } }; _proto.setFontPath = function setFontPath(path) { if (path != this._layout.fontPath) { this._layout.fontPath = path; this._updateCfgFlag_Font(); } }; _proto.setFontSize = function setFontSize(fontSize, fontSizeRetina) { var oldfontsize = this._getFieldValue(this._cfg, this._cfgFields, "fontSize"); if (oldfontsize != fontSize) { this._setFieldValue(this._cfg, this._cfgFields, "fontSize", fontSize); this._setFieldValue(this._cfg, this._cfgFields, "fontSizeRetina", fontSizeRetina); this._updateCfgFlag_Font(); } }; _proto.setOutline = function setOutline(outline) { var oldOutline = this._getLayoutValue("outlineSize"); oldOutline > 0 != outline > 0 && this._updateCfgFlag_Font(); if (oldOutline != outline) { this._updateCfgFlag_Content(); this._setLayoutValue("outlineSize", outline); } }; _proto.setOutlineColor = function setOutlineColor(color) { var oldColor = this._getLayoutValue("outlineColor"); if (!this._colorEqual(oldColor, color)) { this._setLayoutValue("outlineColor", color); this._updateCfgFlag_Content(); } }; _proto.setLineHeight = function setLineHeight(lineHeight) { var oldLineHeight = this._getLayoutValue("lineHeight"); if (oldLineHeight != lineHeight) { this._setLayoutValue("lineHeight", lineHeight); this._updateCfgFlag_Content(); } }; _proto.setOverFlow = function setOverFlow(overflow) { var oldValue = this._getLayoutValue("overflow"); if (oldValue != overflow) { this._setLayoutValue("overflow", overflow); this._updateCfgFlag_Content(); } }; _proto.setEnableWrap = function setEnableWrap(value) { var oldValue = this._getLayoutValue("wrap"); if (oldValue != value) { this._setLayoutValue("wrap", value); this._updateCfgFlag_Content(); } }; _proto.setVerticalAlign = function setVerticalAlign(value) { var oldValue = this._getLayoutValue("valign"); if (oldValue != value) { this._setLayoutValue("valign", value); this._updateCfgFlag_Content(); } }; _proto.setHorizontalAlign = function setHorizontalAlign(value) { var oldValue = this._getLayoutValue("halign"); if (oldValue != value) { this._setLayoutValue("halign", value); this._updateCfgFlag_Content(); } }; _proto.setContentSize = function setContentSize(width, height) { var oldWidth = this._getLayoutValue("width"); var oldHeight = this._getLayoutValue("height"); if (oldWidth != width || oldHeight != height) { this._setLayoutValue("height", height); this._setLayoutValue("width", width); this._updateCfgFlag_Content(); } }; _proto.setAnchorPoint = function setAnchorPoint(x, y) { var oldX = this._getLayoutValue("anchorX"); var oldY = this._getLayoutValue("anchorY"); if (oldX != x || oldY != y) { this._setLayoutValue("anchorX", x); this._setLayoutValue("anchorY", y); this._updateCfgFlag_Content(); } }; _proto.setColor = function setColor(color) { var oldColor = this._getLayoutValue("color"); if (!this._colorEqual(oldColor, color)) { this._setLayoutValue("color", color); this._updateCfgFlag_Content(); } }; _proto.setShadow = function setShadow(x, y, blur) { var oldBlur = this._getLayoutValue("shadowBlur"); var oldX = this._getLayoutValue("shadowX"); var oldY = this._getLayoutValue("shadowY"); oldBlur > 0 != blur > 0 && this._updateCfgFlag_Font(); var updateContent = false; if (oldBlur != blur) { this._setLayoutValue("shadowBlur", blur); updateContent = true; } if (oldX != x) { this._setLayoutValue("shadowX", x); updateContent = true; } if (oldY != y) { this._setLayoutValue("shadowY", y); updateContent = true; } updateContent && this._updateCfgFlag_Content(); }; _proto.setShadowColor = function setShadowColor(color) { var oldColor = this._getLayoutValue("shadowColor"); if (!this._colorEqual(oldColor, color)) { this._setLayoutValue("shadowColor", color); this._updateCfgFlag_Content(); } }; _proto.setItalic = function setItalic(enabled) { var oldItalic = this._getLayoutValue("italic"); if (oldItalic != enabled) { this._setLayoutValue("italic", enabled); this._updateCfgFlag_Content(); } }; _proto.setBold = function setBold(bold) { var oldBold = this._getLayoutValue("bold"); if (oldBold != bold) { this._setLayoutValue("bold", bold); this._updateCfgFlag_Content(); this._updateCfgFlag_Font(); } }; _proto.setUnderline = function setUnderline(underline) { var oldBold = this._getLayoutValue("underline"); if (oldBold != underline) { this._setLayoutValue("underline", underline); this._updateCfgFlag_Content(); } }; _proto.setSpacingX = function setSpacingX(x) { var oldX = this._getLayoutValue("spaceX"); if (oldX != x && "number" == typeof x && !isNaN(x)) { this._setLayoutValue("spaceX", x); this._updateCfgFlag_Content(); } }; _proto.updateRenderData = function updateRenderData(comp) { if (!comp._vertsDirty) return; comp.font && comp.font.nativeUrl && this.setFontPath(cc.assetManager.cacheManager.getCache(comp.font.nativeUrl) || comp.font.nativeUrl); var layout = this._layout; var c = comp.node.color; var node = comp.node; var retinaSize = comp.fontSize; this.setString(comp.string); this.setFontSize(comp.fontSize, retinaSize / 72 * comp.fontSize); this.setLineHeight(comp.lineHeight); this.setEnableWrap(comp.enableWrapText); this.setItalic(comp.enableItalic); this.setUnderline(comp.enableUnderline); this.setBold(comp.enableBold); this.setOverFlow(comp.overflow); this.setVerticalAlign(comp.verticalAlign); this.setHorizontalAlign(comp.horizontalAlign); this.setSpacingX(comp.spacingX); this.setContentSize(node.getContentSize().width, node.getContentSize().height); this.setAnchorPoint(node.anchorX, node.anchorY); this.setColor(this._colorToObj(c.getR(), c.getG(), c.getB(), Math.ceil(c.getA() * node.opacity / 255))); var shadow = node.getComponent(cc.LabelShadow); if (shadow && shadow.enabled) { var shadowColor = shadow.color; this.setShadow(shadow.offset.x, shadow.offset.y, shadow.blur); this.setShadowColor(this._colorToObj(shadowColor.getR(), shadowColor.getG(), shadowColor.getB(), Math.ceil(shadowColor.getA() * node.opacity / 255))); } else this.setShadow(0, 0, -1); this._updateTTFMaterial(comp); layout.render(); }; _proto._bindMaterial = function _bindMaterial(comp) { var material = this.labelMaterial; if (!material) { material = _materialVariant["default"].createWithBuiltin("2d-label", comp); this.labelMaterial = material; } return material; }; _proto._updateTTFMaterial = function _updateTTFMaterial(comp) { var material = this._bindMaterial(comp); var node = this._label.node; var layout = this._layout; var outline = node.getComponent(cc.LabelOutline); var outlineSize = 0; if (outline && outline.enabled && outline.width > 0) { outlineSize = Math.max(Math.min(outline.width / 10, .4), .1); var c = outline.color; this.setOutlineColor(this._colorToObj(c.getR(), c.getG(), c.getB(), Math.ceil(c.getA() * node.opacity / 255))); } this.setOutline(outlineSize); material.define("CC_USE_MODEL", true); material.define("USE_TEXTURE_ALPHAONLY", true); material.define("USE_SDF", outlineSize > 0 || comp.enableBold); material.define("USE_SDF_EXTEND", comp.enableBold ? 1 : 0); void 0 !== material.getDefine("CC_SUPPORT_standard_derivatives") && cc.sys.glExtension("OES_standard_derivatives") && material.define("CC_SUPPORT_standard_derivatives", true); layout.setEffect(material.effect._nativeObj); }; _proto.fillBuffers = function fillBuffers(comp, renderer) { this._layout.render(); }; _proto.getVfmt = function getVfmt() {}; return NativeTTF; })(); exports["default"] = NativeTTF; module.exports = exports["default"]; }), { "../../../../../assets/material/CCMaterial": 76, "../../../../../assets/material/material-variant": 83, "../../../../../components/CCLabel": 94, "../../../../../components/CCLabelOutline": 95, "../../../../../components/CCLabelShadow": 96 } ], 178: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _ttf = _interopRequireDefault(require("../../../../utils/label/ttf")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var LabelShadow = require("../../../../../components/CCLabelShadow"); var WHITE = cc.color(255, 255, 255, 255); var WebglTTFAssembler = (function(_TTFAssembler) { _inheritsLoose(WebglTTFAssembler, _TTFAssembler); function WebglTTFAssembler() { return _TTFAssembler.apply(this, arguments) || this; } var _proto = WebglTTFAssembler.prototype; _proto.updateUVs = function updateUVs(comp) { var verts = this._renderData.vDatas[0]; var uv = comp._frame.uv; var uvOffset = this.uvOffset; var floatsPerVert = this.floatsPerVert; for (var i = 0; i < 4; i++) { var srcOffset = 2 * i; var dstOffset = floatsPerVert * i + uvOffset; verts[dstOffset] = uv[srcOffset]; verts[dstOffset + 1] = uv[srcOffset + 1]; } }; _proto.updateColor = function updateColor(comp) { WHITE._fastSetA(comp.node._color.a); var color = WHITE._val; _TTFAssembler.prototype.updateColor.call(this, comp, color); }; _proto.updateVerts = function updateVerts(comp) { var scale = this.getTTFTextureSizeScale(); var node = comp.node, canvasWidth = comp._ttfTexture.width / scale, canvasHeight = comp._ttfTexture.height / scale, appx = node.anchorX * node.width, appy = node.anchorY * node.height; var shadow = LabelShadow && comp.getComponent(LabelShadow); if (shadow && shadow._enabled) { var offsetX = (canvasWidth - node.width) / 2; var offsetY = (canvasHeight - node.height) / 2; var shadowOffset = shadow.offset; -shadowOffset.x > offsetX ? appx += canvasWidth - node.width : offsetX > shadowOffset.x && (appx += offsetX - shadowOffset.x); -shadowOffset.y > offsetY ? appy += canvasHeight - node.height : offsetY > shadowOffset.y && (appy += offsetY - shadowOffset.y); } var local = this._local; local[0] = -appx; local[1] = -appy; local[2] = canvasWidth - appx; local[3] = canvasHeight - appy; this.updateUVs(comp); this.updateWorldVerts(comp); }; return WebglTTFAssembler; })(_ttf["default"]); exports["default"] = WebglTTFAssembler; module.exports = exports["default"]; }), { "../../../../../components/CCLabelShadow": 96, "../../../../utils/label/ttf": 167 } ], 179: [ (function(require, module, exports) { "use strict"; var _assembler = _interopRequireDefault(require("../../../assembler")); var _CCLabel = _interopRequireDefault(require("../../../../components/CCLabel")); var _ttf = _interopRequireDefault(require("./2d/ttf")); var _bmfont = _interopRequireDefault(require("./2d/bmfont")); var _letter = _interopRequireDefault(require("./2d/letter")); var _ttf2 = _interopRequireDefault(require("./3d/ttf")); var _bmfont2 = _interopRequireDefault(require("./3d/bmfont")); var _letter2 = _interopRequireDefault(require("./3d/letter")); var _ttf3 = _interopRequireDefault(require("./2d-multi/ttf")); var _bmfont3 = _interopRequireDefault(require("./2d-multi/bmfont")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var NativeTTF = void 0; false; _CCLabel["default"]._canvasPool = { pool: [], get: function get() { var data = this.pool.pop(); if (!data) { var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); data = { canvas: canvas, context: context }; context.textBaseline = "alphabetic"; } return data; }, put: function put(canvas) { if (this.pool.length >= 32) return; this.pool.push(canvas); } }; _assembler["default"].register(cc.Label, { getConstructor: function getConstructor(label) { var is3DNode = label.node.is3DNode; var material = label.getMaterials()[0]; var isMultiMaterial = material && material.material.isMultiSupport(); var ctor = is3DNode ? _ttf2["default"] : isMultiMaterial ? _ttf3["default"] : _ttf["default"]; if (label.font instanceof cc.BitmapFont) ctor = is3DNode ? _bmfont2["default"] : isMultiMaterial ? _bmfont3["default"] : _bmfont["default"]; else if (label.cacheMode === _CCLabel["default"].CacheMode.CHAR) { false; cc.sys.platform === cc.sys.WECHAT_GAME_SUB ? cc.warn("sorry, subdomain does not support CHAR mode currently!") : ctor = is3DNode ? _letter2["default"] : _letter["default"]; } return ctor; }, TTF: _ttf["default"], Bmfont: _bmfont["default"], Letter: _letter["default"], TTF3D: _ttf2["default"], Bmfont3D: _bmfont2["default"], Letter3D: _letter2["default"], NativeTTF: NativeTTF, TTFMulti: _ttf3["default"], BmfontMulti: _bmfont3["default"] }); }), { "../../../../components/CCLabel": 94, "../../../assembler": 157, "./2d-multi/bmfont": 173, "./2d-multi/ttf": 174, "./2d/bmfont": 175, "./2d/letter": 176, "./2d/nativeTTF": 177, "./2d/ttf": 178, "./3d/bmfont": void 0, "./3d/letter": void 0, "./3d/ttf": void 0 } ], 180: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.MaskAssembler = void 0; var _assembler = _interopRequireDefault(require("../../assembler")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Mask = require("../../../components/CCMask"); var RenderFlow = require("../../render-flow"); var SimpleSpriteAssembler = require("./sprite/2d/simple"); var GraphicsAssembler = require("./graphics"); var gfx = require("../../../../renderer/gfx"); var vfmtPos = require("../vertex-format").vfmtPos; var _maxLevel = 8; var _maskStack = []; function getWriteMask() { return 1 << _maskStack.length - 1; } function getStencilRef() { var result = 0; for (var i = 0; i < _maskStack.length; ++i) result += 1 << i; return result; } function applyStencil(material, func, failOp, ref, stencilMask, writeMask) { var effect = material.effect; var zFailOp = gfx.STENCIL_OP_KEEP, zPassOp = gfx.STENCIL_OP_KEEP; effect.setStencil(gfx.STENCIL_ENABLE, func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask); } function pushMask(mask) { _maskStack.length + 1 > _maxLevel && cc.errorID(9e3, _maxLevel); _maskStack.push(mask); } function exitMask(mask, renderer) { 0 === _maskStack.length && cc.errorID(9001); _maskStack.pop(); 0 === _maskStack.length ? renderer._flushMaterial(mask._exitMaterial) : enableMask(renderer); } function applyClearMask(mask, renderer) { var func = gfx.DS_FUNC_NEVER; var ref = getWriteMask(); var stencilMask = ref; var writeMask = ref; var failOp = mask.inverted ? gfx.STENCIL_OP_REPLACE : gfx.STENCIL_OP_ZERO; applyStencil(mask._clearMaterial, func, failOp, ref, stencilMask, writeMask); var buffer = renderer.getBuffer("mesh", vfmtPos); var offsetInfo = buffer.request(4, 6); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, ibuf = buffer._iData; vbuf[vertexOffset++] = -1; vbuf[vertexOffset++] = -1; vbuf[vertexOffset++] = -1; vbuf[vertexOffset++] = 1; vbuf[vertexOffset++] = 1; vbuf[vertexOffset++] = 1; vbuf[vertexOffset++] = 1; vbuf[vertexOffset++] = -1; ibuf[indiceOffset++] = vertexId; ibuf[indiceOffset++] = vertexId + 3; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 3; ibuf[indiceOffset++] = vertexId + 2; renderer.node = renderer._dummyNode; renderer.material = mask._clearMaterial; renderer._flush(); } function applyAreaMask(mask, renderer) { var func = gfx.DS_FUNC_NEVER; var ref = getWriteMask(); var stencilMask = ref; var writeMask = ref; var failOp = mask.inverted ? gfx.STENCIL_OP_ZERO : gfx.STENCIL_OP_REPLACE; applyStencil(mask._materials[0], func, failOp, ref, stencilMask, writeMask); renderer.material = mask._materials[0]; if (mask._type === Mask.Type.IMAGE_STENCIL) { renderer.node = renderer._dummyNode; SimpleSpriteAssembler.prototype.fillBuffers.call(mask._assembler, mask, renderer); renderer._flush(); } else { renderer.node = mask.node; GraphicsAssembler.prototype.fillBuffers.call(mask._graphics._assembler, mask._graphics, renderer); } } function enableMask(renderer) { var func = gfx.DS_FUNC_EQUAL; var failOp = gfx.STENCIL_OP_KEEP; var ref = getStencilRef(); var stencilMask = ref; var writeMask = getWriteMask(); var mask = _maskStack[_maskStack.length - 1]; applyStencil(mask._enableMaterial, func, failOp, ref, stencilMask, writeMask); renderer._flushMaterial(mask._enableMaterial); } var MaskAssembler = (function(_SimpleSpriteAssemble) { _inheritsLoose(MaskAssembler, _SimpleSpriteAssemble); function MaskAssembler() { return _SimpleSpriteAssemble.apply(this, arguments) || this; } var _proto = MaskAssembler.prototype; _proto.updateRenderData = function updateRenderData(mask) { if (mask._type === Mask.Type.IMAGE_STENCIL) mask.spriteFrame ? SimpleSpriteAssembler.prototype.updateRenderData.call(this, mask) : mask.setMaterial(0, null); else { mask._graphics.setMaterial(0, mask._materials[0]); GraphicsAssembler.prototype.updateRenderData.call(mask._graphics._assembler, mask._graphics, mask._graphics); } }; _proto.fillBuffers = function fillBuffers(mask, renderer) { if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) { pushMask(mask); applyClearMask(mask, renderer); applyAreaMask(mask, renderer); enableMask(renderer); } mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; }; _proto.postFillBuffers = function postFillBuffers(mask, renderer) { (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) && exitMask(mask, renderer); mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; }; return MaskAssembler; })(SimpleSpriteAssembler); exports.MaskAssembler = MaskAssembler; _assembler["default"].register(Mask, MaskAssembler); }), { "../../../../renderer/gfx": 259, "../../../components/CCMask": 98, "../../assembler": 157, "../../render-flow": 161, "../vertex-format": 202, "./graphics": 171, "./sprite/2d/simple": 192 } ], 181: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _motionStreak = _interopRequireDefault(require("./motion-streak")); var _vertexFormat = require("../../webgl/vertex-format"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MotionStreak = require("../../../components/CCMotionStreak"); var RenderFlow = require("../../render-flow"); function Point(point, dir) { this.point = point || cc.v2(); this.dir = dir || cc.v2(); this.distance = 0; this.time = 0; } Point.prototype.setPoint = function(x, y) { this.point.x = x; this.point.y = y; }; Point.prototype.setDir = function(x, y) { this.dir.x = x; this.dir.y = y; }; var _normal = cc.v2(); var _vec2 = cc.v2(); function normal(out, dir) { out.x = -dir.y; out.y = dir.x; return out; } var MultiMotionStreakAssembler = (function(_MotionStreakAssemble) { _inheritsLoose(MultiMotionStreakAssembler, _MotionStreakAssemble); function MultiMotionStreakAssembler() { return _MotionStreakAssemble.apply(this, arguments) || this; } var _proto = MultiMotionStreakAssembler.prototype; _proto.initData = function initData() { this._renderData.createFlexData(0, 16, 42, this.getVfmt()); }; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.update = function update(comp, dt) { false; var stroke = comp._stroke / 2; var node = comp.node; var matrix = node._worldMatrix.m; var tx = matrix[12], ty = matrix[13]; var points = comp._points; var lastPos = comp._lastWPos; var fadeTime = comp._fadeTime; var moved = lastPos.x !== tx || lastPos.y !== ty; if (moved) { var cur; var newHead = false; if (0 === points.length) { var _prev = new Point(); _prev.setPoint(lastPos.x, lastPos.y); this._tailShortenTime = _prev.time = fadeTime; points.push(_prev); cur = new Point(); points.unshift(cur); } else { cur = points[0]; var _prev2 = points[1]; var difx = _prev2.point.x - tx; var dify = _prev2.point.y - ty; newHead = difx * difx + dify * dify >= comp.minSeg * comp.minSeg; } cur.setPoint(tx, ty); cur.time = fadeTime + dt; var prev = points[1]; cur.distance = cur.point.sub(prev.point, _vec2).mag(); _vec2.normalizeSelf(); cur.setDir(_vec2.x, _vec2.y); var prevIsTail = 2 === points.length; prevIsTail && prev.setDir(_vec2.x, _vec2.y); if (newHead) { var point = new Point(cur.point.clone(), cur.dir.clone()); point.distance = cur.distance; point.time = cur.time; points.unshift(point); } } lastPos.x = tx; lastPos.y = ty; if (points.length < 2) return; var color = comp._color, ca = color.a; var crgb = color.b << 16 | color.g << 8 | color.r; var verticesCount = 0; var indicesCount = 0; var flexBuffer = this._renderData._flexBuffer; flexBuffer.reserve(2 * points.length, 6 * (points.length - 1)); var vData = flexBuffer.vData; var uintVData = flexBuffer.uintVData; var vertsOffset = 6; for (var i = points.length - 1; i >= 0; i--) { var p = points[i]; var _point = p.point; var dir = p.dir; p.time -= dt; var isLast = i === points.length - 1; if (p.time <= 0) { isLast && i - 1 >= 0 && (this._tailShortenTime = points[i - 1].time - dt); points.splice(i, 1); continue; } var progress = p.time / fadeTime; if (isLast) { var next = points[i - 1]; if (!next) { points.splice(i, 1); continue; } var nextIsStatic = points.length >= 3; if (nextIsStatic) { var segmentProgress = p.time / this._tailShortenTime; if (segmentProgress <= 1) { _point.x = next.point.x - next.distance * next.dir.x * segmentProgress; _point.y = next.point.y - next.distance * next.dir.y * segmentProgress; } } else this._tailShortenTime = p.time; } normal(_normal, dir); var da = progress * ca; var c = da << 24 >>> 0 | crgb; var offset = verticesCount * vertsOffset; vData[offset] = _point.x + _normal.x * stroke; vData[offset + 1] = _point.y + _normal.y * stroke; vData[offset + 2] = 1; vData[offset + 3] = progress; uintVData[offset + 4] = c; vData[offset + 5] = comp._texId; offset += vertsOffset; vData[offset] = _point.x - _normal.x * stroke; vData[offset + 1] = _point.y - _normal.y * stroke; vData[offset + 2] = 0; vData[offset + 3] = progress; uintVData[offset + 4] = c; vData[offset + 5] = comp._texId; verticesCount += 2; } indicesCount = verticesCount <= 2 ? 0 : 3 * (verticesCount - 2); flexBuffer.used(verticesCount, indicesCount); }; _proto.fillBuffers = function fillBuffers(comp, renderer) { var _this$_renderData$_fl = this._renderData._flexBuffer, vData = _this$_renderData$_fl.vData, usedVertices = _this$_renderData$_fl.usedVertices, usedIndices = _this$_renderData$_fl.usedIndices, usedVerticesFloats = _this$_renderData$_fl.usedVerticesFloats; var buffer = this.getBuffer(renderer); var offsetInfo = buffer.request(usedVertices, usedIndices); var vertexOffset = offsetInfo.byteOffset >> 2, vbuf = buffer._vData; vData.length + vertexOffset > vbuf.length ? vbuf.set(vData.subarray(0, usedVerticesFloats), vertexOffset) : vbuf.set(vData, vertexOffset); var ibuf = buffer._iData, indiceOffset = offsetInfo.indiceOffset, vertexId = offsetInfo.vertexOffset; for (var i = 0, l = usedVertices; i < l; i += 2) { var start = vertexId + i; ibuf[indiceOffset++] = start; ibuf[indiceOffset++] = start + 2; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 2; ibuf[indiceOffset++] = start + 3; } comp.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; }; return MultiMotionStreakAssembler; })(_motionStreak["default"]); exports["default"] = MultiMotionStreakAssembler; _motionStreak["default"].register(MotionStreak, { getConstructor: function getConstructor(comp) { var material = comp.getMaterials()[0]; var isMultiMaterial = material && material.material.isMultiSupport(); return isMultiMaterial ? MultiMotionStreakAssembler : _motionStreak["default"]; }, MotionStreakAssembler: _motionStreak["default"], MultiMotionStreakAssembler: MultiMotionStreakAssembler }); MultiMotionStreakAssembler.prototype.floatsPerVert = 6; MultiMotionStreakAssembler.prototype.texIdOffset = 5; MultiMotionStreakAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../components/CCMotionStreak": 99, "../../render-flow": 161, "../../webgl/vertex-format": 202, "./motion-streak": 182 } ], 182: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var RenderFlow = require("../../render-flow"); function Point(point, dir) { this.point = point || cc.v2(); this.dir = dir || cc.v2(); this.distance = 0; this.time = 0; } Point.prototype.setPoint = function(x, y) { this.point.x = x; this.point.y = y; }; Point.prototype.setDir = function(x, y) { this.dir.x = x; this.dir.y = y; }; var _tangent = cc.v2(); var _miter = cc.v2(); var _normal = cc.v2(); var _vec2 = cc.v2(); function normal(out, dir) { out.x = -dir.y; out.y = dir.x; return out; } function computeMiter(miter, lineA, lineB, halfThick, maxMultiple) { lineA.add(lineB, _tangent); _tangent.normalizeSelf(); miter.x = -_tangent.y; miter.y = _tangent.x; _vec2.x = -lineA.y; _vec2.y = lineA.x; var multiple = 1 / miter.dot(_vec2); maxMultiple && (multiple = Math.min(multiple, maxMultiple)); return halfThick * multiple; } var MotionStreakAssembler = (function(_Assembler2D) { _inheritsLoose(MotionStreakAssembler, _Assembler2D); function MotionStreakAssembler() { var _this; _this = _Assembler2D.call(this) || this; _this._tailShortenTime = 0; return _this; } var _proto = MotionStreakAssembler.prototype; _proto.initData = function initData() { this._renderData.createFlexData(0, 16, 42); }; _proto.update = function update(comp, dt) { false; var stroke = comp._stroke / 2; var node = comp.node; var matrix = node._worldMatrix.m; var tx = matrix[12], ty = matrix[13]; var points = comp._points; var lastPos = comp._lastWPos; var fadeTime = comp._fadeTime; var moved = lastPos.x !== tx || lastPos.y !== ty; if (moved) { var cur; var newHead = false; if (0 === points.length) { var _prev = new Point(); _prev.setPoint(lastPos.x, lastPos.y); this._tailShortenTime = _prev.time = fadeTime; points.push(_prev); cur = new Point(); points.unshift(cur); } else { cur = points[0]; var _prev2 = points[1]; var difx = _prev2.point.x - tx; var dify = _prev2.point.y - ty; newHead = difx * difx + dify * dify >= comp.minSeg * comp.minSeg; } cur.setPoint(tx, ty); cur.time = fadeTime + dt; var prev = points[1]; cur.distance = cur.point.sub(prev.point, _vec2).mag(); _vec2.normalizeSelf(); cur.setDir(_vec2.x, _vec2.y); var prevIsTail = 2 === points.length; prevIsTail && prev.setDir(_vec2.x, _vec2.y); if (newHead) { var point = new Point(cur.point.clone(), cur.dir.clone()); point.distance = cur.distance; point.time = cur.time; points.unshift(point); } } lastPos.x = tx; lastPos.y = ty; if (points.length < 2) return; var color = comp._color, ca = color.a; var crgb = color.b << 16 | color.g << 8 | color.r; var verticesCount = 0; var indicesCount = 0; var flexBuffer = this._renderData._flexBuffer; flexBuffer.reserve(2 * points.length, 6 * (points.length - 1)); var vData = flexBuffer.vData; var uintVData = flexBuffer.uintVData; var vertsOffset = 5; for (var i = points.length - 1; i >= 0; i--) { var p = points[i]; var _point = p.point; var dir = p.dir; p.time -= dt; var isLast = i === points.length - 1; if (p.time <= 0) { isLast && i - 1 >= 0 && (this._tailShortenTime = points[i - 1].time - dt); points.splice(i, 1); continue; } var progress = p.time / fadeTime; if (isLast) { var next = points[i - 1]; if (!next) { points.splice(i, 1); continue; } var nextIsStatic = points.length >= 3; if (nextIsStatic) { var segmentProgress = p.time / this._tailShortenTime; if (segmentProgress <= 1) { _point.x = next.point.x - next.distance * next.dir.x * segmentProgress; _point.y = next.point.y - next.distance * next.dir.y * segmentProgress; } } else this._tailShortenTime = p.time; } normal(_normal, dir); var da = progress * ca; var c = da << 24 >>> 0 | crgb; var offset = verticesCount * vertsOffset; vData[offset] = _point.x + _normal.x * stroke; vData[offset + 1] = _point.y + _normal.y * stroke; vData[offset + 2] = 1; vData[offset + 3] = progress; uintVData[offset + 4] = c; offset += vertsOffset; vData[offset] = _point.x - _normal.x * stroke; vData[offset + 1] = _point.y - _normal.y * stroke; vData[offset + 2] = 0; vData[offset + 3] = progress; uintVData[offset + 4] = c; verticesCount += 2; } indicesCount = verticesCount <= 2 ? 0 : 3 * (verticesCount - 2); flexBuffer.used(verticesCount, indicesCount); }; _proto.fillBuffers = function fillBuffers(comp, renderer) { var _this$_renderData$_fl = this._renderData._flexBuffer, vData = _this$_renderData$_fl.vData, usedVertices = _this$_renderData$_fl.usedVertices, usedIndices = _this$_renderData$_fl.usedIndices, usedVerticesFloats = _this$_renderData$_fl.usedVerticesFloats; var buffer = renderer._meshBuffer; var offsetInfo = buffer.request(usedVertices, usedIndices); var vertexOffset = offsetInfo.byteOffset >> 2, vbuf = buffer._vData; vData.length + vertexOffset > vbuf.length ? vbuf.set(vData.subarray(0, usedVerticesFloats), vertexOffset) : vbuf.set(vData, vertexOffset); var ibuf = buffer._iData, indiceOffset = offsetInfo.indiceOffset, vertexId = offsetInfo.vertexOffset; for (var i = 0, l = usedVertices; i < l; i += 2) { var start = vertexId + i; ibuf[indiceOffset++] = start; ibuf[indiceOffset++] = start + 2; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 2; ibuf[indiceOffset++] = start + 3; } comp.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; }; return MotionStreakAssembler; })(_assembler2d["default"]); exports["default"] = MotionStreakAssembler; module.exports = exports["default"]; }), { "../../assembler-2d": 155, "../../render-flow": 161 } ], 183: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _vertexFormat = require("../../../../webgl/vertex-format"); var _barFilled = _interopRequireDefault(require("../2d/bar-filled")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var BarFilledAssemblerMulti = (function(_BarFilledAssembler) { _inheritsLoose(BarFilledAssemblerMulti, _BarFilledAssembler); function BarFilledAssemblerMulti() { return _BarFilledAssembler.apply(this, arguments) || this; } var _proto = BarFilledAssemblerMulti.prototype; _proto.initData = function initData() { var data = this._renderData; data.createFlexData(0, this.verticesCount, this.indicesCount, this.getVfmt()); var indices = data.iDatas[0]; data.initQuadIndices(indices); }; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(sprite) { _BarFilledAssembler.prototype.updateRenderData.call(this, sprite); if (sprite._texIdDirty) { sprite._updateMultiTexId(sprite.getMaterial(0), sprite._spriteFrame._texture); if (sprite._texIdDirty) { this.updateTexId(sprite); sprite._texIdDirty = false; } } }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(sprite) { if (sprite._vertsDirty) { var fillStart = sprite._fillStart; var fillRange = sprite._fillRange; if (fillRange < 0) { fillStart += fillRange; fillRange = -fillRange; } fillRange = fillStart + fillRange; fillStart = fillStart > 1 ? 1 : fillStart; fillStart = fillStart < 0 ? 0 : fillStart; fillRange = fillRange > 1 ? 1 : fillRange; fillRange = fillRange < 0 ? 0 : fillRange; fillRange -= fillStart; fillRange = fillRange < 0 ? 0 : fillRange; var fillEnd = fillStart + fillRange; fillEnd = fillEnd > 1 ? 1 : fillEnd; this.updateUVs(sprite, fillStart, fillEnd); this.updateVerts(sprite, fillStart, fillEnd); sprite._vertsDirty = false; } if (sprite._texIdDirty) { sprite._updateMultiTexId(sprite.getMaterial(0), sprite._spriteFrame._texture); if (sprite._texIdDirty) { this.updateTexId(sprite); sprite._texIdDirty = false; } } false; }; return BarFilledAssemblerMulti; })(_barFilled["default"]); exports["default"] = BarFilledAssemblerMulti; BarFilledAssemblerMulti.prototype.floatsPerVert = 6; BarFilledAssemblerMulti.prototype.texIdOffset = 5; BarFilledAssemblerMulti.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/bar-filled": 189 } ], 184: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _vertexFormat = require("../../../../webgl/vertex-format"); var _mesh = _interopRequireDefault(require("../2d/mesh")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MultiMeshSpriteAssembler = (function(_MeshSpriteAssembler) { _inheritsLoose(MultiMeshSpriteAssembler, _MeshSpriteAssembler); function MultiMeshSpriteAssembler() { return _MeshSpriteAssembler.apply(this, arguments) || this; } var _proto = MultiMeshSpriteAssembler.prototype; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(sprite) { var frame = sprite.spriteFrame; _MeshSpriteAssembler.prototype.updateRenderData.call(this, sprite); if (frame) { sprite._texIdDirty && sprite._updateMultiTexId(sprite.getMaterial(0), frame._texture); this.updateTexId(sprite); sprite._texIdDirty = false; } }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(sprite) { var frame = sprite.spriteFrame; if (frame) { var vertices = frame.vertices; if (vertices) { this.verticesCount = vertices.x.length; this.indicesCount = vertices.triangles.length; var renderData = this._renderData; var flexBuffer = renderData._flexBuffer; if (flexBuffer.reserve(this.verticesCount, this.indicesCount)) { this.updateColor(sprite); sprite._vertsDirty = true; } flexBuffer.used(this.verticesCount, this.indicesCount); this.updateIndices(vertices.triangles); if (sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); this.updateWorldVerts(sprite); sprite._vertsDirty = false; } } } sprite._texIdDirty && sprite._updateMultiTexId(sprite.getMaterial(0), frame._texture); this.updateTexId(sprite); sprite._texIdDirty = false; false; }; return MultiMeshSpriteAssembler; })(_mesh["default"]); exports["default"] = MultiMeshSpriteAssembler; MultiMeshSpriteAssembler.prototype.floatsPerVert = 6; MultiMeshSpriteAssembler.prototype.texIdOffset = 5; MultiMeshSpriteAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/mesh": 190 } ], 185: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _vertexFormat = require("../../../../webgl/vertex-format"); var _radialFilled = _interopRequireDefault(require("../2d/radial-filled")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MultiRadialFilledAssembler = (function(_RadialFilledAssemble) { _inheritsLoose(MultiRadialFilledAssembler, _RadialFilledAssemble); function MultiRadialFilledAssembler() { return _RadialFilledAssemble.apply(this, arguments) || this; } var _proto = MultiRadialFilledAssembler.prototype; _proto.initData = function initData(sprite) { this._renderData.createFlexData(0, 4, 6, this.getVfmt()); this.updateIndices(); }; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(sprite) { _RadialFilledAssemble.prototype.updateRenderData.call(this, sprite); sprite._texIdDirty && sprite._updateMultiTexId(sprite.getMaterial(0), sprite.spriteFrame._texture); this.updateTexId(sprite); sprite._texIdDirty = false; }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(sprite) { this._aftUpdateRenderData(sprite); sprite._texIdDirty && sprite._updateMultiTexId(sprite.getMaterial(0), sprite.spriteFrame._texture); this.updateTexId(sprite); sprite._texIdDirty = false; false; }; return MultiRadialFilledAssembler; })(_radialFilled["default"]); exports["default"] = MultiRadialFilledAssembler; MultiRadialFilledAssembler.prototype.floatsPerVert = 6; MultiRadialFilledAssembler.prototype.texIdOffset = 5; MultiRadialFilledAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/radial-filled": 191 } ], 186: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _vertexFormat = require("../../../../webgl/vertex-format"); var _simple = _interopRequireDefault(require("../2d/simple")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MultiSimpleSpriteAssembler = (function(_SimpleSpriteAssemble) { _inheritsLoose(MultiSimpleSpriteAssembler, _SimpleSpriteAssemble); function MultiSimpleSpriteAssembler() { return _SimpleSpriteAssemble.apply(this, arguments) || this; } var _proto = MultiSimpleSpriteAssembler.prototype; _proto.initData = function initData() { var data = this._renderData; data.createFlexData(0, this.verticesCount, this.indicesCount, this.getVfmt()); var indices = data.iDatas[0]; data.initQuadIndices(indices); }; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(sprite) { _SimpleSpriteAssemble.prototype.updateRenderData.call(this, sprite); if (sprite._texIdDirty) { sprite._updateMultiTexId(sprite.getMaterial(0), sprite._spriteFrame._texture); if (sprite._texIdDirty) { this.updateTexId(sprite); sprite._texIdDirty = false; } } }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(sprite) { if (sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); sprite._vertsDirty = false; } if (sprite._texIdDirty) { sprite._updateMultiTexId(sprite.getMaterial(0), sprite._spriteFrame._texture); if (sprite._texIdDirty) { this.updateTexId(sprite); sprite._texIdDirty = false; } } false; }; return MultiSimpleSpriteAssembler; })(_simple["default"]); exports["default"] = MultiSimpleSpriteAssembler; MultiSimpleSpriteAssembler.prototype.floatsPerVert = 6; MultiSimpleSpriteAssembler.prototype.texIdOffset = 5; MultiSimpleSpriteAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/simple": 192 } ], 187: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _vertexFormat = require("../../../../webgl/vertex-format"); var _sliced = _interopRequireDefault(require("../2d/sliced")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MultiSlicedAssembler = (function(_SlicedAssembler) { _inheritsLoose(MultiSlicedAssembler, _SlicedAssembler); function MultiSlicedAssembler() { return _SlicedAssembler.apply(this, arguments) || this; } var _proto = MultiSlicedAssembler.prototype; _proto.initData = function initData(sprite) { if (this._renderData.meshCount > 0) return; this._renderData.createFlexData(0, this.verticesCount, this.indicesCount, this.getVfmt()); var indices = this._renderData.iDatas[0]; var indexOffset = 0; for (var r = 0; r < 3; ++r) for (var c = 0; c < 3; ++c) { var start = 4 * r + c; indices[indexOffset++] = start; indices[indexOffset++] = start + 1; indices[indexOffset++] = start + 4; indices[indexOffset++] = start + 1; indices[indexOffset++] = start + 5; indices[indexOffset++] = start + 4; } }; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(sprite) { _SlicedAssembler.prototype.updateRenderData.call(this, sprite); if (sprite._texIdDirty) { sprite._updateMultiTexId(sprite.getMaterial(0), sprite._spriteFrame._texture); if (sprite._texIdDirty) { this.updateTexId(sprite); sprite._texIdDirty = false; } } }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(sprite) { if (sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); sprite._vertsDirty = false; } if (sprite._texIdDirty) { sprite._updateMultiTexId(sprite.getMaterial(0), sprite._spriteFrame._texture); if (sprite._texIdDirty) { this.updateTexId(sprite); sprite._texIdDirty = false; } } false; }; return MultiSlicedAssembler; })(_sliced["default"]); exports["default"] = MultiSlicedAssembler; MultiSlicedAssembler.prototype.floatsPerVert = 6; MultiSlicedAssembler.prototype.texIdOffset = 5; MultiSlicedAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/sliced": 193 } ], 188: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _vertexFormat = require("../../../../webgl/vertex-format"); var _tiled = _interopRequireDefault(require("../2d/tiled")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MultiTiledAssembler = (function(_TiledAssembler) { _inheritsLoose(MultiTiledAssembler, _TiledAssembler); function MultiTiledAssembler() { return _TiledAssembler.apply(this, arguments) || this; } var _proto = MultiTiledAssembler.prototype; _proto.getVfmt = function getVfmt() { return _vertexFormat.vfmtPosUvColorTexId; }; _proto.getBuffer = function getBuffer() { return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(sprite) { _TiledAssembler.prototype.updateRenderData.call(this, sprite); sprite._texIdDirty && sprite._updateMultiTexId(sprite.getMaterial(0), sprite.spriteFrame._texture); this.updateTexId(sprite); sprite._texIdDirty = false; }; _proto.updateRenderDataForSwitchMaterial = function updateRenderDataForSwitchMaterial(sprite) { var frame = sprite._spriteFrame; var node = sprite.node; var contentWidth = this.contentWidth = Math.abs(node.width); var contentHeight = this.contentHeight = Math.abs(node.height); var rect = frame._rect; var leftWidth = frame.insetLeft, rightWidth = frame.insetRight, centerWidth = rect.width - leftWidth - rightWidth, topHeight = frame.insetTop, bottomHeight = frame.insetBottom, centerHeight = rect.height - topHeight - bottomHeight; this.sizableWidth = contentWidth - leftWidth - rightWidth; this.sizableHeight = contentHeight - topHeight - bottomHeight; this.sizableWidth = this.sizableWidth > 0 ? this.sizableWidth : 0; this.sizableHeight = this.sizableHeight > 0 ? this.sizableHeight : 0; var hRepeat = this.hRepeat = 0 === centerWidth ? this.sizableWidth : this.sizableWidth / centerWidth; var vRepeat = this.vRepeat = 0 === centerHeight ? this.sizableHeight : this.sizableHeight / centerHeight; var row = this.row = Math.ceil(vRepeat + 2); var col = this.col = Math.ceil(hRepeat + 2); var count = row * col; this.verticesCount = 4 * count; this.indicesCount = 6 * count; var renderData = this._renderData; var flexBuffer = renderData._flexBuffer; if (flexBuffer.reserve(this.verticesCount, this.indicesCount)) { this._updateIndices(); this.updateColor(sprite); } flexBuffer.used(this.verticesCount, this.indicesCount); if (sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); sprite._vertsDirty = false; } sprite._texIdDirty && sprite._updateMultiTexId(sprite.getMaterial(0), sprite.spriteFrame._texture); this.updateTexId(sprite); sprite._texIdDirty = false; false; }; return MultiTiledAssembler; })(_tiled["default"]); exports["default"] = MultiTiledAssembler; MultiTiledAssembler.prototype.floatsPerVert = 6; MultiTiledAssembler.prototype.texIdOffset = 5; MultiTiledAssembler.prototype.isMulti = true; module.exports = exports["default"]; }), { "../../../../webgl/vertex-format": 202, "../2d/tiled": 194 } ], 189: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Sprite = require("../../../../../components/CCSprite"); var FillType = Sprite.FillType; var BarFilledAssembler = (function(_Assembler2D) { _inheritsLoose(BarFilledAssembler, _Assembler2D); function BarFilledAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = BarFilledAssembler.prototype; _proto.updateRenderData = function updateRenderData(sprite) { var frame = sprite._spriteFrame; var assemblerChanged = this.packDynamicAtlasAndCheckMaterial(sprite, frame); if (!assemblerChanged && sprite._vertsDirty) { var fillStart = sprite._fillStart; var fillRange = sprite._fillRange; if (fillRange < 0) { fillStart += fillRange; fillRange = -fillRange; } fillRange = fillStart + fillRange; fillStart = fillStart > 1 ? 1 : fillStart; fillStart = fillStart < 0 ? 0 : fillStart; fillRange = fillRange > 1 ? 1 : fillRange; fillRange = fillRange < 0 ? 0 : fillRange; fillRange -= fillStart; fillRange = fillRange < 0 ? 0 : fillRange; var fillEnd = fillStart + fillRange; fillEnd = fillEnd > 1 ? 1 : fillEnd; this.updateUVs(sprite, fillStart, fillEnd); this.updateVerts(sprite, fillStart, fillEnd); sprite._vertsDirty = false; } return assemblerChanged; }; _proto.updateUVs = function updateUVs(sprite, fillStart, fillEnd) { var spriteFrame = sprite._spriteFrame; var atlasWidth = spriteFrame._texture.width; var atlasHeight = spriteFrame._texture.height; var textureRect = spriteFrame._rect; var ul, vb, ur, vt; var quadUV0, quadUV1, quadUV2, quadUV3, quadUV4, quadUV5, quadUV6, quadUV7; if (spriteFrame._rotated) { ul = textureRect.x / atlasWidth; vb = (textureRect.y + textureRect.width) / atlasHeight; ur = (textureRect.x + textureRect.height) / atlasWidth; vt = textureRect.y / atlasHeight; quadUV0 = quadUV2 = ul; quadUV4 = quadUV6 = ur; quadUV3 = quadUV7 = vb; quadUV1 = quadUV5 = vt; } else { ul = textureRect.x / atlasWidth; vb = (textureRect.y + textureRect.height) / atlasHeight; ur = (textureRect.x + textureRect.width) / atlasWidth; vt = textureRect.y / atlasHeight; quadUV0 = quadUV4 = ul; quadUV2 = quadUV6 = ur; quadUV1 = quadUV3 = vb; quadUV5 = quadUV7 = vt; } var verts = this._renderData.vDatas[0]; var uvOffset = this.uvOffset; var floatsPerVert = this.floatsPerVert; switch (sprite._fillType) { case FillType.HORIZONTAL: verts[uvOffset] = quadUV0 + (quadUV2 - quadUV0) * fillStart; verts[uvOffset + 1] = quadUV1 + (quadUV3 - quadUV1) * fillStart; verts[uvOffset + floatsPerVert] = quadUV0 + (quadUV2 - quadUV0) * fillEnd; verts[uvOffset + floatsPerVert + 1] = quadUV1 + (quadUV3 - quadUV1) * fillEnd; verts[uvOffset + 2 * floatsPerVert] = quadUV4 + (quadUV6 - quadUV4) * fillStart; verts[uvOffset + 2 * floatsPerVert + 1] = quadUV5 + (quadUV7 - quadUV5) * fillStart; verts[uvOffset + 3 * floatsPerVert] = quadUV4 + (quadUV6 - quadUV4) * fillEnd; verts[uvOffset + 3 * floatsPerVert + 1] = quadUV5 + (quadUV7 - quadUV5) * fillEnd; break; case FillType.VERTICAL: verts[uvOffset] = quadUV0 + (quadUV4 - quadUV0) * fillStart; verts[uvOffset + 1] = quadUV1 + (quadUV5 - quadUV1) * fillStart; verts[uvOffset + floatsPerVert] = quadUV2 + (quadUV6 - quadUV2) * fillStart; verts[uvOffset + floatsPerVert + 1] = quadUV3 + (quadUV7 - quadUV3) * fillStart; verts[uvOffset + 2 * floatsPerVert] = quadUV0 + (quadUV4 - quadUV0) * fillEnd; verts[uvOffset + 2 * floatsPerVert + 1] = quadUV1 + (quadUV5 - quadUV1) * fillEnd; verts[uvOffset + 3 * floatsPerVert] = quadUV2 + (quadUV6 - quadUV2) * fillEnd; verts[uvOffset + 3 * floatsPerVert + 1] = quadUV3 + (quadUV7 - quadUV3) * fillEnd; break; default: cc.errorID(2626); } }; _proto.updateVerts = function updateVerts(sprite, fillStart, fillEnd) { var node = sprite.node, width = node.width, height = node.height, appx = node.anchorX * width, appy = node.anchorY * height; var l = -appx, b = -appy, r = width - appx, t = height - appy; var progressStart, progressEnd; switch (sprite._fillType) { case FillType.HORIZONTAL: progressStart = l + (r - l) * fillStart; progressEnd = l + (r - l) * fillEnd; l = progressStart; r = progressEnd; break; case FillType.VERTICAL: progressStart = b + (t - b) * fillStart; progressEnd = b + (t - b) * fillEnd; b = progressStart; t = progressEnd; break; default: cc.errorID(2626); } var local = this._local; local[0] = l; local[1] = b; local[2] = r; local[3] = t; this.updateWorldVerts(sprite); }; return BarFilledAssembler; })(_assembler2d["default"]); exports["default"] = BarFilledAssembler; module.exports = exports["default"]; }), { "../../../../../components/CCSprite": 105, "../../../../assembler-2d": 155 } ], 190: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var MeshSpriteAssembler = (function(_Assembler2D) { _inheritsLoose(MeshSpriteAssembler, _Assembler2D); function MeshSpriteAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = MeshSpriteAssembler.prototype; _proto.initData = function initData(sprite) { this._renderData.createFlexData(0, 4, 6, this.getVfmt()); }; _proto.updateRenderData = function updateRenderData(sprite) { var frame = sprite.spriteFrame; var assemblerChanged = this.packDynamicAtlasAndCheckMaterial(sprite, frame); if (!assemblerChanged && frame) { var vertices = frame.vertices; if (vertices) { this.verticesCount = vertices.x.length; this.indicesCount = vertices.triangles.length; var renderData = this._renderData; var flexBuffer = renderData._flexBuffer; if (flexBuffer.reserve(this.verticesCount, this.indicesCount)) { this.updateColor(sprite); sprite._vertsDirty = true; } flexBuffer.used(this.verticesCount, this.indicesCount); this.updateIndices(vertices.triangles); if (sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); this.updateWorldVerts(sprite); sprite._vertsDirty = false; } } } return assemblerChanged; }; _proto.updateIndices = function updateIndices(triangles) { this._renderData.iDatas[0].set(triangles); }; _proto.updateUVs = function updateUVs(sprite) { var vertices = sprite.spriteFrame.vertices, u = vertices.nu, v = vertices.nv; var uvOffset = this.uvOffset; var floatsPerVert = this.floatsPerVert; var verts = this._renderData.vDatas[0]; for (var i = 0; i < u.length; i++) { var dstOffset = floatsPerVert * i + uvOffset; verts[dstOffset] = u[i]; verts[dstOffset + 1] = v[i]; } }; _proto.updateVerts = function updateVerts(sprite) { var node = sprite.node, contentWidth = Math.abs(node.width), contentHeight = Math.abs(node.height), appx = node.anchorX * contentWidth, appy = node.anchorY * contentHeight; var frame = sprite.spriteFrame, vertices = frame.vertices, x = vertices.x, y = vertices.y, originalWidth = frame._originalSize.width, originalHeight = frame._originalSize.height, rectWidth = frame._rect.width, rectHeight = frame._rect.height, offsetX = frame._offset.x, offsetY = frame._offset.y, trimX = offsetX + (originalWidth - rectWidth) / 2, trimY = offsetY + (originalHeight - rectHeight) / 2; var scaleX = contentWidth / (sprite.trim ? rectWidth : originalWidth), scaleY = contentHeight / (sprite.trim ? rectHeight : originalHeight); var local = this._local; if (sprite.trim) for (var _i = 0, _l = x.length; _i < _l; _i++) { var _offset = 2 * _i; local[_offset] = (x[_i] - trimX) * scaleX - appx; local[_offset + 1] = (originalHeight - y[_i] - trimY) * scaleY - appy; } else for (var i = 0, l = x.length; i < l; i++) { var offset = 2 * i; local[offset] = x[i] * scaleX - appx; local[offset + 1] = (originalHeight - y[i]) * scaleY - appy; } if (frame._flipX) for (var _i2 = 0, _l2 = this.verticesCount; _i2 < _l2; _i2++) local[2 * _i2] = contentWidth - local[2 * _i2] - 2 * appx; if (frame._flipY) for (var _i3 = 0, _l3 = this.verticesCount; _i3 < _l3; _i3++) local[2 * _i3 + 1] = contentHeight - local[2 * _i3 + 1] - 2 * appy; }; _proto.updateWorldVerts = function updateWorldVerts(sprite) { var node = sprite.node; var matrix = node._worldMatrix; var matrixm = matrix.m; var a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5], tx = matrixm[12], ty = matrixm[13]; var local = this._local; var world = this._renderData.vDatas[0]; var floatsPerVert = this.floatsPerVert; for (var i = 0, l = this.verticesCount; i < l; i++) { var lx = local[2 * i]; var ly = local[2 * i + 1]; world[floatsPerVert * i] = lx * a + ly * c + tx; world[floatsPerVert * i + 1] = lx * b + ly * d + ty; } }; return MeshSpriteAssembler; })(_assembler2d["default"]); exports["default"] = MeshSpriteAssembler; module.exports = exports["default"]; }), { "../../../../assembler-2d": 155 } ], 191: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var PI_2 = 2 * Math.PI; var _vertPos = [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ]; var _vertices = [ 0, 0, 0, 0 ]; var _uvs = [ 0, 0, 0, 0, 0, 0, 0, 0 ]; var _intersectPoint_1 = [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ]; var _intersectPoint_2 = [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ]; var _center = cc.v2(0, 0); var _triangles = []; function _calcInsectedPoints(left, right, bottom, top, center, angle, intersectPoints) { var sinAngle = Math.sin(angle); var cosAngle = Math.cos(angle); var tanAngle, cotAngle; if (0 !== Math.cos(angle)) { tanAngle = sinAngle / cosAngle; if ((left - center.x) * cosAngle > 0) { var yleft = center.y + tanAngle * (left - center.x); intersectPoints[0].x = left; intersectPoints[0].y = yleft; } if ((right - center.x) * cosAngle > 0) { var yright = center.y + tanAngle * (right - center.x); intersectPoints[2].x = right; intersectPoints[2].y = yright; } } if (0 !== Math.sin(angle)) { cotAngle = cosAngle / sinAngle; if ((top - center.y) * sinAngle > 0) { var xtop = center.x + cotAngle * (top - center.y); intersectPoints[3].x = xtop; intersectPoints[3].y = top; } if ((bottom - center.y) * sinAngle > 0) { var xbottom = center.x + cotAngle * (bottom - center.y); intersectPoints[1].x = xbottom; intersectPoints[1].y = bottom; } } } function _calculateVertices(sprite) { var node = sprite.node, width = node.width, height = node.height, appx = node.anchorX * width, appy = node.anchorY * height; var l = -appx, b = -appy, r = width - appx, t = height - appy; var vertices = _vertices; vertices[0] = l; vertices[1] = b; vertices[2] = r; vertices[3] = t; var fillCenter = sprite._fillCenter, cx = _center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l, cy = _center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t - b) + b; _vertPos[0].x = _vertPos[3].x = l; _vertPos[1].x = _vertPos[2].x = r; _vertPos[0].y = _vertPos[1].y = b; _vertPos[2].y = _vertPos[3].y = t; _triangles.length = 0; cx !== vertices[0] && (_triangles[0] = [ 3, 0 ]); cx !== vertices[2] && (_triangles[2] = [ 1, 2 ]); cy !== vertices[1] && (_triangles[1] = [ 0, 1 ]); cy !== vertices[3] && (_triangles[3] = [ 2, 3 ]); } function _calculateUVs(spriteFrame) { var atlasWidth = spriteFrame._texture.width; var atlasHeight = spriteFrame._texture.height; var textureRect = spriteFrame._rect; var u0, u1, v0, v1; var uvs = _uvs; if (spriteFrame._rotated) { u0 = textureRect.x / atlasWidth; u1 = (textureRect.x + textureRect.height) / atlasWidth; v0 = textureRect.y / atlasHeight; v1 = (textureRect.y + textureRect.width) / atlasHeight; uvs[0] = uvs[2] = u0; uvs[4] = uvs[6] = u1; uvs[3] = uvs[7] = v1; uvs[1] = uvs[5] = v0; } else { u0 = textureRect.x / atlasWidth; u1 = (textureRect.x + textureRect.width) / atlasWidth; v0 = textureRect.y / atlasHeight; v1 = (textureRect.y + textureRect.height) / atlasHeight; uvs[0] = uvs[4] = u0; uvs[2] = uvs[6] = u1; uvs[1] = uvs[3] = v1; uvs[5] = uvs[7] = v0; } } function _getVertAngle(start, end) { var placementX, placementY; placementX = end.x - start.x; placementY = end.y - start.y; if (0 === placementX && 0 === placementY) return; if (0 === placementX) return placementY > 0 ? .5 * Math.PI : 1.5 * Math.PI; var angle = Math.atan(placementY / placementX); placementX < 0 && (angle += Math.PI); return angle; } var RadialFilledAssembler = (function(_Assembler2D) { _inheritsLoose(RadialFilledAssembler, _Assembler2D); function RadialFilledAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = RadialFilledAssembler.prototype; _proto.initData = function initData(sprite) { this._renderData.createFlexData(0, 4, 6, this.getVfmt()); this.updateIndices(); }; _proto.updateRenderData = function updateRenderData(sprite) { _Assembler2D.prototype.updateRenderData.call(this, sprite); var frame = sprite.spriteFrame; var assemblerChanged = this.packDynamicAtlasAndCheckMaterial(sprite, frame); assemblerChanged || this._aftUpdateRenderData(sprite); return assemblerChanged; }; _proto._aftUpdateRenderData = function _aftUpdateRenderData(sprite) { var frame = sprite.spriteFrame; if (sprite._vertsDirty) { var fillStart = sprite._fillStart; var fillRange = sprite._fillRange; if (fillRange < 0) { fillStart += fillRange; fillRange = -fillRange; } while (fillStart >= 1) fillStart -= 1; while (fillStart < 0) fillStart += 1; fillStart *= PI_2; fillRange *= PI_2; _calculateVertices(sprite); _calculateUVs(frame); _calcInsectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart, _intersectPoint_1); _calcInsectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart + fillRange, _intersectPoint_2); this.updateVerts(sprite, fillStart, fillRange); sprite._vertsDirty = false; } }; _proto.updateVerts = function updateVerts(sprite, fillStart, fillRange) { var fillEnd = fillStart + fillRange; var local = this._local; local.length = 0; var offset = 0; var floatsPerTriangle = 3 * this.floatsPerVert; for (var triangleIndex = 0; triangleIndex < 4; ++triangleIndex) { var triangle = _triangles[triangleIndex]; if (!triangle) continue; if (fillRange >= PI_2) { local.length = offset + floatsPerTriangle; this._generateTriangle(local, offset, _center, _vertPos[triangle[0]], _vertPos[triangle[1]]); offset += floatsPerTriangle; continue; } var startAngle = _getVertAngle(_center, _vertPos[triangle[0]]); var endAngle = _getVertAngle(_center, _vertPos[triangle[1]]); endAngle < startAngle && (endAngle += PI_2); startAngle -= PI_2; endAngle -= PI_2; for (var testIndex = 0; testIndex < 3; ++testIndex) { if (startAngle >= fillEnd) ; else if (startAngle >= fillStart) { local.length = offset + floatsPerTriangle; endAngle >= fillEnd ? this._generateTriangle(local, offset, _center, _vertPos[triangle[0]], _intersectPoint_2[triangleIndex]) : this._generateTriangle(local, offset, _center, _vertPos[triangle[0]], _vertPos[triangle[1]]); offset += floatsPerTriangle; } else if (endAngle <= fillStart) ; else if (endAngle <= fillEnd) { local.length = offset + floatsPerTriangle; this._generateTriangle(local, offset, _center, _intersectPoint_1[triangleIndex], _vertPos[triangle[1]]); offset += floatsPerTriangle; } else { local.length = offset + floatsPerTriangle; this._generateTriangle(local, offset, _center, _intersectPoint_1[triangleIndex], _intersectPoint_2[triangleIndex]); offset += floatsPerTriangle; } startAngle += PI_2; endAngle += PI_2; } } this.allocWorldVerts(sprite); this.updateWorldVerts(sprite); }; _proto.allocWorldVerts = function allocWorldVerts(sprite) { var color = sprite.node._color._val; var renderData = this._renderData; var floatsPerVert = this.floatsPerVert; var local = this._local; var verticesCount = local.length / floatsPerVert; this.verticesCount = this.indicesCount = verticesCount; var flexBuffer = renderData._flexBuffer; flexBuffer.reserve(verticesCount, verticesCount) && this.updateIndices(); flexBuffer.used(this.verticesCount, this.indicesCount); var verts = renderData.vDatas[0], uintVerts = renderData.uintVDatas[0]; var uvOffset = this.uvOffset; for (var offset = 0; offset < local.length; offset += floatsPerVert) { var start = offset + uvOffset; verts[start] = local[start]; verts[start + 1] = local[start + 1]; uintVerts[start + 2] = color; } }; _proto.updateIndices = function updateIndices() { var iData = this._renderData.iDatas[0]; for (var i = 0; i < iData.length; i++) iData[i] = i; }; _proto.updateWorldVerts = function updateWorldVerts(sprite) { var node = sprite.node; var matrix = node._worldMatrix; var matrixm = matrix.m, a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5], tx = matrixm[12], ty = matrixm[13]; var local = this._local; var world = this._renderData.vDatas[0]; var floatsPerVert = this.floatsPerVert; for (var offset = 0; offset < local.length; offset += floatsPerVert) { var x = local[offset]; var y = local[offset + 1]; world[offset] = x * a + y * c + tx; world[offset + 1] = x * b + y * d + ty; } }; _proto._generateTriangle = function _generateTriangle(verts, offset, vert0, vert1, vert2) { var vertices = _vertices; var v0x = vertices[0]; var v0y = vertices[1]; var v1x = vertices[2]; var v1y = vertices[3]; var floatsPerVert = this.floatsPerVert; verts[offset] = vert0.x; verts[offset + 1] = vert0.y; verts[offset + floatsPerVert] = vert1.x; verts[offset + floatsPerVert + 1] = vert1.y; verts[offset + 2 * floatsPerVert] = vert2.x; verts[offset + 2 * floatsPerVert + 1] = vert2.y; var uvOffset = this.uvOffset; var progressX, progressY; progressX = (vert0.x - v0x) / (v1x - v0x); progressY = (vert0.y - v0y) / (v1y - v0y); this._generateUV(progressX, progressY, verts, offset + uvOffset); progressX = (vert1.x - v0x) / (v1x - v0x); progressY = (vert1.y - v0y) / (v1y - v0y); this._generateUV(progressX, progressY, verts, offset + floatsPerVert + uvOffset); progressX = (vert2.x - v0x) / (v1x - v0x); progressY = (vert2.y - v0y) / (v1y - v0y); this._generateUV(progressX, progressY, verts, offset + 2 * floatsPerVert + uvOffset); }; _proto._generateUV = function _generateUV(progressX, progressY, verts, offset) { var uvs = _uvs; var px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX; var px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX; var py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX; var py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX; verts[offset] = px1 + (px2 - px1) * progressY; verts[offset + 1] = py1 + (py2 - py1) * progressY; }; return RadialFilledAssembler; })(_assembler2d["default"]); exports["default"] = RadialFilledAssembler; module.exports = exports["default"]; }), { "../../../../assembler-2d": 155 } ], 192: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var SimpleSpriteAssembler = (function(_Assembler2D) { _inheritsLoose(SimpleSpriteAssembler, _Assembler2D); function SimpleSpriteAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = SimpleSpriteAssembler.prototype; _proto.updateRenderData = function updateRenderData(sprite) { var assemblerChanged = this.packDynamicAtlasAndCheckMaterial(sprite, sprite._spriteFrame); if (!assemblerChanged && sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); sprite._vertsDirty = false; } return assemblerChanged; }; _proto.updateUVs = function updateUVs(sprite) { var uv = sprite._spriteFrame.uv; var uvOffset = this.uvOffset; var floatsPerVert = this.floatsPerVert; var verts = this._renderData.vDatas[0]; for (var i = 0; i < 4; i++) { var srcOffset = 2 * i; var dstOffset = floatsPerVert * i + uvOffset; verts[dstOffset] = uv[srcOffset]; verts[dstOffset + 1] = uv[srcOffset + 1]; } }; _proto.updateVerts = function updateVerts(sprite) { var node = sprite.node, cw = node.width, ch = node.height, appx = node.anchorX * cw, appy = node.anchorY * ch, l, b, r, t; if (sprite.trim) { l = -appx; b = -appy; r = cw - appx; t = ch - appy; } else { var frame = sprite.spriteFrame, ow = frame._originalSize.width, oh = frame._originalSize.height, rw = frame._rect.width, rh = frame._rect.height, offset = frame._offset, scaleX = cw / ow, scaleY = ch / oh; var trimLeft = offset.x + (ow - rw) / 2; var trimRight = offset.x - (ow - rw) / 2; var trimBottom = offset.y + (oh - rh) / 2; var trimTop = offset.y - (oh - rh) / 2; l = trimLeft * scaleX - appx; b = trimBottom * scaleY - appy; r = cw + trimRight * scaleX - appx; t = ch + trimTop * scaleY - appy; } var local = this._local; local[0] = l; local[1] = b; local[2] = r; local[3] = t; this.updateWorldVerts(sprite); }; return SimpleSpriteAssembler; })(_assembler2d["default"]); exports["default"] = SimpleSpriteAssembler; module.exports = exports["default"]; }), { "../../../../assembler-2d": 155 } ], 193: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var SlicedAssembler = (function(_Assembler2D) { _inheritsLoose(SlicedAssembler, _Assembler2D); function SlicedAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = SlicedAssembler.prototype; _proto.initData = function initData(sprite) { if (this._renderData.meshCount > 0) return; this._renderData.createData(0, this.verticesFloats, this.indicesCount); var indices = this._renderData.iDatas[0]; var indexOffset = 0; for (var r = 0; r < 3; ++r) for (var c = 0; c < 3; ++c) { var start = 4 * r + c; indices[indexOffset++] = start; indices[indexOffset++] = start + 1; indices[indexOffset++] = start + 4; indices[indexOffset++] = start + 1; indices[indexOffset++] = start + 5; indices[indexOffset++] = start + 4; } }; _proto.initLocal = function initLocal() { this._local = []; this._local.length = 8; }; _proto.updateRenderData = function updateRenderData(sprite) { var frame = sprite._spriteFrame; var assemblerChanged = this.packDynamicAtlasAndCheckMaterial(sprite, frame); if (!assemblerChanged && sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); sprite._vertsDirty = false; } return assemblerChanged; }; _proto.updateVerts = function updateVerts(sprite) { var node = sprite.node, width = node.width, height = node.height, appx = node.anchorX * width, appy = node.anchorY * height; var frame = sprite.spriteFrame; var leftWidth = frame.insetLeft; var rightWidth = frame.insetRight; var topHeight = frame.insetTop; var bottomHeight = frame.insetBottom; var sizableWidth = width - leftWidth - rightWidth; var sizableHeight = height - topHeight - bottomHeight; var xScale = width / (leftWidth + rightWidth); var yScale = height / (topHeight + bottomHeight); xScale = isNaN(xScale) || xScale > 1 ? 1 : xScale; yScale = isNaN(yScale) || yScale > 1 ? 1 : yScale; sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; var local = this._local; local[0] = -appx; local[1] = -appy; local[2] = leftWidth * xScale - appx; local[3] = bottomHeight * yScale - appy; local[4] = local[2] + sizableWidth; local[5] = local[3] + sizableHeight; local[6] = width - appx; local[7] = height - appy; this.updateWorldVerts(sprite); }; _proto.updateUVs = function updateUVs(sprite) { var verts = this._renderData.vDatas[0]; var uvSliced = sprite.spriteFrame.uvSliced; var uvOffset = this.uvOffset; var floatsPerVert = this.floatsPerVert; for (var row = 0; row < 4; ++row) for (var col = 0; col < 4; ++col) { var vid = 4 * row + col; var uv = uvSliced[vid]; var voffset = vid * floatsPerVert; verts[voffset + uvOffset] = uv.u; verts[voffset + uvOffset + 1] = uv.v; } }; _proto.updateWorldVerts = function updateWorldVerts(sprite) { var matrix = sprite.node._worldMatrix; var matrixm = matrix.m, a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5], tx = matrixm[12], ty = matrixm[13]; var local = this._local; var world = this._renderData.vDatas[0]; var floatsPerVert = this.floatsPerVert; for (var row = 0; row < 4; ++row) { var localRowY = local[2 * row + 1]; for (var col = 0; col < 4; ++col) { var localColX = local[2 * col]; var worldIndex = (4 * row + col) * floatsPerVert; world[worldIndex] = localColX * a + localRowY * c + tx; world[worldIndex + 1] = localColX * b + localRowY * d + ty; } } }; return SlicedAssembler; })(_assembler2d["default"]); exports["default"] = SlicedAssembler; Object.assign(SlicedAssembler.prototype, { verticesCount: 16, indicesCount: 54 }); module.exports = exports["default"]; }), { "../../../../assembler-2d": 155 } ], 194: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler2d = _interopRequireDefault(require("../../../../assembler-2d")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var TiledAssembler = (function(_Assembler2D) { _inheritsLoose(TiledAssembler, _Assembler2D); function TiledAssembler() { return _Assembler2D.apply(this, arguments) || this; } var _proto = TiledAssembler.prototype; _proto.initData = function initData(sprite) { this.verticesCount = 0; this.contentWidth = 0; this.contentHeight = 0; this.rectWidth = 0; this.rectHeight = 0; this.hRepeat = 0; this.vRepeat = 0; this.row = 0; this.col = 0; this._renderData.createFlexData(0, 4, 6, this.getVfmt()); this._updateIndices(); }; _proto.initLocal = function initLocal() { this._local = { x: [], y: [] }; }; _proto._updateIndices = function _updateIndices() { var iData = this._renderData.iDatas[0]; for (var i = 0, vid = 0, l = iData.length; i < l; i += 6, vid += 4) { iData[i] = vid; iData[i + 1] = vid + 1; iData[i + 2] = vid + 2; iData[i + 3] = vid + 1; iData[i + 4] = vid + 3; iData[i + 5] = vid + 2; } }; _proto.updateRenderData = function updateRenderData(sprite) { var frame = sprite._spriteFrame; var assemblerChanged = this.packDynamicAtlasAndCheckMaterial(sprite, frame); if (!assemblerChanged) { var node = sprite.node; var contentWidth = this.contentWidth = Math.abs(node.width); var contentHeight = this.contentHeight = Math.abs(node.height); var rect = frame._rect; var leftWidth = frame.insetLeft, rightWidth = frame.insetRight, centerWidth = rect.width - leftWidth - rightWidth, topHeight = frame.insetTop, bottomHeight = frame.insetBottom, centerHeight = rect.height - topHeight - bottomHeight; this.sizableWidth = contentWidth - leftWidth - rightWidth; this.sizableHeight = contentHeight - topHeight - bottomHeight; this.sizableWidth = this.sizableWidth > 0 ? this.sizableWidth : 0; this.sizableHeight = this.sizableHeight > 0 ? this.sizableHeight : 0; var hRepeat = this.hRepeat = 0 === centerWidth ? this.sizableWidth : this.sizableWidth / centerWidth; var vRepeat = this.vRepeat = 0 === centerHeight ? this.sizableHeight : this.sizableHeight / centerHeight; var row = this.row = Math.ceil(vRepeat + 2); var col = this.col = Math.ceil(hRepeat + 2); var count = row * col; this.verticesCount = 4 * count; this.indicesCount = 6 * count; var renderData = this._renderData; var flexBuffer = renderData._flexBuffer; if (flexBuffer.reserve(this.verticesCount, this.indicesCount)) { this._updateIndices(); this.updateColor(sprite); } flexBuffer.used(this.verticesCount, this.indicesCount); if (sprite._vertsDirty) { this.updateUVs(sprite); this.updateVerts(sprite); sprite._vertsDirty = false; } } return assemblerChanged; }; _proto.updateVerts = function updateVerts(sprite) { var frame = sprite._spriteFrame; var rect = frame._rect; var node = sprite.node, appx = node.anchorX * node.width, appy = node.anchorY * node.height; var row = this.row, col = this.col, contentWidth = this.contentWidth, contentHeight = this.contentHeight; var _this$_local = this._local, x = _this$_local.x, y = _this$_local.y; x.length = y.length = 0; var leftWidth = frame.insetLeft, rightWidth = frame.insetRight, centerWidth = rect.width - leftWidth - rightWidth, topHeight = frame.insetTop, bottomHeight = frame.insetBottom, centerHeight = rect.height - topHeight - bottomHeight; var xScale = node.width / (leftWidth + rightWidth) > 1 ? 1 : node.width / (leftWidth + rightWidth); var yScale = node.height / (topHeight + bottomHeight) > 1 ? 1 : node.height / (topHeight + bottomHeight); var offsetWidth = 0, offsetHeight = 0; offsetWidth = centerWidth > 0 ? Math.floor(1e3 * this.sizableWidth) / 1e3 % centerWidth === 0 ? centerWidth : this.sizableWidth % centerWidth : this.sizableWidth; offsetHeight = centerHeight > 0 ? Math.floor(1e3 * this.sizableHeight) / 1e3 % centerHeight === 0 ? centerHeight : this.sizableHeight % centerHeight : this.sizableHeight; for (var i = 0; i <= col; i++) 0 === i ? x[i] = -appx : i > 0 && i < col ? x[i] = 1 === i ? leftWidth * xScale + Math.min(centerWidth, this.sizableWidth) - appx : centerWidth > 0 ? i === col - 1 ? leftWidth + offsetWidth + centerWidth * (i - 2) - appx : leftWidth + Math.min(centerWidth, this.sizableWidth) + centerWidth * (i - 2) - appx : leftWidth + this.sizableWidth - appx : i === col && (x[i] = Math.min(leftWidth + this.sizableWidth + rightWidth, contentWidth) - appx); for (var _i = 0; _i <= row; _i++) 0 === _i ? y[_i] = -appy : _i > 0 && _i < row ? y[_i] = 1 === _i ? bottomHeight * yScale + Math.min(centerHeight, this.sizableHeight) - appy : centerHeight > 0 ? _i === row - 1 ? bottomHeight + offsetHeight + (_i - 2) * centerHeight - appy : bottomHeight + Math.min(centerHeight, this.sizableHeight) + (_i - 2) * centerHeight - appy : bottomHeight + this.sizableHeight - appy : _i === row && (y[_i] = Math.min(bottomHeight + this.sizableHeight + topHeight, contentHeight) - appy); this.updateWorldVerts(sprite); }; _proto.updateWorldVerts = function updateWorldVerts(sprite) { var renderData = this._renderData; var local = this._local; var localX = local.x, localY = local.y; var world = renderData.vDatas[0]; var row = this.row, col = this.col; var matrix = sprite.node._worldMatrix; var matrixm = matrix.m; var a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5], tx = matrixm[12], ty = matrixm[13]; var x, x1, y, y1; var floatsPerVert = this.floatsPerVert; var vertexOffset = 0; for (var yindex = 0, ylength = row; yindex < ylength; ++yindex) { y = localY[yindex]; y1 = localY[yindex + 1]; for (var xindex = 0, xlength = col; xindex < xlength; ++xindex) { x = localX[xindex]; x1 = localX[xindex + 1]; world[vertexOffset] = x * a + y * c + tx; world[vertexOffset + 1] = x * b + y * d + ty; vertexOffset += floatsPerVert; world[vertexOffset] = x1 * a + y * c + tx; world[vertexOffset + 1] = x1 * b + y * d + ty; vertexOffset += floatsPerVert; world[vertexOffset] = x * a + y1 * c + tx; world[vertexOffset + 1] = x * b + y1 * d + ty; vertexOffset += floatsPerVert; world[vertexOffset] = x1 * a + y1 * c + tx; world[vertexOffset + 1] = x1 * b + y1 * d + ty; vertexOffset += floatsPerVert; } } }; _proto.updateUVs = function updateUVs(sprite) { var verts = this._renderData.vDatas[0]; if (!verts) return; var frame = sprite._spriteFrame; var rect = frame._rect; var leftWidth = frame.insetLeft, rightWidth = frame.insetRight, centerWidth = rect.width - leftWidth - rightWidth, topHeight = frame.insetTop, bottomHeight = frame.insetBottom, centerHeight = rect.height - topHeight - bottomHeight; var row = this.row, col = this.col, hRepeat = this.hRepeat, vRepeat = this.vRepeat; var coefu = 0, coefv = 0; var uv = sprite.spriteFrame.uv; var uvSliced = sprite.spriteFrame.uvSliced; var rotated = sprite.spriteFrame._rotated; var floatsPerVert = this.floatsPerVert, uvOffset = this.uvOffset; var tempXVerts = [], tempYVerts = []; for (var yindex = 0, ylength = row; yindex < ylength; ++yindex) { coefv = this.sizableHeight > centerHeight ? this.sizableHeight >= yindex * centerHeight ? 1 : vRepeat % 1 : vRepeat; for (var xindex = 0, xlength = col; xindex < xlength; ++xindex) { coefu = this.sizableWidth > centerWidth ? this.sizableWidth >= xindex * centerWidth ? 1 : hRepeat % 1 : hRepeat; if (rotated) { if (0 === yindex) { tempXVerts[0] = uvSliced[0].u; tempXVerts[1] = uvSliced[0].u; tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefv; } else if (yindex < row - 1) { tempXVerts[0] = uvSliced[4].u; tempXVerts[1] = uvSliced[4].u; tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefv; } else if (yindex === row - 1) { tempXVerts[0] = uvSliced[8].u; tempXVerts[1] = uvSliced[8].u; tempXVerts[2] = uvSliced[12].u; } if (0 === xindex) { tempYVerts[0] = uvSliced[0].v; tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefu; tempYVerts[2] = uvSliced[0].v; } else if (xindex < col - 1) { tempYVerts[0] = uvSliced[1].v; tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefu; tempYVerts[2] = uvSliced[1].v; } else if (xindex === col - 1) { tempYVerts[0] = uvSliced[2].v; tempYVerts[1] = uvSliced[3].v; tempYVerts[2] = uvSliced[2].v; } tempXVerts[3] = tempXVerts[2]; tempYVerts[3] = tempYVerts[1]; } else { if (0 === xindex) { tempXVerts[0] = uvSliced[0].u; tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefu; tempXVerts[2] = uv[0]; } else if (xindex < col - 1) { tempXVerts[0] = uvSliced[1].u; tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefu; tempXVerts[2] = uvSliced[1].u; } else if (xindex === col - 1) { tempXVerts[0] = uvSliced[2].u; tempXVerts[1] = uvSliced[3].u; tempXVerts[2] = uvSliced[2].u; } if (0 === yindex) { tempYVerts[0] = uvSliced[0].v; tempYVerts[1] = uvSliced[0].v; tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefv; } else if (yindex < row - 1) { tempYVerts[0] = uvSliced[4].v; tempYVerts[1] = uvSliced[4].v; tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefv; } else if (yindex === row - 1) { tempYVerts[0] = uvSliced[8].v; tempYVerts[1] = uvSliced[8].v; tempYVerts[2] = uvSliced[12].v; } tempXVerts[3] = tempXVerts[1]; tempYVerts[3] = tempYVerts[2]; } verts[uvOffset] = tempXVerts[0]; verts[uvOffset + 1] = tempYVerts[0]; uvOffset += floatsPerVert; verts[uvOffset] = tempXVerts[1]; verts[uvOffset + 1] = tempYVerts[1]; uvOffset += floatsPerVert; verts[uvOffset] = tempXVerts[2]; verts[uvOffset + 1] = tempYVerts[2]; uvOffset += floatsPerVert; verts[uvOffset] = tempXVerts[3]; verts[uvOffset + 1] = tempYVerts[3]; uvOffset += floatsPerVert; } } }; return TiledAssembler; })(_assembler2d["default"]); exports["default"] = TiledAssembler; module.exports = exports["default"]; }), { "../../../../assembler-2d": 155 } ], 195: [ (function(require, module, exports) { "use strict"; var _assembler = _interopRequireDefault(require("../../../assembler")); var _CCSprite = require("../../../../components/CCSprite"); var _simple = _interopRequireDefault(require("./2d/simple")); var _sliced = _interopRequireDefault(require("./2d/sliced")); var _tiled = _interopRequireDefault(require("./2d/tiled")); var _radialFilled = _interopRequireDefault(require("./2d/radial-filled")); var _barFilled = _interopRequireDefault(require("./2d/bar-filled")); var _mesh = _interopRequireDefault(require("./2d/mesh")); var _simple2 = _interopRequireDefault(require("./3d/simple")); var _sliced2 = _interopRequireDefault(require("./3d/sliced")); var _tiled2 = _interopRequireDefault(require("./3d/tiled")); var _radialFilled2 = _interopRequireDefault(require("./3d/radial-filled")); var _barFilled2 = _interopRequireDefault(require("./3d/bar-filled")); var _mesh2 = _interopRequireDefault(require("./3d/mesh")); var _simple3 = _interopRequireDefault(require("./2d-multi/simple")); var _sliced3 = _interopRequireDefault(require("./2d-multi/sliced")); var _tiled3 = _interopRequireDefault(require("./2d-multi/tiled")); var _radialFilled3 = _interopRequireDefault(require("./2d-multi/radial-filled")); var _barFilled3 = _interopRequireDefault(require("./2d-multi/bar-filled")); var _mesh3 = _interopRequireDefault(require("./2d-multi/mesh")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ctor = { getConstructor: function getConstructor(sprite) { var is3DNode = sprite.node.is3DNode; var material = sprite.getMaterials()[0]; var isMultiMaterial = material && material.material.isMultiSupport(); var ctor = is3DNode ? _simple2["default"] : isMultiMaterial ? _simple3["default"] : _simple["default"]; switch (sprite.type) { case _CCSprite.Type.SLICED: ctor = is3DNode ? _sliced2["default"] : isMultiMaterial ? _sliced3["default"] : _sliced["default"]; break; case _CCSprite.Type.TILED: ctor = is3DNode ? _tiled2["default"] : isMultiMaterial ? _tiled3["default"] : _tiled["default"]; break; case _CCSprite.Type.FILLED: ctor = sprite._fillType === _CCSprite.FillType.RADIAL ? is3DNode ? _radialFilled2["default"] : isMultiMaterial ? _radialFilled3["default"] : _radialFilled["default"] : is3DNode ? _barFilled2["default"] : isMultiMaterial ? _barFilled3["default"] : _barFilled["default"]; break; case _CCSprite.Type.MESH: ctor = is3DNode ? _mesh2["default"] : isMultiMaterial ? _mesh3["default"] : _mesh["default"]; } return ctor; }, Simple: _simple["default"], Sliced: _sliced["default"], Tiled: _tiled["default"], RadialFilled: _radialFilled["default"], BarFilled: _barFilled["default"], Mesh: _mesh["default"], Simple3D: _simple2["default"], Sliced3D: _sliced2["default"], Tiled3D: _tiled2["default"], RadialFilled3D: _radialFilled2["default"], BarFilled3D: _barFilled2["default"], Mesh3D: _mesh2["default"], SimpleMulti: _simple3["default"], SlicedMulti: _sliced3["default"], TiledMulti: _tiled3["default"], RadialFilledMulti: _radialFilled3["default"], BarFilledMulti: _barFilled3["default"], MeshMulti: _mesh3["default"] }; _assembler["default"].register(cc.Sprite, ctor); }), { "../../../../components/CCSprite": 105, "../../../assembler": 157, "./2d-multi/bar-filled": 183, "./2d-multi/mesh": 184, "./2d-multi/radial-filled": 185, "./2d-multi/simple": 186, "./2d-multi/sliced": 187, "./2d-multi/tiled": 188, "./2d/bar-filled": 189, "./2d/mesh": 190, "./2d/radial-filled": 191, "./2d/simple": 192, "./2d/sliced": 193, "./2d/tiled": 194, "./3d/bar-filled": void 0, "./3d/mesh": void 0, "./3d/radial-filled": void 0, "./3d/simple": void 0, "./3d/sliced": void 0, "./3d/tiled": void 0 } ], 196: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var FlexBuffer = (function() { function FlexBuffer(handler, index, verticesCount, indicesCount, vfmt) { this._handler = handler; this._index = index; this._vfmt = vfmt; this._verticesBytes = vfmt._bytes; this._initVerticesCount = verticesCount; this._initIndicesCount = indicesCount; this.reset(); } var _proto = FlexBuffer.prototype; _proto._reallocVData = function _reallocVData(floatsCount, oldData) { this.vData = new Float32Array(floatsCount); this.uintVData = new Uint32Array(this.vData.buffer); oldData && this.vData.set(oldData); this._handler.updateMesh(this._index, this.vData, this.iData); }; _proto._reallocIData = function _reallocIData(indicesCount, oldData) { this.iData = new Uint16Array(indicesCount); oldData && this.iData.set(oldData); this._handler.updateMesh(this._index, this.vData, this.iData); }; _proto.reserve = function reserve(verticesCount, indicesCount) { var floatsCount = verticesCount * this._verticesBytes >> 2; var newFloatsCount = this.vData.length; var realloced = false; if (floatsCount > newFloatsCount) { while (newFloatsCount < floatsCount) newFloatsCount *= 2; this._reallocVData(newFloatsCount, this.vData); realloced = true; } var newIndicesCount = this.iData.length; if (indicesCount > newIndicesCount) { while (newIndicesCount < indicesCount) newIndicesCount *= 2; this._reallocIData(indicesCount, this.iData); realloced = true; } return realloced; }; _proto.used = function used(verticesCount, indicesCount) { this.usedVertices = verticesCount; this.usedIndices = indicesCount; this.usedVerticesFloats = verticesCount * this._verticesBytes >> 2; this._handler.updateMeshRange(verticesCount, indicesCount); }; _proto.reset = function reset() { var floatsCount = this._initVerticesCount * this._verticesBytes >> 2; this._reallocVData(floatsCount); this._reallocIData(this._initIndicesCount); this.usedVertices = 0; this.usedVerticesFloats = 0; this.usedIndices = 0; }; return FlexBuffer; })(); exports["default"] = FlexBuffer; cc.FlexBuffer = FlexBuffer; module.exports = exports["default"]; }), {} ], 197: [ (function(require, module, exports) { "use strict"; var _gfx = _interopRequireDefault(require("../../../renderer/gfx")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var FIX_IOS14_BUFFER; if (cc.sys.platform === cc.sys.WECHAT_GAME) { var _GameGlobal; FIX_IOS14_BUFFER = (cc.sys.os === cc.sys.OS_IOS || cc.sys.os === cc.sys.OS_OSX) && (null == (_GameGlobal = GameGlobal) ? void 0 : _GameGlobal.isIOSHighPerformanceMode) && /(OS 1[4-9])|(Version\/1[4-9])/.test(window.navigator.userAgent); } else FIX_IOS14_BUFFER = (cc.sys.os === cc.sys.OS_IOS || cc.sys.os === cc.sys.OS_OSX) && cc.sys.isBrowser && /(OS 1[4-9])|(Version\/1[4-9])/.test(window.navigator.userAgent); var MeshBuffer = cc.Class({ name: "cc.MeshBuffer", ctor: function ctor(batcher, vertexFormat) { this.init(batcher, vertexFormat); }, init: function init(batcher, vertexFormat) { this.byteOffset = 0; this.indiceOffset = 0; this.vertexOffset = 0; this.indiceStart = 0; this._dirty = false; this._vertexFormat = vertexFormat; this._vertexBytes = this._vertexFormat._bytes; this._arrOffset = 0; this._vbArr = []; this._vb = new _gfx["default"].VertexBuffer(batcher._device, vertexFormat, _gfx["default"].USAGE_DYNAMIC, new ArrayBuffer(), 0); this._vbArr[0] = this._vb; this._ibArr = []; this._ib = new _gfx["default"].IndexBuffer(batcher._device, _gfx["default"].INDEX_FMT_UINT16, _gfx["default"].USAGE_STATIC, new ArrayBuffer(), 0); this._ibArr[0] = this._ib; this._vData = null; this._uintVData = null; this._iData = null; this._batcher = batcher; this._initVDataCount = 256 * vertexFormat._bytes; this._initIDataCount = 1536; this._offsetInfo = { byteOffset: 0, vertexOffset: 0, indiceOffset: 0 }; this._reallocBuffer(); }, uploadData: function uploadData() { if (0 === this.byteOffset || !this._dirty) return; var vertexsData = new Float32Array(this._vData.buffer, 0, this.byteOffset >> 2); var indicesData = new Uint16Array(this._iData.buffer, 0, this.indiceOffset); var vb = this._vb; vb.update(0, vertexsData); var ib = this._ib; ib.update(0, indicesData); this._dirty = false; }, switchBuffer: function switchBuffer() { var offset = ++this._arrOffset; this.byteOffset = 0; this.vertexOffset = 0; this.indiceOffset = 0; this.indiceStart = 0; if (offset < this._vbArr.length) { this._vb = this._vbArr[offset]; this._ib = this._ibArr[offset]; } else { this._vb = new _gfx["default"].VertexBuffer(this._batcher._device, this._vertexFormat, _gfx["default"].USAGE_DYNAMIC, new ArrayBuffer(), 0); this._vbArr[offset] = this._vb; this._ib = new _gfx["default"].IndexBuffer(this._batcher._device, _gfx["default"].INDEX_FMT_UINT16, _gfx["default"].USAGE_STATIC, new ArrayBuffer(), 0); this._ibArr[offset] = this._ib; } }, checkAndSwitchBuffer: function checkAndSwitchBuffer(vertexCount) { if (this.vertexOffset + vertexCount > 65535) { this.uploadData(); this._batcher._flush(); this.switchBuffer(); } }, requestStatic: function requestStatic(vertexCount, indiceCount) { this.checkAndSwitchBuffer(vertexCount); var byteOffset = this.byteOffset + vertexCount * this._vertexBytes; var indiceOffset = this.indiceOffset + indiceCount; var byteLength = this._vData.byteLength; var indiceLength = this._iData.length; if (byteOffset > byteLength || indiceOffset > indiceLength) { while (byteLength < byteOffset || indiceLength < indiceOffset) { this._initVDataCount *= 2; this._initIDataCount *= 2; byteLength = 4 * this._initVDataCount; indiceLength = this._initIDataCount; } this._reallocBuffer(); } this._updateOffset(vertexCount, indiceCount, byteOffset); }, _updateOffset: function _updateOffset(vertexCount, indiceCount, byteOffset) { var offsetInfo = this._offsetInfo; offsetInfo.vertexOffset = this.vertexOffset; this.vertexOffset += vertexCount; offsetInfo.indiceOffset = this.indiceOffset; this.indiceOffset += indiceCount; offsetInfo.byteOffset = this.byteOffset; this.byteOffset = byteOffset; this._dirty = true; }, request: function request(vertexCount, indiceCount) { if (this._batcher._buffer !== this) { this._batcher._flush(); this._batcher._buffer = this; } this.requestStatic(vertexCount, indiceCount); return this._offsetInfo; }, requestForSpine: function requestForSpine(vertexCount, indiceCount) { if (this._batcher._buffer !== this) { this._batcher._flush(); this._batcher._buffer = this; } this.requestStaticForSpine(vertexCount, indiceCount); return this._offsetInfo; }, requestStaticForSpine: function requestStaticForSpine(vertexCount, indiceCount) { this.checkAndSwitchBuffer(vertexCount); var byteOffset = this.byteOffset + vertexCount * this._vertexBytes; var indiceOffset = this.indiceOffset + indiceCount; var byteLength = this._vData.byteLength; var indiceLength = this._iData.length; if (byteOffset > byteLength || indiceOffset > indiceLength) { while (byteLength < byteOffset || indiceLength < indiceOffset) { this._initVDataCount *= 2; this._initIDataCount *= 2; byteLength = 4 * this._initVDataCount; indiceLength = this._initIDataCount; } this._reallocBuffer(); } var offsetInfo = this._offsetInfo; offsetInfo.vertexOffset = this.vertexOffset; offsetInfo.indiceOffset = this.indiceOffset; offsetInfo.byteOffset = this.byteOffset; }, adjustForSpine: function adjustForSpine(vertexCount, indiceCount) { this.vertexOffset += vertexCount; this.indiceOffset += indiceCount; this.byteOffset = this.byteOffset + vertexCount * this._vertexBytes; this._dirty = true; }, _reallocBuffer: function _reallocBuffer() { this._reallocVData(true); this._reallocIData(true); }, _reallocVData: function _reallocVData(copyOldData) { var oldVData; this._vData && (oldVData = new Uint8Array(this._vData.buffer)); this._vData = new Float32Array(this._initVDataCount); this._uintVData = new Uint32Array(this._vData.buffer); var newData = new Uint8Array(this._uintVData.buffer); if (oldVData && copyOldData) for (var i = 0, l = oldVData.length; i < l; i++) newData[i] = oldVData[i]; }, _reallocIData: function _reallocIData(copyOldData) { var oldIData = this._iData; this._iData = new Uint16Array(this._initIDataCount); if (oldIData && copyOldData) { var iData = this._iData; for (var i = 0, l = oldIData.length; i < l; i++) iData[i] = oldIData[i]; } }, reset: function reset() { this._arrOffset = 0; this._vb = this._vbArr[0]; this._ib = this._ibArr[0]; this.byteOffset = 0; this.indiceOffset = 0; this.vertexOffset = 0; this.indiceStart = 0; this._dirty = false; }, destroy: function destroy() { this.reset(); for (var i = 0; i < this._vbArr.length; i++) { var vb = this._vbArr[i]; vb.destroy(); } this._vbArr = null; for (var _i = 0; _i < this._ibArr.length; _i++) { var ib = this._ibArr[_i]; ib.destroy(); } this._ibArr = null; this._ib = null; this._vb = null; }, forwardIndiceStartToOffset: function forwardIndiceStartToOffset() { this.indiceStart = this.indiceOffset; } }); if (FIX_IOS14_BUFFER) { MeshBuffer.prototype.checkAndSwitchBuffer = function(vertexCount) { if (this.vertexOffset + vertexCount > 65535) { this.uploadData(); this._batcher._flush(); } }; MeshBuffer.prototype.forwardIndiceStartToOffset = function() { this.uploadData(); this.switchBuffer(); }; } cc.MeshBuffer = module.exports = MeshBuffer; }), { "../../../renderer/gfx": 259 } ], 198: [ (function(require, module, exports) { "use strict"; var _inputAssembler = _interopRequireDefault(require("../../../renderer/core/input-assembler")); var _recyclePool = _interopRequireDefault(require("../../../renderer/memop/recycle-pool")); var _model = _interopRequireDefault(require("../../../renderer/scene/model")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _require = require("./vertex-format"), vfmtPosUvColor = _require.vfmtPosUvColor, vfmt3D = _require.vfmt3D; var QuadBuffer = require("./quad-buffer"); var MeshBuffer = require("./mesh-buffer"); var SpineBuffer = require("./spine-buffer"); var Material = require("../../assets/material/CCMaterial"); var idGenerater = new (require("../../platform/id-generater"))("VertextFormat"); var _buffers = {}; var empty_material = new Material(); var empty_ia = new _inputAssembler["default"](); empty_ia._count = 0; var ModelBatcher = function ModelBatcher(device, renderScene) { this._renderScene = renderScene; this._device = device; this.walking = false; this.material = empty_material; this.cullingMask = 1; this._iaPool = new _recyclePool["default"](function() { return new _inputAssembler["default"](); }, 16); this._modelPool = new _recyclePool["default"](function() { return new _model["default"](); }, 16); this._quadBuffer = this.getBuffer("quad", vfmtPosUvColor); this._meshBuffer = this.getBuffer("mesh", vfmtPosUvColor); this._quadBuffer3D = this.getBuffer("quad", vfmt3D); this._meshBuffer3D = this.getBuffer("mesh", vfmt3D); this._buffer = this._meshBuffer; this._batchedModels = []; this._dummyNode = new cc.Node(); this._sortKey = 0; this.node = this._dummyNode; this.parentOpacity = 1; this.parentOpacityDirty = 0; this.worldMatDirty = 0; }; ModelBatcher.prototype = { constructor: ModelBatcher, reset: function reset() { this._iaPool.reset(); var scene = this._renderScene; var models = this._batchedModels; for (var i = 0; i < models.length; ++i) { models[i].setInputAssembler(null); models[i].setEffect(null); scene.removeModel(models[i]); } this._modelPool.reset(); models.length = 0; this._sortKey = 0; for (var key in _buffers) _buffers[key].reset(); this._buffer = this._meshBuffer; this.node = this._dummyNode; this.material = empty_material; this.cullingMask = 1; this.parentOpacity = 1; this.parentOpacityDirty = 0; this.worldMatDirty = 0; }, _flushMaterial: function _flushMaterial(material) { if (!material) return; this.material = material; var effect = material.effect; if (!effect) return; var model = this._modelPool.add(); this._batchedModels.push(model); model.sortKey = this._sortKey++; model._cullingMask = this.cullingMask; model.setNode(this.node); model.setEffect(effect, null); model.setInputAssembler(empty_ia); this._renderScene.addModel(model); }, _flush: function _flush() { var material = this.material, buffer = this._buffer, indiceCount = buffer.indiceOffset - buffer.indiceStart; if (!this.walking || !material || indiceCount <= 0) return; var effect = material.effect; if (!effect) return; var ia = this._iaPool.add(); ia._vertexBuffer = buffer._vb; ia._indexBuffer = buffer._ib; ia._start = buffer.indiceStart; ia._count = indiceCount; var model = this._modelPool.add(); this._batchedModels.push(model); model.sortKey = this._sortKey++; model._cullingMask = this.cullingMask; model.setNode(this.node); model.setEffect(effect); model.setInputAssembler(ia); this._renderScene.addModel(model); buffer.forwardIndiceStartToOffset(); }, _flushIA: function _flushIA(ia) { if (!ia) return; var material = this.material; var effect = material.effect; if (!effect) return; var model = this._modelPool.add(); this._batchedModels.push(model); model.sortKey = this._sortKey++; model._cullingMask = this.cullingMask; model.setNode(this.node); model.setEffect(effect); model.setInputAssembler(ia); this._renderScene.addModel(model); }, terminate: function terminate() { cc.dynamicAtlasManager && cc.dynamicAtlasManager.enabled && cc.dynamicAtlasManager.update(); this._flush(); for (var key in _buffers) _buffers[key].uploadData(); this.walking = false; }, getBuffer: function getBuffer(type, vertextFormat) { var key = type + vertextFormat.getHash(); var buffer = _buffers[key]; if (!buffer) { if ("mesh" === type) buffer = new MeshBuffer(this, vertextFormat); else if ("quad" === type) buffer = new QuadBuffer(this, vertextFormat); else { if ("spine" !== type) { cc.error("Not support buffer type [" + type + "]"); return null; } buffer = new SpineBuffer(this, vertextFormat); } _buffers[key] = buffer; } return buffer; } }; module.exports = ModelBatcher; }), { "../../../renderer/core/input-assembler": 249, "../../../renderer/memop/recycle-pool": 274, "../../../renderer/scene/model": 280, "../../assets/material/CCMaterial": 76, "../../platform/id-generater": 146, "./mesh-buffer": 197, "./quad-buffer": 199, "./spine-buffer": 201, "./vertex-format": 202 } ], 199: [ (function(require, module, exports) { "use strict"; var MeshBuffer = require("./mesh-buffer"); var QuadBuffer = cc.Class({ name: "cc.QuadBuffer", extends: MeshBuffer, _fillQuadBuffer: function _fillQuadBuffer() { var count = this._initIDataCount / 6; var buffer = this._iData; for (var i = 0, idx = 0; i < count; i++) { var vertextID = 4 * i; buffer[idx++] = vertextID; buffer[idx++] = vertextID + 1; buffer[idx++] = vertextID + 2; buffer[idx++] = vertextID + 1; buffer[idx++] = vertextID + 3; buffer[idx++] = vertextID + 2; } var indicesData = new Uint16Array(this._iData.buffer, 0, 6 * count); this._ib.update(0, indicesData); }, uploadData: function uploadData() { if (0 === this.byteOffset || !this._dirty) return; var vertexsData = new Float32Array(this._vData.buffer, 0, this.byteOffset >> 2); this._vb.update(0, vertexsData); this._dirty = false; }, switchBuffer: function switchBuffer() { this._super(); var indicesData = new Uint16Array(this._iData.buffer, 0, this._initIDataCount); this._ib.update(0, indicesData); }, _reallocBuffer: function _reallocBuffer() { this._reallocVData(true); this._reallocIData(); this._fillQuadBuffer(); } }); cc.QuadBuffer = module.exports = QuadBuffer; }), { "./mesh-buffer": 197 } ], 200: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = RenderData; var _flexBuffer = _interopRequireDefault(require("./flex-buffer")); var _vertexFormat = require("./vertex-format"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function RenderData() { this.vDatas = []; this.uintVDatas = []; this.iDatas = []; this.meshCount = 0; this._infos = null; this._flexBuffer = null; } cc.js.mixin(RenderData.prototype, { init: function init(assembler) {}, clear: function clear() { this.vDatas.length = 0; this.iDatas.length = 0; this.uintVDatas.length = 0; this.meshCount = 0; this._infos = null; this._flexBuffer && this._flexBuffer.reset(); }, updateMesh: function updateMesh(index, vertices, indices) { this.vDatas[index] = vertices; this.uintVDatas[index] = new Uint32Array(vertices.buffer, 0, vertices.length); this.iDatas[index] = indices; this.meshCount = this.vDatas.length; }, updateMeshRange: function updateMeshRange(verticesCount, indicesCount) {}, createData: function createData(index, verticesFloats, indicesCount) { var vertices = new Float32Array(verticesFloats); var indices = new Uint16Array(indicesCount); this.updateMesh(index, vertices, indices); }, createQuadData: function createQuadData(index, verticesFloats, indicesCount) { this.createData(index, verticesFloats, indicesCount); this.initQuadIndices(this.iDatas[index]); }, createFlexData: function createFlexData(index, verticesFloats, indicesCount, vfmt) { vfmt = vfmt || _vertexFormat.vfmtPosUvColor; this._flexBuffer = new _flexBuffer["default"](this, index, verticesFloats, indicesCount, vfmt); }, initQuadIndices: function initQuadIndices(indices) { var count = indices.length / 6; for (var i = 0, idx = 0; i < count; i++) { var vertextID = 4 * i; indices[idx++] = vertextID; indices[idx++] = vertextID + 1; indices[idx++] = vertextID + 2; indices[idx++] = vertextID + 1; indices[idx++] = vertextID + 3; indices[idx++] = vertextID + 2; } } }); cc.RenderData = RenderData; module.exports = exports["default"]; }), { "./flex-buffer": 196, "./vertex-format": 202 } ], 201: [ (function(require, module, exports) { "use strict"; var SpineBuffer = cc.Class({ name: "cc.SpineBuffer", extends: require("./mesh-buffer"), requestStatic: function requestStatic(vertexCount, indiceCount) { this.checkAndSwitchBuffer(vertexCount); var byteOffset = this.byteOffset + vertexCount * this._vertexBytes; var indiceOffset = this.indiceOffset + indiceCount; var byteLength = this._vData.byteLength; var indiceLength = this._iData.length; if (byteOffset > byteLength || indiceOffset > indiceLength) { while (byteLength < byteOffset || indiceLength < indiceOffset) { this._initVDataCount *= 2; this._initIDataCount *= 2; byteLength = 4 * this._initVDataCount; indiceLength = this._initIDataCount; } this._reallocBuffer(); } var offsetInfo = this._offsetInfo; offsetInfo.vertexOffset = this.vertexOffset; offsetInfo.indiceOffset = this.indiceOffset; offsetInfo.byteOffset = this.byteOffset; }, adjust: function adjust(vertexCount, indiceCount) { this.vertexOffset += vertexCount; this.indiceOffset += indiceCount; this.byteOffset = this.byteOffset + vertexCount * this._vertexBytes; this._dirty = true; } }); cc.SpineBuffer = module.exports = SpineBuffer; }), { "./mesh-buffer": 197 } ], 202: [ (function(require, module, exports) { "use strict"; var _gfx = _interopRequireDefault(require("../../../renderer/gfx")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var vfmt3D = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 3 }, { name: _gfx["default"].ATTR_UV0, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_COLOR, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true } ]); vfmt3D.name = "vfmt3D"; _gfx["default"].VertexFormat.XYZ_UV_Color = vfmt3D; var vfmtPosUvColor = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_UV0, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_COLOR, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true } ]); vfmtPosUvColor.name = "vfmtPosUvColor"; _gfx["default"].VertexFormat.XY_UV_Color = vfmtPosUvColor; var vfmtPosUvColorTexId = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_UV0, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_COLOR, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true }, { name: _gfx["default"].ATTR_TEX_ID, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 1 } ]); vfmtPosUvColorTexId.name = "vfmtPosUvColorTexId"; _gfx["default"].VertexFormat.XY_UV_Color_TexId = vfmtPosUvColorTexId; var vfmtPosUvTwoColor = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_UV0, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_COLOR, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true }, { name: _gfx["default"].ATTR_COLOR0, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true } ]); vfmtPosUvTwoColor.name = "vfmtPosUvTwoColor"; _gfx["default"].VertexFormat.XY_UV_Two_Color = vfmtPosUvTwoColor; var vfmtPosUvTwoColorTexId = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_UV0, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_COLOR, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true }, { name: _gfx["default"].ATTR_COLOR0, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true }, { name: _gfx["default"].ATTR_TEX_ID, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 1 } ]); vfmtPosUvTwoColorTexId.name = "vfmtPosUvTwoColorTexId"; _gfx["default"].VertexFormat.XY_UV_Two_Color_TexId = vfmtPosUvTwoColorTexId; var vfmtPosUv = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_UV0, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 } ]); vfmtPosUv.name = "vfmtPosUv"; _gfx["default"].VertexFormat.XY_UV = vfmtPosUv; var vfmtPosColor = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 }, { name: _gfx["default"].ATTR_COLOR, type: _gfx["default"].ATTR_TYPE_UINT8, num: 4, normalize: true } ]); vfmtPosColor.name = "vfmtPosColor"; _gfx["default"].VertexFormat.XY_Color = vfmtPosColor; var vfmtPos = new _gfx["default"].VertexFormat([ { name: _gfx["default"].ATTR_POSITION, type: _gfx["default"].ATTR_TYPE_FLOAT32, num: 2 } ]); vfmtPos.name = "vfmtPos"; _gfx["default"].VertexFormat.XY = vfmtPos; module.exports = { vfmt3D: vfmt3D, vfmtPosUvColor: vfmtPosUvColor, vfmtPosUvTwoColor: vfmtPosUvTwoColor, vfmtPosUv: vfmtPosUv, vfmtPosColor: vfmtPosColor, vfmtPos: vfmtPos, vfmtPosUvColorTexId: vfmtPosUvColorTexId, vfmtPosUvTwoColorTexId: vfmtPosUvTwoColorTexId }; }), { "../../../renderer/gfx": 259 } ], 203: [ (function(require, module, exports) { "use strict"; require("./sp"); require("./multi-handler"); require("./multi-batcher"); }), { "./multi-batcher": 204, "./multi-handler": 205, "./sp": 206 } ], 204: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.MultiBatcher = void 0; var _multiHandler = require("./multi-handler"); function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = "undefined" !== typeof Symbol && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && "number" === typeof o.length) { it && (o = it); var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if ("string" === typeof o) return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); "Object" === n && o.constructor && (n = o.constructor.name); if ("Map" === n || "Set" === n) return Array.from(o); if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { (null == len || len > arr.length) && (len = arr.length); for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var MultiBatcher = (function() { function MultiBatcher() { this.handlers = []; this.nextHandler = void 0; } var _proto = MultiBatcher.prototype; _proto.init = function init() { var handler = new _multiHandler.MultiHandler(); this.handlers.push(handler); this.nextHandler = handler; }; _proto.requsetMaterial = function requsetMaterial(texture) { if (!texture._multiMaterial) { var handler = this.nextHandler; var index = handler.getEmptyIndex(); if (-1 === index) { for (var _iterator = _createForOfIteratorHelperLoose(this.handlers), _step; !(_step = _iterator()).done; ) { var _handler = _step.value; index = _handler.getEmptyIndex(); if (-1 !== index) { handler = _handler; this.nextHandler = handler; break; } } if (-1 === index) { handler = new _multiHandler.MultiHandler(); this.handlers.push(handler); this.nextHandler = handler; index = 0; } } texture.linkMaterial(handler.material, index); } return texture._multiMaterial; }; _proto.reset = function reset() { this.handlers.length = 0; }; return MultiBatcher; })(); exports.MultiBatcher = MultiBatcher; cc.sp.multiBatcher = new MultiBatcher(); cc.sp.MultiBatcher = MultiBatcher; }), { "./multi-handler": 205 } ], 205: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.MultiHandler = void 0; var MultiHandler = (function() { function MultiHandler(material) { this.material = void 0; this.textures = []; this.hasEmptySlot = false; if (material) this.material = material; else { this.material = cc.Material.create(cc.sp.multi2dSpriteEffectAsset); this.material.name = "multi-2d-universal"; this.material.define("USE_TEXTURE", true); this.material.define("USE_MULTI_TEXTURE", true); } this.material._multiHandler = this; this.syncTextures(); } var _proto = MultiHandler.prototype; _proto.syncTextures = function syncTextures() { var effect = this.material["effect"]; var properties = effect.passes[0]._properties; this.textures[0] = properties.texture.value; this.textures[1] = properties.texture2.value; this.textures[2] = properties.texture3.value; this.textures[3] = properties.texture4.value; this.textures[4] = properties.texture5.value; this.textures[5] = properties.texture6.value; this.textures[6] = properties.texture7.value; this.textures[7] = properties.texture8.value; this.hasEmptySlot = true; this.getEmptyIndex(); }; _proto.setTexture = function setTexture(index, texture) { this.textures[index] = texture ? texture.getImpl() : null; this.material.setProperty(cc.sp.propertyIndex2Name(index), texture); null == texture && (this.hasEmptySlot = true); }; _proto.removeTexture = function removeTexture(texture) { var index = this.getIndex(texture); -1 !== index && this.setTexture(index, null); }; _proto.hasTexture = function hasTexture(texture) { return -1 !== this.textures.indexOf(texture); }; _proto.getIndex = function getIndex(texture) { return this.textures.indexOf(texture); }; _proto.getTexture = function getTexture(index) { return this.textures[index]; }; _proto.getEmptyIndex = function getEmptyIndex() { if (!this.hasEmptySlot) return -1; var index = this.textures.indexOf(null); if (-1 !== index) return index; this.hasEmptySlot = false; return -1; }; _proto.autoSetTexture = function autoSetTexture(texture) { var index = this.getEmptyIndex(); if (-1 === index) return -1; this.setTexture(index, texture); return index; }; return MultiHandler; })(); exports.MultiHandler = MultiHandler; cc.sp.MultiHandler = MultiHandler; }), {} ], 206: [ (function(require, module, exports) { "use strict"; cc.sp = { inited: false, version: "1.0.0", MAX_MULTITEXTURE_NUM: -1, autoSwitchMaterial: true, allowDynamicAtlas: true, enableLabelRetina: true, labelRetinaScale: 1, charAtlasAutoBatchCount: 1, charAtlasAutoResetBeforeSceneLoad: true, multi2dSpriteEffectAsset: null, i2nMap: [ "texture" ], n2iMap: { texture: 0 }, propertyIndex2Name: function propertyIndex2Name(index) { return this.i2nMap[index]; }, propertyName2Index: function propertyName2Index(name) { return this.n2iMap[name]; } }; for (var i = 1; i < 8; i++) { var name = "texture" + (i + 1); cc.sp.i2nMap[i] = name; cc.sp.n2iMap[name] = i; } }), {} ], 207: [ (function(require, module, exports) { "use strict"; require("../platform/CCSys"); var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; var DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/; var NORMALIZE_RE = /[^\.\/]+\/\.\.\//; cc.path = { join: function join() { var l = arguments.length; var result = ""; for (var i = 0; i < l; i++) result = (result + ("" === result ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); return result; }, extname: function extname(pathStr) { var temp = EXTNAME_RE.exec(pathStr); return temp ? temp[1] : ""; }, mainFileName: function mainFileName(fileName) { if (fileName) { var idx = fileName.lastIndexOf("."); if (-1 !== idx) return fileName.substring(0, idx); } return fileName; }, basename: function basename(pathStr, extname) { var index = pathStr.indexOf("?"); index > 0 && (pathStr = pathStr.substring(0, index)); var reg = /(\/|\\)([^\/\\]+)$/g; var result = reg.exec(pathStr.replace(/(\/|\\)$/, "")); if (!result) return pathStr; var baseName = result[2]; if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase()) return baseName.substring(0, baseName.length - extname.length); return baseName; }, dirname: function dirname(pathStr) { var temp = DIRNAME_RE.exec(pathStr); return temp ? temp[2] : ""; }, changeExtname: function changeExtname(pathStr, extname) { extname = extname || ""; var index = pathStr.indexOf("?"); var tempStr = ""; if (index > 0) { tempStr = pathStr.substring(index); pathStr = pathStr.substring(0, index); } index = pathStr.lastIndexOf("."); if (index < 0) return pathStr + extname + tempStr; return pathStr.substring(0, index) + extname + tempStr; }, changeBasename: function changeBasename(pathStr, basename, isSameExt) { if (0 === basename.indexOf(".")) return this.changeExtname(pathStr, basename); var index = pathStr.indexOf("?"); var tempStr = ""; var ext = isSameExt ? this.extname(pathStr) : ""; if (index > 0) { tempStr = pathStr.substring(index); pathStr = pathStr.substring(0, index); } index = pathStr.lastIndexOf("/"); index = index <= 0 ? 0 : index + 1; return pathStr.substring(0, index) + basename + ext + tempStr; }, _normalize: function _normalize(url) { var oldUrl = url = String(url); do { oldUrl = url; url = url.replace(NORMALIZE_RE, ""); } while (oldUrl.length !== url.length); return url; }, sep: cc.sys.os === cc.sys.OS_WINDOWS ? "\\" : "/", stripSep: function stripSep(path) { return path.replace(/[\/\\]$/, ""); } }; module.exports = cc.path; }), { "../platform/CCSys": 138 } ], 208: [ (function(require, module, exports) { "use strict"; var AffineTransform = function AffineTransform(a, b, c, d, tx, ty) { this.a = a; this.b = b; this.c = c; this.d = d; this.tx = tx; this.ty = ty; }; AffineTransform.create = function(a, b, c, d, tx, ty) { return { a: a, b: b, c: c, d: d, tx: tx, ty: ty }; }; AffineTransform.identity = function() { return { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 }; }; AffineTransform.clone = function(t) { return { a: t.a, b: t.b, c: t.c, d: t.d, tx: t.tx, ty: t.ty }; }; AffineTransform.concat = function(out, t1, t2) { var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty; out.a = a * t2.a + b * t2.c; out.b = a * t2.b + b * t2.d; out.c = c * t2.a + d * t2.c; out.d = c * t2.b + d * t2.d; out.tx = tx * t2.a + ty * t2.c + t2.tx; out.ty = tx * t2.b + ty * t2.d + t2.ty; return out; }; AffineTransform.invert = function(out, t) { var a = t.a, b = t.b, c = t.c, d = t.d; var determinant = 1 / (a * d - b * c); var tx = t.tx, ty = t.ty; out.a = determinant * d; out.b = -determinant * b; out.c = -determinant * c; out.d = determinant * a; out.tx = determinant * (c * ty - d * tx); out.ty = determinant * (b * tx - a * ty); return out; }; AffineTransform.fromMat4 = function(out, mat) { var matm = mat.m; out.a = matm[0]; out.b = matm[1]; out.c = matm[4]; out.d = matm[5]; out.tx = matm[12]; out.ty = matm[13]; return out; }; AffineTransform.transformVec2 = function(out, point, transOrY, t) { var x, y; if (void 0 === t) { t = transOrY; x = point.x; y = point.y; } else { x = point; y = transOrY; } out.x = t.a * x + t.c * y + t.tx; out.y = t.b * x + t.d * y + t.ty; return out; }; AffineTransform.transformSize = function(out, size, t) { out.width = t.a * size.width + t.c * size.height; out.height = t.b * size.width + t.d * size.height; return out; }; AffineTransform.transformRect = function(out, rect, t) { var ol = rect.x; var ob = rect.y; var or = ol + rect.width; var ot = ob + rect.height; var lbx = t.a * ol + t.c * ob + t.tx; var lby = t.b * ol + t.d * ob + t.ty; var rbx = t.a * or + t.c * ob + t.tx; var rby = t.b * or + t.d * ob + t.ty; var ltx = t.a * ol + t.c * ot + t.tx; var lty = t.b * ol + t.d * ot + t.ty; var rtx = t.a * or + t.c * ot + t.tx; var rty = t.b * or + t.d * ot + t.ty; var minX = Math.min(lbx, rbx, ltx, rtx); var maxX = Math.max(lbx, rbx, ltx, rtx); var minY = Math.min(lby, rby, lty, rty); var maxY = Math.max(lby, rby, lty, rty); out.x = minX; out.y = minY; out.width = maxX - minX; out.height = maxY - minY; return out; }; AffineTransform.transformObb = function(out_bl, out_tl, out_tr, out_br, rect, anAffineTransform) { var x = rect.x; var y = rect.y; var width = rect.width; var height = rect.height; var tx = anAffineTransform.a * x + anAffineTransform.c * y + anAffineTransform.tx; var ty = anAffineTransform.b * x + anAffineTransform.d * y + anAffineTransform.ty; var xa = anAffineTransform.a * width; var xb = anAffineTransform.b * width; var yc = anAffineTransform.c * height; var yd = anAffineTransform.d * height; out_tl.x = tx; out_tl.y = ty; out_tr.x = xa + tx; out_tr.y = xb + ty; out_bl.x = yc + tx; out_bl.y = yd + ty; out_br.x = xa + yc + tx; out_br.y = xb + yd + ty; }; cc.AffineTransform = module.exports = AffineTransform; }), {} ], 209: [ (function(require, module, exports) { "use strict"; var Flags = require("../platform/CCObject").Flags; var misc = require("./misc"); var js = require("../platform/js"); var IdGenerater = require("../platform/id-generater"); var eventManager = require("../event-manager"); var RenderFlow = require("../renderer/render-flow"); var Destroying = Flags.Destroying; var DontDestroy = Flags.DontDestroy; var Deactivating = Flags.Deactivating; var CHILD_ADDED = "child-added"; var CHILD_REMOVED = "child-removed"; var idGenerater = new IdGenerater("Node"); function getConstructor(typeOrClassName) { if (!typeOrClassName) { cc.errorID(3804); return null; } if ("string" === typeof typeOrClassName) return js.getClassByName(typeOrClassName); return typeOrClassName; } function findComponent(node, constructor) { if (constructor._sealed) for (var i = 0; i < node._components.length; ++i) { var comp = node._components[i]; if (comp.constructor === constructor) return comp; } else for (var _i = 0; _i < node._components.length; ++_i) { var _comp = node._components[_i]; if (_comp instanceof constructor) return _comp; } return null; } function findComponents(node, constructor, components) { if (constructor._sealed) for (var i = 0; i < node._components.length; ++i) { var comp = node._components[i]; comp.constructor === constructor && components.push(comp); } else for (var _i2 = 0; _i2 < node._components.length; ++_i2) { var _comp2 = node._components[_i2]; _comp2 instanceof constructor && components.push(_comp2); } } function findChildComponent(children, constructor) { for (var i = 0; i < children.length; ++i) { var node = children[i]; var comp = findComponent(node, constructor); if (comp) return comp; if (node._children.length > 0) { comp = findChildComponent(node._children, constructor); if (comp) return comp; } } return null; } function findChildComponents(children, constructor, components) { for (var i = 0; i < children.length; ++i) { var node = children[i]; findComponents(node, constructor, components); node._children.length > 0 && findChildComponents(node._children, constructor, components); } } var BaseNode = cc.Class({ name: "cc._BaseNode", extends: cc.Object, properties: { _parent: null, _children: [], _active: true, _components: [], _prefab: null, _persistNode: { get: function get() { return (this._objFlags & DontDestroy) > 0; }, set: function set(value) { value ? this._objFlags |= DontDestroy : this._objFlags &= ~DontDestroy; } }, name: { get: function get() { return this._name; }, set: function set(value) { false; this._name = value; false; } }, uuid: { get: function get() { return this._id; } }, children: { get: function get() { return this._children; } }, childrenCount: { get: function get() { return this._children.length; } }, active: { get: function get() { return this._active; }, set: function set(value) { value = !!value; if (this._active !== value) { this._active = value; var parent = this._parent; if (parent) { var couldActiveInScene = parent._activeInHierarchy; couldActiveInScene && cc.director._nodeActivator.activateNode(this, value); } } } }, activeInHierarchy: { get: function get() { return this._activeInHierarchy; } } }, ctor: function ctor(name) { this._name = void 0 !== name ? name : "New Node"; this._activeInHierarchy = false; this._id = idGenerater.getNewId(); cc.director._scheduler && cc.director._scheduler.enableForTarget(this); this.__eventTargets = []; }, getParent: function getParent() { return this._parent; }, setParent: function setParent(value) { if (this._parent === value) return; false; var oldParent = this._parent; (true, oldParent) && oldParent._objFlags & Deactivating && cc.errorID(3821); this._parent = value || null; this._onSetParent(value); if (value) { (true, value._objFlags & Deactivating) && cc.errorID(3821); eventManager._setDirtyForNode(this); value._children.push(this); value.emit && value.emit(CHILD_ADDED, this); value._renderFlag |= RenderFlow.FLAG_CHILDREN; } if (oldParent) { if (!(oldParent._objFlags & Destroying)) { var removeAt = oldParent._children.indexOf(this); false; oldParent._children.splice(removeAt, 1); oldParent.emit && oldParent.emit(CHILD_REMOVED, this); this._onHierarchyChanged(oldParent); 0 === oldParent._children.length && (oldParent._renderFlag &= ~RenderFlow.FLAG_CHILDREN); } } else value && this._onHierarchyChanged(null); }, attr: function attr(attrs) { js.mixin(this, attrs); }, getChildByUuid: function getChildByUuid(uuid) { if (!uuid) { cc.log("Invalid uuid"); return null; } var locChildren = this._children; for (var i = 0, len = locChildren.length; i < len; i++) if (locChildren[i]._id === uuid) return locChildren[i]; return null; }, getChildByName: function getChildByName(name) { if (!name) { cc.log("Invalid name"); return null; } var locChildren = this._children; for (var i = 0, len = locChildren.length; i < len; i++) if (locChildren[i]._name === name) return locChildren[i]; return null; }, addChild: function addChild(child) { false; cc.assertID(child, 1606); cc.assertID(null === child._parent, 1605); child.setParent(this); }, insertChild: function insertChild(child, siblingIndex) { child.parent = this; child.setSiblingIndex(siblingIndex); }, getSiblingIndex: function getSiblingIndex() { return this._parent ? this._parent._children.indexOf(this) : 0; }, setSiblingIndex: function setSiblingIndex(index) { if (!this._parent) return; if (this._parent._objFlags & Deactivating) { cc.errorID(3821); return; } var siblings = this._parent._children; index = -1 !== index ? index : siblings.length - 1; var oldIndex = siblings.indexOf(this); if (index !== oldIndex) { siblings.splice(oldIndex, 1); index < siblings.length ? siblings.splice(index, 0, this) : siblings.push(this); this._onSiblingIndexChanged && this._onSiblingIndexChanged(index); } }, walk: function walk(prefunc, postfunc) { var BaseNode = cc._BaseNode; var index = 1; var children, child, curr, i, afterChildren; var stack = BaseNode._stacks[BaseNode._stackId]; if (!stack) { stack = []; BaseNode._stacks.push(stack); } BaseNode._stackId++; stack.length = 0; stack[0] = this; var parent = null; afterChildren = false; while (index) { index--; curr = stack[index]; if (!curr) continue; !afterChildren && prefunc ? prefunc(curr) : afterChildren && postfunc && postfunc(curr); stack[index] = null; if (!afterChildren) { if (curr._children.length > 0) { parent = curr; children = curr._children; i = 0; stack[index] = children[i]; index++; } else { stack[index] = curr; index++; afterChildren = true; } continue; } if (parent === this._parent) break; afterChildren = false; if (children) { i++; if (children[i]) { stack[index] = children[i]; index++; } else if (parent) { stack[index] = parent; index++; afterChildren = true; if (parent._parent) { children = parent._parent._children; i = children.indexOf(parent); parent = parent._parent; } else { parent = null; children = null; } if (i < 0) break; } } } stack.length = 0; BaseNode._stackId--; }, cleanup: function cleanup() {}, removeFromParent: function removeFromParent(cleanup) { if (this._parent) { void 0 === cleanup && (cleanup = true); this._parent.removeChild(this, cleanup); } }, removeChild: function removeChild(child, cleanup) { if (this._children.indexOf(child) > -1) { (cleanup || void 0 === cleanup) && child.cleanup(); child.parent = null; } }, removeAllChildren: function removeAllChildren(cleanup) { var children = this._children; void 0 === cleanup && (cleanup = true); for (var i = children.length - 1; i >= 0; i--) { var node = children[i]; if (node) { cleanup && node.cleanup(); node.parent = null; } } this._children.length = 0; }, isChildOf: function isChildOf(parent) { var child = this; do { if (child === parent) return true; child = child._parent; } while (child); return false; }, getComponent: function getComponent(typeOrClassName) { var constructor = getConstructor(typeOrClassName); if (constructor) return findComponent(this, constructor); return null; }, getComponents: function getComponents(typeOrClassName) { var constructor = getConstructor(typeOrClassName), components = []; constructor && findComponents(this, constructor, components); return components; }, getComponentInChildren: function getComponentInChildren(typeOrClassName) { var constructor = getConstructor(typeOrClassName); if (constructor) return findChildComponent(this._children, constructor); return null; }, getComponentsInChildren: function getComponentsInChildren(typeOrClassName) { var constructor = getConstructor(typeOrClassName), components = []; if (constructor) { findComponents(this, constructor, components); findChildComponents(this._children, constructor, components); } return components; }, _checkMultipleComp: (false, false) && function(ctor) { var existing = this.getComponent(ctor._disallowMultiple); if (existing) { existing.constructor === ctor ? cc.errorID(3805, js.getClassName(ctor), this._name) : cc.errorID(3806, js.getClassName(ctor), this._name, js.getClassName(existing)); return false; } return true; }, addComponent: function addComponent(typeOrClassName) { false; var constructor; if ("string" === typeof typeOrClassName) { constructor = js.getClassByName(typeOrClassName); if (!constructor) { cc.errorID(3807, typeOrClassName); cc._RFpeek() && cc.errorID(3808, typeOrClassName); return null; } } else { if (!typeOrClassName) { cc.errorID(3804); return null; } constructor = typeOrClassName; } if ("function" !== typeof constructor) { cc.errorID(3809); return null; } if (!js.isChildClassOf(constructor, cc.Component)) { cc.errorID(3810); return null; } if ((false, false) && constructor._disallowMultiple && !this._checkMultipleComp(constructor)) return null; var ReqComp = constructor._requireComponent; if (ReqComp && !this.getComponent(ReqComp)) { var depended = this.addComponent(ReqComp); if (!depended) return null; } var component = new constructor(); component.node = this; this._components.push(component); (false, false) && cc.engine && this._id in cc.engine.attachedObjsForEditor && (cc.engine.attachedObjsForEditor[component._id] = component); this._activeInHierarchy && cc.director._nodeActivator.activateComp(component); return component; }, _addComponentAt: false, removeComponent: function removeComponent(component) { if (!component) { cc.errorID(3813); return; } component instanceof cc.Component || (component = this.getComponent(component)); component && component.destroy(); }, _getDependComponent: false, _removeComponent: function _removeComponent(component) { if (!component) { cc.errorID(3814); return; } if (!(this._objFlags & Destroying)) { var i = this._components.indexOf(component); if (-1 !== i) { this._components.splice(i, 1); (false, false) && cc.engine && delete cc.engine.attachedObjsForEditor[component._id]; } else component.node !== this && cc.errorID(3815); } }, destroy: function destroy() { cc.Object.prototype.destroy.call(this) && (this.active = false); }, destroyAllChildren: function destroyAllChildren() { var children = this._children; for (var i = 0; i < children.length; ++i) children[i].destroy(); }, _onSetParent: function _onSetParent(value) {}, _onPostActivated: function _onPostActivated() {}, _onBatchCreated: function _onBatchCreated(dontSyncChildPrefab) {}, _onHierarchyChanged: function _onHierarchyChanged(oldParent) { var newParent = this._parent; if (this._persistNode && !(newParent instanceof cc.Scene)) { cc.game.removePersistRootNode(this); false; } var scene; var inCurrentSceneBefore; var inCurrentSceneNow; var newPrefabRoot; var myPrefabInfo; var PrefabUtils; false, false; var shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy); this._activeInHierarchy !== shouldActiveNow && cc.director._nodeActivator.activateNode(this, shouldActiveNow); }, _instantiate: function _instantiate(cloned, isSyncedNode) { cloned || (cloned = cc.instantiate._clone(this, this)); var newPrefabInfo = cloned._prefab; var PrefabUtils; false; var syncing; false; cloned._parent = null; cloned._onBatchCreated(isSyncedNode); return cloned; }, _registerIfAttached: (false, false) && function(register) { var attachedObjsForEditor = cc.engine.attachedObjsForEditor; if (register) { attachedObjsForEditor[this._id] = this; for (var i = 0; i < this._components.length; i++) { var comp = this._components[i]; attachedObjsForEditor[comp._id] = comp; } cc.engine.emit("node-attach-to-scene", this); } else { cc.engine.emit("node-detach-from-scene", this); delete attachedObjsForEditor[this._id]; for (var _i3 = 0; _i3 < this._components.length; _i3++) { var _comp3 = this._components[_i3]; delete attachedObjsForEditor[_comp3._id]; } } var children = this._children; for (var _i4 = 0, len = children.length; _i4 < len; ++_i4) { var child = children[_i4]; child._registerIfAttached(register); } }, _onPreDestroy: function _onPreDestroy() { var i, len; this._objFlags |= Destroying; var parent = this._parent; var destroyByParent = parent && parent._objFlags & Destroying; !destroyByParent && (false, false) && this._registerIfAttached(false); var children = this._children; for (i = 0, len = children.length; i < len; ++i) children[i]._destroyImmediate(); for (i = 0, len = this._components.length; i < len; ++i) { var component = this._components[i]; component._destroyImmediate(); } var eventTargets = this.__eventTargets; for (i = 0, len = eventTargets.length; i < len; ++i) { var target = eventTargets[i]; target && target.targetOff(this); } eventTargets.length = 0; this._persistNode && cc.game.removePersistRootNode(this); if (!destroyByParent && parent) { var childIndex = parent._children.indexOf(this); parent._children.splice(childIndex, 1); parent.emit && parent.emit("child-removed", this); } return destroyByParent; }, onRestore: false }); BaseNode.idGenerater = idGenerater; BaseNode._stacks = [ [] ]; BaseNode._stackId = 0; BaseNode.prototype._onPreDestroyBase = BaseNode.prototype._onPreDestroy; false; BaseNode.prototype._onHierarchyChangedBase = BaseNode.prototype._onHierarchyChanged; false; var SameNameGetSets = [ "parent", "name", "children", "childrenCount" ]; misc.propertyDefine(BaseNode, SameNameGetSets, {}); false; cc._BaseNode = module.exports = BaseNode; }), { "../event-manager": 117, "../platform/CCObject": 135, "../platform/id-generater": 146, "../platform/js": 150, "../renderer/render-flow": 161, "./misc": 217 } ], 210: [ (function(require, module, exports) { "use strict"; var EPSILON = 1e-6; function binarySearchEpsilon(array, value) { for (var l = 0, h = array.length - 1, m = h >>> 1; l <= h; m = l + h >>> 1) { var test = array[m]; if (test > value + EPSILON) h = m - 1; else { if (!(test < value - EPSILON)) return m; l = m + 1; } } return ~l; } module.exports = { binarySearchEpsilon: binarySearchEpsilon }; }), {} ], 211: [ (function(require, module, exports) { "use strict"; var RenderComponent = require("../components/CCRenderComponent"); var BlendFactor = require("../platform/CCMacro").BlendFactor; var gfx = require("../../renderer/gfx"); var BlendFunc = cc.Class({ properties: { _srcBlendFactor: BlendFactor.SRC_ALPHA, _dstBlendFactor: BlendFactor.ONE_MINUS_SRC_ALPHA, srcBlendFactor: { get: function get() { return this._srcBlendFactor; }, set: function set(value) { if (this._srcBlendFactor === value) return; this._srcBlendFactor = value; this._updateBlendFunc(true); this._onBlendChanged && this._onBlendChanged(); }, animatable: false, type: BlendFactor, tooltip: false, visible: true }, dstBlendFactor: { get: function get() { return this._dstBlendFactor; }, set: function set(value) { if (this._dstBlendFactor === value) return; this._dstBlendFactor = value; this._updateBlendFunc(true); }, animatable: false, type: BlendFactor, tooltip: false, visible: true } }, setMaterial: function setMaterial(index, material) { var materialVar = RenderComponent.prototype.setMaterial.call(this, index, material); this._srcBlendFactor === BlendFactor.SRC_ALPHA && this._dstBlendFactor === BlendFactor.ONE_MINUS_SRC_ALPHA || this._updateMaterialBlendFunc(materialVar); return materialVar; }, _updateMaterial: function _updateMaterial() { this._updateBlendFunc(); }, _updateBlendFunc: function _updateBlendFunc(force) { if (!force && this._srcBlendFactor === BlendFactor.SRC_ALPHA && this._dstBlendFactor === BlendFactor.ONE_MINUS_SRC_ALPHA) return; var materials = this.getMaterials(); for (var i = 0; i < materials.length; i++) { var material = materials[i]; this._updateMaterialBlendFunc(material); } }, _updateMaterialBlendFunc: function _updateMaterialBlendFunc(material) { material.setBlend(true, gfx.BLEND_FUNC_ADD, this._srcBlendFactor, this._dstBlendFactor, gfx.BLEND_FUNC_ADD, this._srcBlendFactor, this._dstBlendFactor); false; } }); module.exports = cc.BlendFunc = BlendFunc; }), { "../../renderer/gfx": 259, "../components/CCRenderComponent": 100, "../platform/CCMacro": 134 } ], 212: [ (function(require, module, exports) { "use strict"; var Base64Values = require("./misc").BASE64_VALUES; var HexChars = "0123456789abcdef".split(""); var _t = [ "", "", "", "" ]; var UuidTemplate = _t.concat(_t, "-", _t, "-", _t, "-", _t, "-", _t, _t, _t); var Indices = UuidTemplate.map((function(x, i) { return "-" === x ? NaN : i; })).filter(isFinite); module.exports = function(base64) { if (22 !== base64.length) return base64; UuidTemplate[0] = base64[0]; UuidTemplate[1] = base64[1]; for (var i = 2, j = 2; i < 22; i += 2) { var lhs = Base64Values[base64.charCodeAt(i)]; var rhs = Base64Values[base64.charCodeAt(i + 1)]; UuidTemplate[Indices[j++]] = HexChars[lhs >> 2]; UuidTemplate[Indices[j++]] = HexChars[(3 & lhs) << 2 | rhs >> 4]; UuidTemplate[Indices[j++]] = HexChars[15 & rhs]; } return UuidTemplate.join(""); }; false; }), { "./misc": 217 } ], 213: [ (function(require, module, exports) { "use strict"; cc.find = module.exports = function(path, referenceNode) { if (null == path) { cc.errorID(3814); return null; } if (referenceNode) false; else { var scene = cc.director.getScene(); if (!scene) { false; return null; } false; referenceNode = scene; } var match = referenceNode; var startIndex = "/" !== path[0] ? 0 : 1; var nameList = path.split("/"); for (var n = startIndex; n < nameList.length; n++) { var name = nameList[n]; var children = match._children; match = null; for (var t = 0, len = children.length; t < len; ++t) { var subChild = children[t]; if (subChild.name === name) { match = subChild; break; } } if (!match) return null; } return match; }; }), {} ], 214: [ (function(require, module, exports) { "use strict"; var _materialVariant = _interopRequireDefault(require("../assets/material/material-variant")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Material = require("../assets/material/CCMaterial"); var GraySpriteState = cc.Class({ properties: { _normalMaterial: null, normalMaterial: { get: function get() { return this._normalMaterial; }, set: function set(val) { this._normalMaterial = val; this._updateDisabledState && this._updateDisabledState(); }, type: Material, tooltip: false, animatable: false }, _grayMaterial: null, grayMaterial: { get: function get() { return this._grayMaterial; }, set: function set(val) { this._grayMaterial = val; this._updateDisabledState && this._updateDisabledState(); }, type: Material, tooltip: false, animatable: false } }, _switchGrayMaterial: function _switchGrayMaterial(useGrayMaterial, renderComp) { var material; if (useGrayMaterial) { material = this._grayMaterial; material || (material = Material.getBuiltinMaterial("2d-gray-sprite")); material = this._grayMaterial = _materialVariant["default"].create(material, renderComp); } else { material = this._normalMaterial; material || (material = Material.getBuiltinMaterial("2d-sprite", renderComp)); material = this._normalMaterial = _materialVariant["default"].create(material, renderComp); } renderComp.setMaterial(0, material); } }); module.exports = GraySpriteState; }), { "../assets/material/CCMaterial": 76, "../assets/material/material-variant": 83 } ], 215: [ (function(require, module, exports) { "use strict"; var eventRegx = /^(click)(\s)*=|(param)(\s)*=/; var imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/; var HtmlTextParser = function HtmlTextParser() { this._parsedObject = {}; this._specialSymbolArray = []; this._specialSymbolArray.push([ /</g, "<" ]); this._specialSymbolArray.push([ />/g, ">" ]); this._specialSymbolArray.push([ /&/g, "&" ]); this._specialSymbolArray.push([ /"/g, '"' ]); this._specialSymbolArray.push([ /'/g, "'" ]); this._specialSymbolArray.push([ / /g, " " ]); }; HtmlTextParser.prototype = { constructor: HtmlTextParser, parse: function parse(htmlString) { this._resultObjectArray = []; if (!htmlString) return this._resultObjectArray; this._stack = []; var startIndex = 0; var length = htmlString.length; while (startIndex < length) { var tagEndIndex = htmlString.indexOf(">", startIndex); var tagBeginIndex = -1; if (tagEndIndex >= 0) { tagBeginIndex = htmlString.lastIndexOf("<", tagEndIndex); var noTagBegin = tagBeginIndex < startIndex - 1; if (noTagBegin) { tagBeginIndex = htmlString.indexOf("<", tagEndIndex + 1); tagEndIndex = htmlString.indexOf(">", tagBeginIndex + 1); } } if (tagBeginIndex < 0) { this._stack.pop(); this._processResult(htmlString.substring(startIndex)); startIndex = length; } else { var newStr = htmlString.substring(startIndex, tagBeginIndex); var tagStr = htmlString.substring(tagBeginIndex + 1, tagEndIndex); "" === tagStr && (newStr = htmlString.substring(startIndex, tagEndIndex + 1)); this._processResult(newStr); -1 === tagEndIndex ? tagEndIndex = tagBeginIndex : "/" === htmlString.charAt(tagBeginIndex + 1) ? this._stack.pop() : this._addToStack(tagStr); startIndex = tagEndIndex + 1; } } return this._resultObjectArray; }, _attributeToObject: function _attributeToObject(attribute) { attribute = attribute.trim(); var obj = {}; var header = attribute.match(/^(color|size)(\s)*=/); var tagName; var nextSpace; var eventObj; var eventHanlderString; if (header) { tagName = header[0]; attribute = attribute.substring(tagName.length).trim(); if ("" === attribute) return obj; nextSpace = attribute.indexOf(" "); switch (tagName[0]) { case "c": obj.color = nextSpace > -1 ? attribute.substring(0, nextSpace).trim() : attribute; break; case "s": obj.size = parseInt(attribute); } if (nextSpace > -1) { eventHanlderString = attribute.substring(nextSpace + 1).trim(); eventObj = this._processEventHandler(eventHanlderString); obj.event = eventObj; } return obj; } header = attribute.match(/^(br(\s)*\/)/); if (header && header[0].length > 0) { tagName = header[0].trim(); if (tagName.startsWith("br") && "/" === tagName[tagName.length - 1]) { obj.isNewLine = true; this._resultObjectArray.push({ text: "", style: { newline: true } }); return obj; } } header = attribute.match(/^(img(\s)*src(\s)*=[^>]+\/)/); if (header && header[0].length > 0) { tagName = header[0].trim(); if (tagName.startsWith("img") && "/" === tagName[tagName.length - 1]) { header = attribute.match(imageAttrReg); var tagValue; var remainingArgument; var isValidImageTag = false; while (header) { attribute = attribute.substring(attribute.indexOf(header[0])); tagName = attribute.substr(0, header[0].length); remainingArgument = attribute.substring(tagName.length).trim(); nextSpace = remainingArgument.indexOf(" "); tagValue = nextSpace > -1 ? remainingArgument.substr(0, nextSpace) : remainingArgument; tagName = tagName.replace(/[^a-zA-Z]/g, "").trim(); tagName = tagName.toLocaleLowerCase(); attribute = remainingArgument.substring(nextSpace).trim(); tagValue.endsWith("/") && (tagValue = tagValue.slice(0, -1)); if ("src" === tagName) { switch (tagValue.charCodeAt(0)) { case 34: case 39: isValidImageTag = true; tagValue = tagValue.slice(1, -1); } obj.isImage = true; obj.src = tagValue; } else if ("height" === tagName) obj.imageHeight = parseInt(tagValue); else if ("width" === tagName) obj.imageWidth = parseInt(tagValue); else if ("align" === tagName) { switch (tagValue.charCodeAt(0)) { case 34: case 39: tagValue = tagValue.slice(1, -1); } obj.imageAlign = tagValue.toLocaleLowerCase(); } else "offset" === tagName ? obj.imageOffset = tagValue : "click" === tagName && (obj.event = this._processEventHandler(tagName + "=" + tagValue)); obj.event && "param" === tagName && (obj.event.param = tagValue.replace(/^\"|\"$/g, "")); header = attribute.match(imageAttrReg); } isValidImageTag && obj.isImage && this._resultObjectArray.push({ text: "", style: obj }); return {}; } } header = attribute.match(/^(outline(\s)*[^>]*)/); if (header) { attribute = header[0].substring("outline".length).trim(); var defaultOutlineObject = { color: "#ffffff", width: 1 }; if (attribute) { var outlineAttrReg = /(\s)*color(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/; header = attribute.match(outlineAttrReg); var tagValue; while (header) { attribute = attribute.substring(attribute.indexOf(header[0])); tagName = attribute.substr(0, header[0].length); remainingArgument = attribute.substring(tagName.length).trim(); nextSpace = remainingArgument.indexOf(" "); tagValue = nextSpace > -1 ? remainingArgument.substr(0, nextSpace) : remainingArgument; tagName = tagName.replace(/[^a-zA-Z]/g, "").trim(); tagName = tagName.toLocaleLowerCase(); attribute = remainingArgument.substring(nextSpace).trim(); "click" === tagName ? obj.event = this._processEventHandler(tagName + "=" + tagValue) : "color" === tagName ? defaultOutlineObject.color = tagValue : "width" === tagName && (defaultOutlineObject.width = parseInt(tagValue)); obj.event && "param" === tagName && (obj.event.param = tagValue.replace(/^\"|\"$/g, "")); header = attribute.match(outlineAttrReg); } } obj.outline = defaultOutlineObject; } header = attribute.match(/^(on|u|b|i)(\s)*/); if (header && header[0].length > 0) { tagName = header[0]; attribute = attribute.substring(tagName.length).trim(); switch (tagName[0]) { case "u": obj.underline = true; break; case "i": obj.italic = true; break; case "b": obj.bold = true; } if ("" === attribute) return obj; eventObj = this._processEventHandler(attribute); obj.event = eventObj; } return obj; }, _processEventHandler: function _processEventHandler(eventString) { var index = 0; var obj = {}; var eventNames = eventString.match(eventRegx); var isValidTag = false; while (eventNames) { var eventName = eventNames[0]; var eventValue = ""; isValidTag = false; eventString = eventString.substring(eventName.length).trim(); if ('"' === eventString.charAt(0)) { index = eventString.indexOf('"', 1); if (index > -1) { eventValue = eventString.substring(1, index).trim(); isValidTag = true; } index++; } else if ("'" === eventString.charAt(0)) { index = eventString.indexOf("'", 1); if (index > -1) { eventValue = eventString.substring(1, index).trim(); isValidTag = true; } index++; } else { var match = eventString.match(/(\S)+/); eventValue = match ? match[0] : ""; index = eventValue.length; } if (isValidTag) { eventName = eventName.substring(0, eventName.length - 1).trim(); obj[eventName] = eventValue; } eventString = eventString.substring(index).trim(); eventNames = eventString.match(eventRegx); } return obj; }, _addToStack: function _addToStack(attribute) { var obj = this._attributeToObject(attribute); if (0 === this._stack.length) this._stack.push(obj); else { if (obj.isNewLine || obj.isImage) return; var previousTagObj = this._stack[this._stack.length - 1]; for (var key in previousTagObj) obj[key] || (obj[key] = previousTagObj[key]); this._stack.push(obj); } }, _processResult: function _processResult(value) { if ("" === value) return; value = this._escapeSpecialSymbol(value); this._stack.length > 0 ? this._resultObjectArray.push({ text: value, style: this._stack[this._stack.length - 1] }) : this._resultObjectArray.push({ text: value }); }, _escapeSpecialSymbol: function _escapeSpecialSymbol(str) { for (var i = 0; i < this._specialSymbolArray.length; ++i) { var key = this._specialSymbolArray[i][0]; var value = this._specialSymbolArray[i][1]; str = str.replace(key, value); } return str; } }; false; module.exports = HtmlTextParser; }), {} ], 216: [ (function(require, module, exports) { "use strict"; require("./CCPath"); true; require("./profiler/CCProfiler"); require("./find"); require("./mutable-forward-iterator"); }), { "./CCPath": 207, "./find": 213, "./mutable-forward-iterator": 218, "./profiler/CCProfiler": 221 } ], 217: [ (function(require, module, exports) { "use strict"; var js = require("../platform/js"); var misc = {}; misc.propertyDefine = function(ctor, sameNameGetSets, diffNameGetSets) { function define(np, propName, getter, setter) { var pd = Object.getOwnPropertyDescriptor(np, propName); if (pd) { pd.get && (np[getter] = pd.get); pd.set && setter && (np[setter] = pd.set); } else { var getterFunc = np[getter]; var clsName; false; js.getset(np, propName, getterFunc, np[setter]); } } var propName, np = ctor.prototype; for (var i = 0; i < sameNameGetSets.length; i++) { propName = sameNameGetSets[i]; var suffix = propName[0].toUpperCase() + propName.slice(1); define(np, propName, "get" + suffix, "set" + suffix); } for (propName in diffNameGetSets) { var getset = diffNameGetSets[propName]; define(np, propName, getset[0], getset[1]); } }; misc.NextPOT = function(x) { x -= 1; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; }; false; misc.BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/; var BASE64_KEYS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var BASE64_VALUES = new Array(123); for (var i = 0; i < 123; ++i) BASE64_VALUES[i] = 64; for (var _i = 0; _i < 64; ++_i) BASE64_VALUES[BASE64_KEYS.charCodeAt(_i)] = _i; misc.BASE64_VALUES = BASE64_VALUES; misc.pushToMap = function(map, key, value, pushFront) { var exists = map[key]; if (exists) if (Array.isArray(exists)) if (pushFront) { exists.push(exists[0]); exists[0] = value; } else exists.push(value); else map[key] = pushFront ? [ value, exists ] : [ exists, value ]; else map[key] = value; }; misc.clampf = function(value, min_inclusive, max_inclusive) { if (min_inclusive > max_inclusive) { var temp = min_inclusive; min_inclusive = max_inclusive; max_inclusive = temp; } return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; }; misc.clamp01 = function(value) { return value < 0 ? 0 : value < 1 ? value : 1; }; misc.lerp = function(a, b, r) { return a + (b - a) * r; }; misc.degreesToRadians = function(angle) { return angle * cc.macro.RAD; }; misc.radiansToDegrees = function(angle) { return angle * cc.macro.DEG; }; cc.misc = module.exports = misc; }), { "../platform/js": 150 } ], 218: [ (function(require, module, exports) { "use strict"; function MutableForwardIterator(array) { this.i = 0; this.array = array; } var proto = MutableForwardIterator.prototype; proto.remove = function(value) { var index = this.array.indexOf(value); index >= 0 && this.removeAt(index); }; proto.removeAt = function(i) { this.array.splice(i, 1); i <= this.i && --this.i; }; proto.fastRemove = function(value) { var index = this.array.indexOf(value); index >= 0 && this.fastRemoveAt(index); }; proto.fastRemoveAt = function(i) { var array = this.array; array[i] = array[array.length - 1]; --array.length; i <= this.i && --this.i; }; proto.push = function(item) { this.array.push(item); }; module.exports = MutableForwardIterator; }), {} ], 219: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var Pool = (function() { function Pool() { this.enabled = false; this.count = 0; this.maxSize = 1024; } var _proto = Pool.prototype; _proto.get = function get() {}; _proto.put = function put() {}; _proto.clear = function clear() {}; return Pool; })(); exports["default"] = Pool; cc.pool = {}; Pool.register = function(name, pool) { cc.pool[name] = pool; }; module.exports = exports["default"]; }), {} ], 220: [ (function(require, module, exports) { "use strict"; cc._PrefabInfo = cc.Class({ name: "cc.PrefabInfo", properties: { root: null, asset: null, fileId: "", sync: false } }); module.exports = { syncWithPrefab: function syncWithPrefab(node) { var _prefab = node._prefab; if (!_prefab.asset) { var NodeUtils; var PrefabUtils; false; cc.errorID(3701, node.name); node._prefab = null; return; } var _objFlags = node._objFlags; var _parent = node._parent; var _id = node._id; var _name = node._name; var _active = node._active; var eulerAnglesX = node._eulerAngles.x; var eulerAnglesY = node._eulerAngles.y; var eulerAnglesZ = node._eulerAngles.z; var _localZOrder = node._localZOrder; var trs = node._trs; var x = trs[0]; var y = trs[1]; var z = trs[2]; cc.game._isCloning = true; var prefabRoot; true; _prefab.asset._doInstantiate(node); cc.game._isCloning = false; node._objFlags = _objFlags; node._parent = _parent; node._id = _id; node._prefab = _prefab; node._name = _name; node._active = _active; node._localZOrder = _localZOrder; trs = node._trs; trs[0] = x; trs[1] = y; trs[2] = z; node._eulerAngles.x = eulerAnglesX; node._eulerAngles.y = eulerAnglesY; node._eulerAngles.z = eulerAnglesZ; } }; }), {} ], 221: [ (function(require, module, exports) { "use strict"; var macro = require("../../platform/CCMacro"); var PerfCounter = require("./perf-counter"); var _showFPS = false; var _fontSize = 15; var _stats = null; var _rootNode = null; var _label = null; function generateStats() { if (_stats) return; _stats = { fps: { desc: "Framerate (FPS)", below: 30, average: 500 }, draws: { desc: "Draw Call" }, frame: { desc: "Frame time (ms)", min: 0, max: 50, average: 500 }, logic: { desc: "Game Logic (ms)", min: 0, max: 50, average: 500, color: "#080" }, render: { desc: "Renderer (ms)", min: 0, max: 50, average: 500, color: "#f90" }, mode: { desc: cc.game.renderType === cc.game.RENDER_TYPE_WEBGL ? "WebGL" : "Canvas", min: 1 } }; var now = performance.now(); for (var id in _stats) _stats[id]._counter = new PerfCounter(id, _stats[id], now); } function generateNode() { if (_rootNode && _rootNode.isValid) return; _rootNode = new cc.Node("PROFILER-NODE"); _rootNode.x = _rootNode.y = 10; _rootNode.groupIndex = cc.Node.BuiltinGroupIndex.DEBUG; cc.Camera._setupDebugCamera(); _rootNode.zIndex = macro.MAX_ZINDEX; cc.game.addPersistRootNode(_rootNode); var left = new cc.Node("LEFT-PANEL"); left.anchorX = left.anchorY = 0; var leftLabel = left.addComponent(cc.Label); leftLabel.fontSize = _fontSize; leftLabel.lineHeight = _fontSize; left.parent = _rootNode; var right = new cc.Node("RIGHT-PANEL"); right.anchorX = 1; right.anchorY = 0; right.x = 200; var rightLabel = right.addComponent(cc.Label); rightLabel.horizontalAlign = cc.Label.HorizontalAlign.RIGHT; rightLabel.fontSize = _fontSize; rightLabel.lineHeight = _fontSize; right.parent = _rootNode; if (cc.sys.platform !== cc.sys.BAIDU_GAME_SUB && cc.sys.platform !== cc.sys.WECHAT_GAME_SUB) { leftLabel.cacheMode = cc.Label.CacheMode.CHAR; rightLabel.cacheMode = cc.Label.CacheMode.CHAR; } _label = { left: leftLabel, right: rightLabel }; } function beforeUpdate() { generateNode(); var now = cc.director._lastUpdate; _stats["frame"]._counter.start(now); _stats["logic"]._counter.start(now); } function afterUpdate() { var now = performance.now(); cc.director.isPaused() ? _stats["frame"]._counter.start(now) : _stats["logic"]._counter.end(now); _stats["render"]._counter.start(now); } function updateLabel(stat) { var length = 20; var desc = stat.desc; var value = stat._counter.human() + ""; stat.label.string = stat.desc + " " + stat._counter.human(); } function afterDraw() { var now = performance.now(); _stats["render"]._counter.end(now); _stats["draws"]._counter.value = cc.renderer.drawCalls; _stats["frame"]._counter.end(now); _stats["fps"]._counter.frame(now); var left = ""; var right = ""; for (var id in _stats) { var stat = _stats[id]; stat._counter.sample(now); left += stat.desc + "\n"; right += stat._counter.human() + "\n"; } if (_label) { _label.left.string = left; _label.right.string = right; } } cc.profiler = module.exports = { isShowingStats: function isShowingStats() { return _showFPS; }, hideStats: function hideStats() { if (_showFPS) { _rootNode && (_rootNode.active = false); cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate); cc.director.off(cc.Director.EVENT_AFTER_UPDATE, afterUpdate); cc.director.off(cc.Director.EVENT_AFTER_DRAW, afterDraw); _showFPS = false; } }, showStats: function showStats() { if (!_showFPS) { generateStats(); _rootNode && (_rootNode.active = true); cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate); cc.director.on(cc.Director.EVENT_AFTER_UPDATE, afterUpdate); cc.director.on(cc.Director.EVENT_AFTER_DRAW, afterDraw); _showFPS = true; } } }; }), { "../../platform/CCMacro": 134, "./perf-counter": 223 } ], 222: [ (function(require, module, exports) { "use strict"; var Counter = cc.Class({ name: "cc.Counter", ctor: function ctor(id, opts, now) { this._id = id; this._opts = opts || {}; this._value = 0; this._total = 0; this._averageValue = 0; this._accumValue = 0; this._accumSamples = 0; this._accumStart = now; }, properties: { value: { get: function get() { return this._value; }, set: function set(v) { this._value = v; } } }, _average: function _average(v, now) { if (this._opts.average) { this._accumValue += v; ++this._accumSamples; var t = now; if (t - this._accumStart >= this._opts.average) { this._averageValue = this._accumValue / this._accumSamples; this._accumValue = 0; this._accumStart = t; this._accumSamples = 0; } } }, sample: function sample(now) { this._average(this._value, now); }, human: function human() { var v = this._opts.average ? this._averageValue : this._value; return Math.round(100 * v) / 100; }, alarm: function alarm() { return this._opts.below && this._value < this._opts.below || this._opts.over && this._value > this._opts.over; } }); module.exports = Counter; }), {} ], 223: [ (function(require, module, exports) { "use strict"; var Counter = require("./counter"); var PerfCounter = cc.Class({ name: "cc.PerfCounter", extends: Counter, ctor: function ctor(id, opts, now) { this._time = now; }, start: function start(now) { this._time = now; }, end: function end(now) { this._value = now - this._time; this._average(this._value); }, tick: function tick() { this.end(); this.start(); }, frame: function frame(now) { var t = now; var e = t - this._time; this._total++; var avg = this._opts.average || 1e3; if (e > avg) { this._value = 1e3 * this._total / e; this._total = 0; this._time = t; this._average(this._value); } } }); module.exports = PerfCounter; }), { "./counter": 222 } ], 224: [ (function(require, module, exports) { "use strict"; var _js = _interopRequireDefault(require("../platform/js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _BASELINE_RATIO = .26; var _BASELINE_OFFSET = 0; false; var MAX_CACHE_SIZE = 100; var pool = new _js["default"].Pool(2); pool.get = function() { var node = this._get() || { key: null, value: null, prev: null, next: null }; return node; }; function LRUCache(size) { this.count = 0; this.limit = size; this.datas = {}; this.head = null; this.tail = null; } LRUCache.prototype.moveToHead = function(node) { node.next = this.head; node.prev = null; null !== this.head && (this.head.prev = node); this.head = node; null === this.tail && (this.tail = node); this.count++; this.datas[node.key] = node; }; LRUCache.prototype.put = function(key, value) { var node = pool.get(); node.key = key; node.value = value; if (this.count >= this.limit) { var discard = this.tail; delete this.datas[discard.key]; this.count--; this.tail = discard.prev; this.tail.next = null; discard.prev = null; discard.next = null; pool.put(discard); } this.moveToHead(node); }; LRUCache.prototype.remove = function(node) { null !== node.prev ? node.prev.next = node.next : this.head = node.next; null !== node.next ? node.next.prev = node.prev : this.tail = node.prev; delete this.datas[node.key]; this.count--; }; LRUCache.prototype.get = function(key) { var node = this.datas[key]; if (node) { this.remove(node); this.moveToHead(node); return node.value; } return null; }; LRUCache.prototype.clear = function() { this.count = 0; this.datas = {}; this.head = null; this.tail = null; }; LRUCache.prototype.has = function(key) { return !!this.datas[key]; }; LRUCache.prototype["delete"] = function(key) { var node = this.datas[key]; this.remove(node); }; var measureCache = new LRUCache(MAX_CACHE_SIZE); var textUtils = { BASELINE_RATIO: _BASELINE_RATIO, MIDDLE_RATIO: (_BASELINE_RATIO + 1) / 2 - _BASELINE_RATIO, BASELINE_OFFSET: _BASELINE_OFFSET, label_wordRex: /([a-zA-Z0-9\xc4\xd6\xdc\xe4\xf6\xfc\xdf\xe9\xe8\xe7\xe0\xf9\xea\xe2\xee\xf4\xfb\u0430-\u044f\u0410-\u042f\u0401\u0451]+|\S)/, label_symbolRex: /^[!,.:;'}\]%\?>\u3001\u2018\u201c\u300b\uff1f\u3002\uff0c\uff01]/, label_lastWordRex: /([a-zA-Z0-9\xc4\xd6\xdc\xe4\xf6\xfc\xdf\xe9\xe8\xe7\xe0\xf9\xea\xe2\xee\xf4\xfb\u0430\xed\xec\xcd\xcc\xef\xc1\xc0\xe1\xe0\xc9\xc8\xd2\xd3\xf2\xf3\u0150\u0151\xd9\xda\u0170\xfa\u0171\xf1\xd1\xe6\xc6\u0153\u0152\xc3\xc2\xe3\xd4\xf5\u011b\u0161\u010d\u0159\u017e\xfd\xe1\xed\xe9\xf3\xfa\u016f\u0165\u010f\u0148\u011a\u0160\u010c\u0158\u017d\xc1\xcd\xc9\xd3\xda\u0164\u017c\u017a\u015b\xf3\u0144\u0142\u0119\u0107\u0105\u017b\u0179\u015a\xd3\u0143\u0141\u0118\u0106\u0104-\u044f\u0410-\u042f\u0401\u0451]+|\S)$/, label_lastEnglish: /[a-zA-Z0-9\xc4\xd6\xdc\xe4\xf6\xfc\xdf\xe9\xe8\xe7\xe0\xf9\xea\xe2\xee\xf4\xfb\u0430\xed\xec\xcd\xcc\xef\xc1\xc0\xe1\xe0\xc9\xc8\xd2\xd3\xf2\xf3\u0150\u0151\xd9\xda\u0170\xfa\u0171\xf1\xd1\xe6\xc6\u0153\u0152\xc3\xc2\xe3\xd4\xf5\u011b\u0161\u010d\u0159\u017e\xfd\xe1\xed\xe9\xf3\xfa\u016f\u0165\u010f\u0148\u011a\u0160\u010c\u0158\u017d\xc1\xcd\xc9\xd3\xda\u0164\u017c\u017a\u015b\xf3\u0144\u0142\u0119\u0107\u0105\u017b\u0179\u015a\xd3\u0143\u0141\u0118\u0106\u0104-\u044f\u0410-\u042f\u0401\u0451]+$/, label_firstEnglish: /^[a-zA-Z0-9\xc4\xd6\xdc\xe4\xf6\xfc\xdf\xe9\xe8\xe7\xe0\xf9\xea\xe2\xee\xf4\xfb\u0430\xed\xec\xcd\xcc\xef\xc1\xc0\xe1\xe0\xc9\xc8\xd2\xd3\xf2\xf3\u0150\u0151\xd9\xda\u0170\xfa\u0171\xf1\xd1\xe6\xc6\u0153\u0152\xc3\xc2\xe3\xd4\xf5\u011b\u0161\u010d\u0159\u017e\xfd\xe1\xed\xe9\xf3\xfa\u016f\u0165\u010f\u0148\u011a\u0160\u010c\u0158\u017d\xc1\xcd\xc9\xd3\xda\u0164\u017c\u017a\u015b\xf3\u0144\u0142\u0119\u0107\u0105\u017b\u0179\u015a\xd3\u0143\u0141\u0118\u0106\u0104-\u044f\u0410-\u042f\u0401\u0451]/, highSurrogateRex: /[\uD800-\uDBFF]/, lowSurrogateRex: /[\uDC00-\uDFFF]/, label_wrapinspection: true, __CHINESE_REG: /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/, __JAPANESE_REG: /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g, __KOREAN_REG: /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/, isUnicodeCJK: function isUnicodeCJK(ch) { return this.__CHINESE_REG.test(ch) || this.__JAPANESE_REG.test(ch) || this.__KOREAN_REG.test(ch); }, isUnicodeSpace: function isUnicodeSpace(ch) { ch = ch.charCodeAt(0); return ch >= 9 && ch <= 13 || 32 === ch || 133 === ch || 160 === ch || 5760 === ch || ch >= 8192 && ch <= 8202 || 8232 === ch || 8233 === ch || 8239 === ch || 8287 === ch || 12288 === ch; }, safeMeasureText: function safeMeasureText(ctx, string, desc) { var font = desc || ctx.font; var key = font + "\ud83c\udfae" + string; var cache = measureCache.get(key); if (null !== cache) return cache; var metric = ctx.measureText(string); var width = metric && metric.width || 0; measureCache.put(key, width); return width; }, _safeSubstring: function _safeSubstring(targetString, startIndex, endIndex) { var newStartIndex = startIndex, newEndIndex = endIndex; var startChar = targetString[startIndex]; this.lowSurrogateRex.test(startChar) && newStartIndex--; if (void 0 !== endIndex) if (endIndex - 1 !== startIndex) { var endChar = targetString[endIndex - 1]; this.highSurrogateRex.test(endChar) && newEndIndex--; } else this.highSurrogateRex.test(startChar) && newEndIndex++; return targetString.substring(newStartIndex, newEndIndex); }, fragmentText: function fragmentText(stringToken, allWidth, maxWidth, measureText) { var wrappedWords = []; if (0 === stringToken.length || maxWidth < 0) { wrappedWords.push(""); return wrappedWords; } var text = stringToken; while (allWidth > maxWidth && text.length > 1) { var fuzzyLen = text.length * (maxWidth / allWidth) | 0; var tmpText = this._safeSubstring(text, fuzzyLen); var width = allWidth - measureText(tmpText); var sLine = tmpText; var pushNum = 0; var checkWhile = 0; var checkCount = 10; while (width > maxWidth && checkWhile++ < checkCount) { fuzzyLen *= maxWidth / width; fuzzyLen |= 0; tmpText = this._safeSubstring(text, fuzzyLen); width = allWidth - measureText(tmpText); } checkWhile = 0; while (width <= maxWidth && checkWhile++ < checkCount) { if (tmpText) { var exec = this.label_wordRex.exec(tmpText); pushNum = exec ? exec[0].length : 1; sLine = tmpText; } fuzzyLen += pushNum; tmpText = this._safeSubstring(text, fuzzyLen); width = allWidth - measureText(tmpText); } fuzzyLen -= pushNum; if (0 === fuzzyLen) { fuzzyLen = 1; sLine = this._safeSubstring(text, 1); } else if (1 === fuzzyLen && this.highSurrogateRex.test(text[0])) { fuzzyLen = 2; sLine = this._safeSubstring(text, 2); } var sText = this._safeSubstring(text, 0, fuzzyLen), result; if (this.label_wrapinspection && this.label_symbolRex.test(sLine || tmpText)) { result = this.label_lastWordRex.exec(sText); fuzzyLen -= result ? result[0].length : 0; 0 === fuzzyLen && (fuzzyLen = 1); sLine = this._safeSubstring(text, fuzzyLen); sText = this._safeSubstring(text, 0, fuzzyLen); } if (this.label_firstEnglish.test(sLine)) { result = this.label_lastEnglish.exec(sText); if (result && sText !== result[0]) { fuzzyLen -= result[0].length; sLine = this._safeSubstring(text, fuzzyLen); sText = this._safeSubstring(text, 0, fuzzyLen); } } if (0 === wrappedWords.length) wrappedWords.push(sText); else { sText = sText.trimLeft(); sText.length > 0 && wrappedWords.push(sText); } text = sLine || tmpText; allWidth = measureText(text); } if (0 === wrappedWords.length) wrappedWords.push(text); else { text = text.trimLeft(); text.length > 0 && wrappedWords.push(text); } return wrappedWords; } }; cc.textUtils = module.exports = textUtils; }), { "../platform/js": 150 } ], 225: [ (function(require, module, exports) { "use strict"; var Texture2D = require("../assets/CCTexture2D"); var textureUtil = { loadImage: function loadImage(url, cb, target) { cc.assertID(url, 3103); var tex = cc.assetManager.assets.get(url); if (tex) { if (tex.loaded) { cb && cb.call(target, null, tex); return tex; } tex.once("load", (function() { cb && cb.call(target, null, tex); }), target); return tex; } cc.assetManager.loadRemote(url, (function(err, texture) { cb && cb.call(target, err, texture); })); }, cacheImage: function cacheImage(url, image) { if (url && image) { var tex = new Texture2D(); tex.initWithElement(image); cc.assetManager.assets.add(url, tex); return tex; } }, postLoadTexture: function postLoadTexture(texture, callback) { if (texture.loaded) { callback && callback(); return; } if (!texture.nativeUrl) { callback && callback(); return; } cc.assetManager.postLoadNative(texture, callback); } }; module.exports = textureUtil; }), { "../assets/CCTexture2D": 72 } ], 226: [ (function(require, module, exports) { "use strict"; var NodeUnit = require("./node-unit"); var NodeMemPool = require("./node-mem-pool"); module.exports = { NodeMemPool: new NodeMemPool(NodeUnit) }; }), { "./node-mem-pool": 228, "./node-unit": 229 } ], 227: [ (function(require, module, exports) { "use strict"; var MemPool = function MemPool(unitClass) { this._unitClass = unitClass; this._pool = []; this._findOrder = []; false; }; var proto = MemPool.prototype; proto._initNative = function() { this._nativeMemPool = new renderer.MemPool(); }; proto._buildUnit = function(unitID) { var unit = new this._unitClass(unitID, this); false; return unit; }; proto._destroyUnit = function(unitID) { this._pool[unitID] = null; for (var idx = 0, n = this._findOrder.length; idx < n; idx++) { var unit = this._findOrder[idx]; if (unit && unit.unitID == unitID) { this._findOrder.splice(idx, 1); break; } } false; }; proto._findUnitID = function() { var unitID = 0; var pool = this._pool; while (pool[unitID]) unitID++; return unitID; }; proto.pop = function() { var findUnit = null; var idx = 0; var findOrder = this._findOrder; var pool = this._pool; for (var n = findOrder.length; idx < n; idx++) { var unit = findOrder[idx]; if (unit && unit.hasSpace()) { findUnit = unit; break; } } if (!findUnit) { var unitID = this._findUnitID(); findUnit = this._buildUnit(unitID); pool[unitID] = findUnit; findOrder.push(findUnit); idx = findOrder.length - 1; } var firstUnit = findOrder[0]; if (firstUnit !== findUnit) { findOrder[0] = findUnit; findOrder[idx] = firstUnit; } return findUnit.pop(); }; proto.push = function(info) { var unit = this._pool[info.unitID]; unit.push(info.index); this._findOrder.length > 1 && unit.isAllFree() && this._destroyUnit(info.unitID); return unit; }; module.exports = MemPool; }), {} ], 228: [ (function(require, module, exports) { "use strict"; var MemPool = require("./mem-pool"); var NodeMemPool = function NodeMemPool(unitClass) { MemPool.call(this, unitClass); }; (function() { var Super = function Super() {}; Super.prototype = MemPool.prototype; NodeMemPool.prototype = new Super(); })(); var proto = NodeMemPool.prototype; proto._initNative = function() { this._nativeMemPool = new renderer.NodeMemPool(); }; proto._destroyUnit = function(unitID) { MemPool.prototype._destroyUnit.call(this, unitID); false; }; module.exports = NodeMemPool; }), { "./mem-pool": 227 } ], 229: [ (function(require, module, exports) { "use strict"; var _utils = require("../../value-types/utils"); var Uint32_Bytes = 4; var Uint8_Bytes = 1; var Dirty_Type = Uint32Array; var Dirty_Members = 1; var Dirty_Stride = Dirty_Members * Uint32_Bytes; var TRS_Members = 10; var TRS_Stride = TRS_Members * _utils.FLOAT_BYTES; var LocalMatrix_Members = 16; var LocalMatrix_Stride = LocalMatrix_Members * _utils.FLOAT_BYTES; var WorldMatrix_Members = 16; var WorldMatrix_Stride = WorldMatrix_Members * _utils.FLOAT_BYTES; var Parent_Type = Uint32Array; var Parent_Members = 2; var Parent_Stride = Parent_Members * Uint32_Bytes; var ZOrder_Type = Uint32Array; var ZOrder_Members = 1; var ZOrder_Stride = ZOrder_Members * Uint32_Bytes; var CullingMask_Type = Int32Array; var CullingMask_Members = 1; var CullingMask_Stride = CullingMask_Members * Uint32_Bytes; var Opacity_Type = Uint8Array; var Opacity_Members = 1; var Opacity_Stride = Opacity_Members * Uint8_Bytes; var Is3D_Type = Uint8Array; var Is3D_Members = 1; var Is3D_Stride = Is3D_Members * Uint8_Bytes; var Node_Type = Uint32Array; var Node_Members = 2; var Skew_Members = 2; var Skew_Stride = Skew_Members * _utils.FLOAT_BYTES; var UnitBase = require("./unit-base"); var NodeUnit = function NodeUnit(unitID, memPool) { UnitBase.call(this, unitID, memPool); var contentNum = this._contentNum; this.trsList = new _utils.FLOAT_ARRAY_TYPE(contentNum * TRS_Members); this.localMatList = new _utils.FLOAT_ARRAY_TYPE(contentNum * LocalMatrix_Members); this.worldMatList = new _utils.FLOAT_ARRAY_TYPE(contentNum * WorldMatrix_Members); false; for (var i = 0; i < contentNum; i++) { var space = this._spacesData[i]; space.trs = new _utils.FLOAT_ARRAY_TYPE(this.trsList.buffer, i * TRS_Stride, TRS_Members); space.localMat = new _utils.FLOAT_ARRAY_TYPE(this.localMatList.buffer, i * LocalMatrix_Stride, LocalMatrix_Members); space.worldMat = new _utils.FLOAT_ARRAY_TYPE(this.worldMatList.buffer, i * WorldMatrix_Stride, WorldMatrix_Members); false; } }; (function() { var Super = function Super() {}; Super.prototype = UnitBase.prototype; NodeUnit.prototype = new Super(); })(); module.exports = NodeUnit; }), { "../../value-types/utils": 239, "./unit-base": 230 } ], 230: [ (function(require, module, exports) { "use strict"; var POINTER_INVALID_FLAG = 65535; var SPACE_FREE_FLAG = 0; var SPACE_USE_FLAG = 1; var POS_NEXT_FREE = 0; var POS_FREE_FLAG = 1; var UnitBase = function UnitBase(unitID, memPool, contentNum) { contentNum = contentNum || 128; this.unitID = unitID; this._memPool = memPool; this._data = new Uint16Array(2); this._data[0] = 0; this._data[1] = 0; this._contentNum = contentNum; this._signData = new Uint16Array(2 * this._contentNum); this._spacesData = []; for (var i = 0; i < contentNum; i++) { var signIndex = 2 * i; this._signData[signIndex + POS_NEXT_FREE] = i + 1; this._signData[signIndex + POS_FREE_FLAG] = SPACE_FREE_FLAG; this._spacesData[i] = { index: i, unitID: unitID }; } this._signData[2 * (contentNum - 1)] = POINTER_INVALID_FLAG; }; var UnitBaseProto = UnitBase.prototype; UnitBaseProto.hasSpace = function() { return this._data[0] !== POINTER_INVALID_FLAG; }; UnitBaseProto.isAllFree = function() { return 0 == this._data[1]; }; UnitBaseProto.pop = function() { var headFreeIndex = this._data[0]; if (headFreeIndex === POINTER_INVALID_FLAG) return null; var index = headFreeIndex; var signIndex = 2 * index; var space = this._spacesData[index]; this._signData[signIndex + POS_FREE_FLAG] = SPACE_USE_FLAG; this._data[0] = this._signData[signIndex + POS_NEXT_FREE]; this._data[1]++; return space; }; UnitBaseProto.push = function(index) { var signIndex = 2 * index; this._signData[signIndex + POS_FREE_FLAG] = SPACE_FREE_FLAG; this._signData[signIndex + POS_NEXT_FREE] = this._data[0]; this._data[0] = index; this._data[1]--; }; UnitBaseProto.dump = function() { var spaceNum = 0; var index = this._data[0]; var freeStr = ""; while (index != POINTER_INVALID_FLAG) { spaceNum++; freeStr += index + "->"; index = this._signData[2 * index + POS_NEXT_FREE]; } var usingNum = 0; var usingStr = ""; var contentNum = this._contentNum; for (var i = 0; i < contentNum; i++) { var freeFlag = this._signData[2 * i + POS_FREE_FLAG]; if (freeFlag == SPACE_USE_FLAG) { usingNum++; usingStr += i + "->"; } } var totalNum = spaceNum + usingNum; console.log("unitID:", this.unitID, "spaceNum:", spaceNum, "calc using num:", usingNum, "store using num:", this._data[1], "calc total num:", totalNum, "actually total num:", this._contentNum); console.log("free info:", freeStr); console.log("using info:", usingStr); usingNum != this._data[1] && cc.error("using num error", "calc using num:", usingNum, "store using num:", this._data[1]); spaceNum + usingNum != this._contentNum && cc.error("total num error", "calc total num:", totalNum, "actually total num:", this._contentNum); }; module.exports = UnitBase; }), {} ], 231: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueType = _interopRequireDefault(require("./value-type")); var _CCClass = _interopRequireDefault(require("../platform/CCClass")); var _misc = _interopRequireDefault(require("../utils/misc")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Color = (function(_ValueType) { _inheritsLoose(Color, _ValueType); Color.copy = function copy(out, a) { out.r = a.r; out.g = a.g; out.b = a.b; out.a = a.a; return out; }; Color.clone = function clone(a) { return new Color(a.r, a.g, a.b, a.a); }; Color.set = function set(out, r, g, b, a) { void 0 === r && (r = 255); void 0 === g && (g = 255); void 0 === b && (b = 255); void 0 === a && (a = 255); out.r = r; out.g = g; out.b = b; out.a = a; return out; }; Color.fromHex = function fromHex(out, hex) { var r = hex >> 24 & 255; var g = hex >> 16 & 255; var b = hex >> 8 & 255; var a = 255 & hex; out.r = r; out.g = g; out.b = b; out.a = a; return out; }; Color.fromHEX = function fromHEX(out, hexString) { hexString = 0 === hexString.indexOf("#") ? hexString.substring(1) : hexString; out.r = parseInt(hexString.substr(0, 2), 16) || 0; out.g = parseInt(hexString.substr(2, 2), 16) || 0; out.b = parseInt(hexString.substr(4, 2), 16) || 0; out.a = parseInt(hexString.substr(6, 2), 16) || 255; out._val = (out.a << 24 >>> 0) + (out.b << 16) + (out.g << 8) + out.r; return out; }; Color.add = function add(out, a, b) { out.r = a.r + b.r; out.g = a.g + b.g; out.b = a.b + b.b; out.a = a.a + b.a; return out; }; Color.subtract = function subtract(out, a, b) { out.r = a.r - b.r; out.g = a.g - b.g; out.b = a.b - b.b; out.a = a.a - b.a; return out; }; Color.multiply = function multiply(out, a, b) { out.r = a.r * b.r; out.g = a.g * b.g; out.b = a.b * b.b; out.a = a.a * b.a; return out; }; Color.divide = function divide(out, a, b) { out.r = a.r / b.r; out.g = a.g / b.g; out.b = a.b / b.b; out.a = a.a / b.a; return out; }; Color.scale = function scale(out, a, b) { out.r = a.r * b; out.g = a.g * b; out.b = a.b * b; out.a = a.a * b; return out; }; Color.lerp = function lerp(out, a, b, t) { var ar = a.r, ag = a.g, ab = a.b, aa = a.a; out.r = ar + t * (b.r - ar); out.g = ag + t * (b.g - ag); out.b = ab + t * (b.b - ab); out.a = aa + t * (b.a - aa); return out; }; Color.toArray = function toArray(out, a, ofs) { void 0 === ofs && (ofs = 0); var scale = a instanceof Color || a.a > 1 ? 1 / 255 : 1; out[ofs + 0] = a.r * scale; out[ofs + 1] = a.g * scale; out[ofs + 2] = a.b * scale; out[ofs + 3] = a.a * scale; return out; }; Color.fromArray = function fromArray(arr, out, ofs) { void 0 === ofs && (ofs = 0); out.r = 255 * arr[ofs + 0]; out.g = 255 * arr[ofs + 1]; out.b = 255 * arr[ofs + 2]; out.a = 255 * arr[ofs + 3]; return out; }; Color.premultiplyAlpha = function premultiplyAlpha(out, color) { var alpha = color.a / 255; out.r = color.r * alpha; out.g = color.g * alpha; out.b = color.b * alpha; out._fastSetA(color.a); return out; }; function Color(r, g, b, a) { var _this; void 0 === r && (r = 0); void 0 === g && (g = 0); void 0 === b && (b = 0); void 0 === a && (a = 255); _this = _ValueType.call(this) || this; _this._val = 0; if ("object" === typeof r) { g = r.g; b = r.b; a = r.a; r = r.r; } _this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (0 | r); return _this; } var _proto = Color.prototype; _proto.clone = function clone() { var ret = new Color(); ret._val = this._val; return ret; }; _proto.equals = function equals(other) { return other && this._val === other._val; }; _proto.lerp = function lerp(to, ratio, out) { out = out || new Color(); var r = this.r; var g = this.g; var b = this.b; var a = this.a; out.r = r + (to.r - r) * ratio; out.g = g + (to.g - g) * ratio; out.b = b + (to.b - b) * ratio; out.a = a + (to.a - a) * ratio; return out; }; _proto.toString = function toString() { return "rgba(" + this.r.toFixed() + ", " + this.g.toFixed() + ", " + this.b.toFixed() + ", " + this.a.toFixed() + ")"; }; _proto.getR = function getR() { return 255 & this._val; }; _proto.setR = function setR(red) { red = ~~_misc["default"].clampf(red, 0, 255); this._val = (4294967040 & this._val | red) >>> 0; return this; }; _proto.getG = function getG() { return (65280 & this._val) >> 8; }; _proto.setG = function setG(green) { green = ~~_misc["default"].clampf(green, 0, 255); this._val = (4294902015 & this._val | green << 8) >>> 0; return this; }; _proto.getB = function getB() { return (16711680 & this._val) >> 16; }; _proto.setB = function setB(blue) { blue = ~~_misc["default"].clampf(blue, 0, 255); this._val = (4278255615 & this._val | blue << 16) >>> 0; return this; }; _proto.getA = function getA() { return (4278190080 & this._val) >>> 24; }; _proto.setA = function setA(alpha) { alpha = ~~_misc["default"].clampf(alpha, 0, 255); this._val = (16777215 & this._val | alpha << 24) >>> 0; return this; }; _proto.toCSS = function toCSS(opt) { return opt && "rgba" !== opt ? "rgb" === opt ? "rgb(" + this.r + "," + this.g + "," + this.b + ")" : "#" + this.toHEX(opt) : "rgba(" + this.r + "," + this.g + "," + this.b + "," + (this.a / 255).toFixed(2) + ")"; }; _proto.fromHEX = function fromHEX(hexString) { hexString = 0 === hexString.indexOf("#") ? hexString.substring(1) : hexString; var r = parseInt(hexString.substr(0, 2), 16) || 0; var g = parseInt(hexString.substr(2, 2), 16) || 0; var b = parseInt(hexString.substr(4, 2), 16) || 0; var a = parseInt(hexString.substr(6, 2), 16) || 255; this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + r; return this; }; _proto.toHEX = function toHEX(fmt) { var prefix = "0"; var hex = [ (this.r < 16 ? prefix : "") + this.r.toString(16), (this.g < 16 ? prefix : "") + this.g.toString(16), (this.b < 16 ? prefix : "") + this.b.toString(16) ]; if ("#rgb" === fmt) { hex[0] = hex[0][0]; hex[1] = hex[1][0]; hex[2] = hex[2][0]; } else "#rrggbbaa" === fmt && hex.push((this.a < 16 ? prefix : "") + this.a.toString(16)); return hex.join(""); }; _proto.toRGBValue = function toRGBValue() { return 16777215 & this._val; }; _proto.fromHSV = function fromHSV(h, s, v) { var r, g, b; if (0 === s) r = g = b = v; else if (0 === v) r = g = b = 0; else { 1 === h && (h = 0); h *= 6; var i = Math.floor(h); var f = h - i; var p = v * (1 - s); var q = v * (1 - s * f); var t = v * (1 - s * (1 - f)); switch (i) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; } } r *= 255; g *= 255; b *= 255; this._val = (this.a << 24 >>> 0) + (b << 16) + (g << 8) + (0 | r); return this; }; _proto.toHSV = function toHSV() { var r = this.r / 255; var g = this.g / 255; var b = this.b / 255; var hsv = { h: 0, s: 0, v: 0 }; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var delta = 0; hsv.v = max; hsv.s = max ? (max - min) / max : 0; if (hsv.s) { delta = max - min; hsv.h = r === max ? (g - b) / delta : g === max ? 2 + (b - r) / delta : 4 + (r - g) / delta; hsv.h /= 6; hsv.h < 0 && (hsv.h += 1); } else hsv.h = 0; return hsv; }; _proto.set = function set(color) { if (color._val) this._val = color._val; else { this.r = color.r; this.g = color.g; this.b = color.b; this.a = color.a; } return this; }; _proto._fastSetA = function _fastSetA(alpha) { this._val = (16777215 & this._val | alpha << 24) >>> 0; }; _proto.multiply = function multiply(other) { var r = (255 & this._val) * other.r >> 8; var g = (65280 & this._val) * other.g >> 8; var b = (16711680 & this._val) * other.b >> 8; var a = ((4278190080 & this._val) >>> 8) * other.a; this._val = 4278190080 & a | 16711680 & b | 65280 & g | 255 & r; return this; }; _createClass(Color, [ { key: "r", get: function get() { return this.getR(); }, set: function set(v) { this.setR(v); } }, { key: "g", get: function get() { return this.getG(); }, set: function set(v) { this.setG(v); } }, { key: "b", get: function get() { return this.getB(); }, set: function set(v) { this.setB(v); } }, { key: "a", get: function get() { return this.getA(); }, set: function set(v) { this.setA(v); } } ], [ { key: "WHITE", get: function get() { return new Color(255, 255, 255, 255); } }, { key: "BLACK", get: function get() { return new Color(0, 0, 0, 255); } }, { key: "TRANSPARENT", get: function get() { return new Color(0, 0, 0, 0); } }, { key: "GRAY", get: function get() { return new Color(127.5, 127.5, 127.5); } }, { key: "RED", get: function get() { return new Color(255, 0, 0); } }, { key: "GREEN", get: function get() { return new Color(0, 255, 0); } }, { key: "BLUE", get: function get() { return new Color(0, 0, 255); } }, { key: "YELLOW", get: function get() { return new Color(255, 235, 4); } }, { key: "ORANGE", get: function get() { return new Color(255, 127, 0); } }, { key: "CYAN", get: function get() { return new Color(0, 255, 255); } }, { key: "MAGENTA", get: function get() { return new Color(255, 0, 255); } } ]); return Color; })(_valueType["default"]); exports["default"] = Color; Color.div = Color.divide; Color.sub = Color.subtract; Color.mul = Color.multiply; Color.WHITE_R = Color.WHITE; Color.BLACK_R = Color.BLACK; Color.TRANSPARENT_R = Color.TRANSPARENT; Color.GRAY_R = Color.GRAY; Color.RED_R = Color.RED; Color.GREEN_R = Color.GREEN; Color.BLUE_R = Color.BLUE; Color.YELLOW_R = Color.YELLOW; Color.ORANGE_R = Color.ORANGE; Color.CYAN_R = Color.CYAN; Color.MAGENTA_R = Color.MAGENTA; _CCClass["default"].fastDefine("cc.Color", Color, { r: 0, g: 0, b: 0, a: 255 }); cc.Color = Color; cc.color = function color(r, g, b, a) { if ("string" === typeof r) { var result = new Color(); return result.fromHEX(r); } if ("object" === typeof r) return new Color(r.r, r.g, r.b, r.a); return new Color(r, g, b, a); }; module.exports = exports["default"]; }), { "../platform/CCClass": 129, "../utils/misc": 217, "./value-type": 240 } ], 232: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; var _exportNames = { Vec2: true, Vec3: true, Vec4: true, Mat4: true, Mat3: true, Rect: true, Size: true, Color: true, Quat: true, Trs: true }; exports.Vec4 = exports.Vec3 = exports.Vec2 = exports.Trs = exports.Size = exports.Rect = exports.Quat = exports.Mat4 = exports.Mat3 = exports.Color = void 0; var _vec = _interopRequireDefault(require("./vec2")); exports.Vec2 = _vec["default"]; var _vec2 = _interopRequireDefault(require("./vec3")); exports.Vec3 = _vec2["default"]; var _vec3 = _interopRequireDefault(require("./vec4")); exports.Vec4 = _vec3["default"]; var _mat = _interopRequireDefault(require("./mat4")); exports.Mat4 = _mat["default"]; var _mat2 = _interopRequireDefault(require("./mat3")); exports.Mat3 = _mat2["default"]; var _rect = _interopRequireDefault(require("./rect")); exports.Rect = _rect["default"]; var _size = _interopRequireDefault(require("./size")); exports.Size = _size["default"]; var _color = _interopRequireDefault(require("./color")); exports.Color = _color["default"]; var _quat = _interopRequireDefault(require("./quat")); exports.Quat = _quat["default"]; var _trs = _interopRequireDefault(require("./trs")); exports.Trs = _trs["default"]; var _utils = require("./utils"); Object.keys(_utils).forEach((function(key) { if ("default" === key || "__esModule" === key) return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === _utils[key]) return; exports[key] = _utils[key]; })); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } cc.math = module.exports; }), { "./color": 231, "./mat3": 233, "./mat4": 234, "./quat": 235, "./rect": 236, "./size": 237, "./trs": 238, "./utils": 239, "./vec2": 241, "./vec3": 242, "./vec4": 243 } ], 233: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _utils = require("../value-types/utils"); var _vec = _interopRequireDefault(require("./vec3")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Mat3 = (function() { Mat3.create = function create(m00, m01, m02, m03, m04, m05, m06, m07, m08) { void 0 === m00 && (m00 = 1); void 0 === m01 && (m01 = 0); void 0 === m02 && (m02 = 0); void 0 === m03 && (m03 = 0); void 0 === m04 && (m04 = 1); void 0 === m05 && (m05 = 0); void 0 === m06 && (m06 = 0); void 0 === m07 && (m07 = 0); void 0 === m08 && (m08 = 1); return new Mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08); }; Mat3.clone = function clone(a) { var am = a.m; return new Mat3(am[0], am[1], am[2], am[3], am[4], am[5], am[6], am[7], am[8]); }; Mat3.copy = function copy(out, a) { out.m.set(a.m); return out; }; Mat3.set = function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { var outm = out.m; outm[0] = m00; outm[1] = m01; outm[2] = m02; outm[3] = m10; outm[4] = m11; outm[5] = m12; outm[6] = m20; outm[7] = m21; outm[8] = m22; return out; }; Mat3.identity = function identity(out) { var outm = out.m; outm[0] = 1; outm[1] = 0; outm[2] = 0; outm[3] = 0; outm[4] = 1; outm[5] = 0; outm[6] = 0; outm[7] = 0; outm[8] = 1; return out; }; Mat3.transpose = function transpose(out, a) { var am = a.m, outm = out.m; if (out === a) { var a01 = am[1], a02 = am[2], a12 = am[5]; outm[1] = am[3]; outm[2] = am[6]; outm[3] = a01; outm[5] = am[7]; outm[6] = a02; outm[7] = a12; } else { outm[0] = am[0]; outm[1] = am[3]; outm[2] = am[6]; outm[3] = am[1]; outm[4] = am[4]; outm[5] = am[7]; outm[6] = am[2]; outm[7] = am[5]; outm[8] = am[8]; } return out; }; Mat3.invert = function invert(out, a) { var am = a.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a10 = am[3], a11 = am[4], a12 = am[5], a20 = am[6], a21 = am[7], a22 = am[8]; var b01 = a22 * a11 - a12 * a21; var b11 = -a22 * a10 + a12 * a20; var b21 = a21 * a10 - a11 * a20; var det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) return out; det = 1 / det; outm[0] = b01 * det; outm[1] = (-a22 * a01 + a02 * a21) * det; outm[2] = (a12 * a01 - a02 * a11) * det; outm[3] = b11 * det; outm[4] = (a22 * a00 - a02 * a20) * det; outm[5] = (-a12 * a00 + a02 * a10) * det; outm[6] = b21 * det; outm[7] = (-a21 * a00 + a01 * a20) * det; outm[8] = (a11 * a00 - a01 * a10) * det; return out; }; Mat3.adjoint = function adjoint(out, a) { var am = a.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a10 = am[3], a11 = am[4], a12 = am[5], a20 = am[6], a21 = am[7], a22 = am[8]; outm[0] = a11 * a22 - a12 * a21; outm[1] = a02 * a21 - a01 * a22; outm[2] = a01 * a12 - a02 * a11; outm[3] = a12 * a20 - a10 * a22; outm[4] = a00 * a22 - a02 * a20; outm[5] = a02 * a10 - a00 * a12; outm[6] = a10 * a21 - a11 * a20; outm[7] = a01 * a20 - a00 * a21; outm[8] = a00 * a11 - a01 * a10; return out; }; Mat3.determinant = function determinant(a) { var am = a.m; var a00 = am[0], a01 = am[1], a02 = am[2], a10 = am[3], a11 = am[4], a12 = am[5], a20 = am[6], a21 = am[7], a22 = am[8]; return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); }; Mat3.multiply = function multiply(out, a, b) { var am = a.m, bm = b.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a10 = am[3], a11 = am[4], a12 = am[5], a20 = am[6], a21 = am[7], a22 = am[8]; var b00 = bm[0], b01 = bm[1], b02 = bm[2]; var b10 = bm[3], b11 = bm[4], b12 = bm[5]; var b20 = bm[6], b21 = bm[7], b22 = bm[8]; outm[0] = b00 * a00 + b01 * a10 + b02 * a20; outm[1] = b00 * a01 + b01 * a11 + b02 * a21; outm[2] = b00 * a02 + b01 * a12 + b02 * a22; outm[3] = b10 * a00 + b11 * a10 + b12 * a20; outm[4] = b10 * a01 + b11 * a11 + b12 * a21; outm[5] = b10 * a02 + b11 * a12 + b12 * a22; outm[6] = b20 * a00 + b21 * a10 + b22 * a20; outm[7] = b20 * a01 + b21 * a11 + b22 * a21; outm[8] = b20 * a02 + b21 * a12 + b22 * a22; return out; }; Mat3.multiplyMat4 = function multiplyMat4(out, a, b) { var am = a.m, bm = b.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a10 = am[3], a11 = am[4], a12 = am[5], a20 = am[6], a21 = am[7], a22 = am[8]; var b00 = bm[0], b01 = bm[1], b02 = bm[2]; var b10 = bm[4], b11 = bm[5], b12 = bm[6]; var b20 = bm[8], b21 = bm[9], b22 = bm[10]; outm[0] = b00 * a00 + b01 * a10 + b02 * a20; outm[1] = b00 * a01 + b01 * a11 + b02 * a21; outm[2] = b00 * a02 + b01 * a12 + b02 * a22; outm[3] = b10 * a00 + b11 * a10 + b12 * a20; outm[4] = b10 * a01 + b11 * a11 + b12 * a21; outm[5] = b10 * a02 + b11 * a12 + b12 * a22; outm[6] = b20 * a00 + b21 * a10 + b22 * a20; outm[7] = b20 * a01 + b21 * a11 + b22 * a21; outm[8] = b20 * a02 + b21 * a12 + b22 * a22; return out; }; Mat3.translate = function translate(out, a, v) { var am = a.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a10 = am[3], a11 = am[4], a12 = am[5], a20 = am[6], a21 = am[7], a22 = am[8]; var x = v.x, y = v.y; outm[0] = a00; outm[1] = a01; outm[2] = a02; outm[3] = a10; outm[4] = a11; outm[5] = a12; outm[6] = x * a00 + y * a10 + a20; outm[7] = x * a01 + y * a11 + a21; outm[8] = x * a02 + y * a12 + a22; return out; }; Mat3.rotate = function rotate(out, a, rad) { var am = a.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a10 = am[3], a11 = am[4], a12 = am[5], a20 = am[6], a21 = am[7], a22 = am[8]; var s = Math.sin(rad); var c = Math.cos(rad); outm[0] = c * a00 + s * a10; outm[1] = c * a01 + s * a11; outm[2] = c * a02 + s * a12; outm[3] = c * a10 - s * a00; outm[4] = c * a11 - s * a01; outm[5] = c * a12 - s * a02; outm[6] = a20; outm[7] = a21; outm[8] = a22; return out; }; Mat3.scale = function scale(out, a, v) { var x = v.x, y = v.y; var am = a.m, outm = out.m; outm[0] = x * am[0]; outm[1] = x * am[1]; outm[2] = x * am[2]; outm[3] = y * am[3]; outm[4] = y * am[4]; outm[5] = y * am[5]; outm[6] = am[6]; outm[7] = am[7]; outm[8] = am[8]; return out; }; Mat3.fromMat4 = function fromMat4(out, a) { var am = a.m, outm = out.m; outm[0] = am[0]; outm[1] = am[1]; outm[2] = am[2]; outm[3] = am[4]; outm[4] = am[5]; outm[5] = am[6]; outm[6] = am[8]; outm[7] = am[9]; outm[8] = am[10]; return out; }; Mat3.fromTranslation = function fromTranslation(out, v) { var outm = out.m; outm[0] = 1; outm[1] = 0; outm[2] = 0; outm[3] = 0; outm[4] = 1; outm[5] = 0; outm[6] = v.x; outm[7] = v.y; outm[8] = 1; return out; }; Mat3.fromRotation = function fromRotation(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); var outm = out.m; outm[0] = c; outm[1] = s; outm[2] = 0; outm[3] = -s; outm[4] = c; outm[5] = 0; outm[6] = 0; outm[7] = 0; outm[8] = 1; return out; }; Mat3.fromScaling = function fromScaling(out, v) { var outm = out.m; outm[0] = v.x; outm[1] = 0; outm[2] = 0; outm[3] = 0; outm[4] = v.y; outm[5] = 0; outm[6] = 0; outm[7] = 0; outm[8] = 1; return out; }; Mat3.fromQuat = function fromQuat(out, q) { var outm = out.m; var x = q.x, y = q.y, z = q.z, w = q.w; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var yx = y * x2; var yy = y * y2; var zx = z * x2; var zy = z * y2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; outm[0] = 1 - yy - zz; outm[3] = yx - wz; outm[6] = zx + wy; outm[1] = yx + wz; outm[4] = 1 - xx - zz; outm[7] = zy - wx; outm[2] = zx - wy; outm[5] = zy + wx; outm[8] = 1 - xx - yy; return out; }; Mat3.fromViewUp = function fromViewUp(out, view, up) { var _fromViewUpIIFE = (function() { var default_up = new _vec["default"](0, 1, 0); var x = new _vec["default"](); var y = new _vec["default"](); return function(out, view, up) { if (_vec["default"].lengthSqr(view) < _utils.EPSILON * _utils.EPSILON) { Mat3.identity(out); return out; } up = up || default_up; _vec["default"].normalize(x, _vec["default"].cross(x, up, view)); if (_vec["default"].lengthSqr(x) < _utils.EPSILON * _utils.EPSILON) { Mat3.identity(out); return out; } _vec["default"].cross(y, view, x); Mat3.set(out, x.x, x.y, x.z, y.x, y.y, y.z, view.x, view.y, view.z); return out; }; })(); return _fromViewUpIIFE(out, view, up); }; Mat3.normalFromMat4 = function normalFromMat4(out, a) { var am = a.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a03 = am[3], a10 = am[4], a11 = am[5], a12 = am[6], a13 = am[7], a20 = am[8], a21 = am[9], a22 = am[10], a23 = am[11], a30 = am[12], a31 = am[13], a32 = am[14], a33 = am[15]; var b00 = a00 * a11 - a01 * a10; var b01 = a00 * a12 - a02 * a10; var b02 = a00 * a13 - a03 * a10; var b03 = a01 * a12 - a02 * a11; var b04 = a01 * a13 - a03 * a11; var b05 = a02 * a13 - a03 * a12; var b06 = a20 * a31 - a21 * a30; var b07 = a20 * a32 - a22 * a30; var b08 = a20 * a33 - a23 * a30; var b09 = a21 * a32 - a22 * a31; var b10 = a21 * a33 - a23 * a31; var b11 = a22 * a33 - a23 * a32; var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) return out; det = 1 / det; outm[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; outm[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; outm[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; outm[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; outm[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; outm[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; outm[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; outm[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; outm[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; return out; }; Mat3.frob = function frob(a) { var am = a.m; return Math.sqrt(Math.pow(am[0], 2) + Math.pow(am[1], 2) + Math.pow(am[2], 2) + Math.pow(am[3], 2) + Math.pow(am[4], 2) + Math.pow(am[5], 2) + Math.pow(am[6], 2) + Math.pow(am[7], 2) + Math.pow(am[8], 2)); }; Mat3.add = function add(out, a, b) { var am = a.m, bm = b.m, outm = out.m; outm[0] = am[0] + bm[0]; outm[1] = am[1] + bm[1]; outm[2] = am[2] + bm[2]; outm[3] = am[3] + bm[3]; outm[4] = am[4] + bm[4]; outm[5] = am[5] + bm[5]; outm[6] = am[6] + bm[6]; outm[7] = am[7] + bm[7]; outm[8] = am[8] + bm[8]; return out; }; Mat3.subtract = function subtract(out, a, b) { var am = a.m, bm = b.m, outm = out.m; outm[0] = am[0] - bm[0]; outm[1] = am[1] - bm[1]; outm[2] = am[2] - bm[2]; outm[3] = am[3] - bm[3]; outm[4] = am[4] - bm[4]; outm[5] = am[5] - bm[5]; outm[6] = am[6] - bm[6]; outm[7] = am[7] - bm[7]; outm[8] = am[8] - bm[8]; return out; }; Mat3.multiplyScalar = function multiplyScalar(out, a, b) { var am = a.m, outm = out.m; outm[0] = am[0] * b; outm[1] = am[1] * b; outm[2] = am[2] * b; outm[3] = am[3] * b; outm[4] = am[4] * b; outm[5] = am[5] * b; outm[6] = am[6] * b; outm[7] = am[7] * b; outm[8] = am[8] * b; return out; }; Mat3.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) { var am = a.m, bm = b.m, outm = out.m; outm[0] = am[0] + bm[0] * scale; outm[1] = am[1] + bm[1] * scale; outm[2] = am[2] + bm[2] * scale; outm[3] = am[3] + bm[3] * scale; outm[4] = am[4] + bm[4] * scale; outm[5] = am[5] + bm[5] * scale; outm[6] = am[6] + bm[6] * scale; outm[7] = am[7] + bm[7] * scale; outm[8] = am[8] + bm[8] * scale; return out; }; Mat3.exactEquals = function exactEquals(a, b) { var am = a.m, bm = b.m; return am[0] === bm[0] && am[1] === bm[1] && am[2] === bm[2] && am[3] === bm[3] && am[4] === bm[4] && am[5] === bm[5] && am[6] === bm[6] && am[7] === bm[7] && am[8] === bm[8]; }; Mat3.equals = function equals(a, b) { var am = a.m, bm = b.m; var a0 = am[0], a1 = am[1], a2 = am[2], a3 = am[3], a4 = am[4], a5 = am[5], a6 = am[6], a7 = am[7], a8 = am[8]; var b0 = bm[0], b1 = bm[1], b2 = bm[2], b3 = bm[3], b4 = bm[4], b5 = bm[5], b6 = bm[6], b7 = bm[7], b8 = bm[8]; return Math.abs(a0 - b0) <= _utils.EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _utils.EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _utils.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= _utils.EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= _utils.EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= _utils.EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= _utils.EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= _utils.EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= _utils.EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)); }; Mat3.toArray = function toArray(out, mat, ofs) { void 0 === ofs && (ofs = 0); var m = mat.m; for (var i = 0; i < 9; i++) out[ofs + i] = m[i]; return out; }; Mat3.fromArray = function fromArray(out, arr, ofs) { void 0 === ofs && (ofs = 0); var m = out.m; for (var i = 0; i < 9; i++) m[i] = arr[ofs + i]; return out; }; function Mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08) { void 0 === m00 && (m00 = 1); void 0 === m01 && (m01 = 0); void 0 === m02 && (m02 = 0); void 0 === m03 && (m03 = 0); void 0 === m04 && (m04 = 1); void 0 === m05 && (m05 = 0); void 0 === m06 && (m06 = 0); void 0 === m07 && (m07 = 0); void 0 === m08 && (m08 = 1); this.m = void 0; if (m00 instanceof _utils.FLOAT_ARRAY_TYPE) this.m = m00; else { this.m = new _utils.FLOAT_ARRAY_TYPE(9); var m = this.m; m[0] = m00; m[1] = m01; m[2] = m02; m[3] = m03; m[4] = m04; m[5] = m05; m[6] = m06; m[7] = m07; m[8] = m08; } } var _proto = Mat3.prototype; _proto.toString = function toString() { var am = this.m; return "mat3(" + am[0] + ", " + am[1] + ", " + am[2] + ", " + am[3] + ", " + am[4] + ", " + am[5] + ", " + am[6] + ", " + am[7] + ", " + am[8] + ")"; }; return Mat3; })(); exports["default"] = Mat3; Mat3.sub = Mat3.subtract; Mat3.mul = Mat3.multiply; Mat3.IDENTITY = Object.freeze(new Mat3()); cc.Mat3 = Mat3; module.exports = exports["default"]; }), { "../value-types/utils": 239, "./vec3": 242 } ], 234: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueType = _interopRequireDefault(require("./value-type")); var _CCClass = _interopRequireDefault(require("../platform/CCClass")); var _vec = _interopRequireDefault(require("./vec3")); var _quat = _interopRequireDefault(require("./quat")); var _utils = require("./utils"); var _mat = _interopRequireDefault(require("./mat3")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _a00 = 0; var _a01 = 0; var _a02 = 0; var _a03 = 0; var _a10 = 0; var _a11 = 0; var _a12 = 0; var _a13 = 0; var _a20 = 0; var _a21 = 0; var _a22 = 0; var _a23 = 0; var _a30 = 0; var _a31 = 0; var _a32 = 0; var _a33 = 0; var Mat4 = (function(_ValueType) { _inheritsLoose(Mat4, _ValueType); var _proto = Mat4.prototype; _proto.mul = function mul(m, out) { return Mat4.multiply(out || new Mat4(), this, m); }; _proto.mulScalar = function mulScalar(num, out) { Mat4.multiplyScalar(out || new Mat4(), this, num); }; _proto.sub = function sub(m, out) { Mat4.subtract(out || new Mat4(), this, m); }; Mat4.clone = function clone(a) { var m = a.m; return new Mat4(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]); }; Mat4.copy = function copy(out, a) { var m = out.m, am = a.m; m[0] = am[0]; m[1] = am[1]; m[2] = am[2]; m[3] = am[3]; m[4] = am[4]; m[5] = am[5]; m[6] = am[6]; m[7] = am[7]; m[8] = am[8]; m[9] = am[9]; m[10] = am[10]; m[11] = am[11]; m[12] = am[12]; m[13] = am[13]; m[14] = am[14]; m[15] = am[15]; return out; }; Mat4.set = function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { var m = out.m; m[0] = m00; m[1] = m01; m[2] = m02; m[3] = m03; m[4] = m10; m[5] = m11; m[6] = m12; m[7] = m13; m[8] = m20; m[9] = m21; m[10] = m22; m[11] = m23; m[12] = m30; m[13] = m31; m[14] = m32; m[15] = m33; return out; }; Mat4.identity = function identity(out) { var m = out.m; m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.transpose = function transpose(out, a) { var m = out.m, am = a.m; if (out === a) { var a01 = am[1], a02 = am[2], a03 = am[3], a12 = am[6], a13 = am[7], a23 = am[11]; m[1] = am[4]; m[2] = am[8]; m[3] = am[12]; m[4] = a01; m[6] = am[9]; m[7] = am[13]; m[8] = a02; m[9] = a12; m[11] = am[14]; m[12] = a03; m[13] = a13; m[14] = a23; } else { m[0] = am[0]; m[1] = am[4]; m[2] = am[8]; m[3] = am[12]; m[4] = am[1]; m[5] = am[5]; m[6] = am[9]; m[7] = am[13]; m[8] = am[2]; m[9] = am[6]; m[10] = am[10]; m[11] = am[14]; m[12] = am[3]; m[13] = am[7]; m[14] = am[11]; m[15] = am[15]; } return out; }; Mat4.invert = function invert(out, a) { var am = a.m; _a00 = am[0]; _a01 = am[1]; _a02 = am[2]; _a03 = am[3]; _a10 = am[4]; _a11 = am[5]; _a12 = am[6]; _a13 = am[7]; _a20 = am[8]; _a21 = am[9]; _a22 = am[10]; _a23 = am[11]; _a30 = am[12]; _a31 = am[13]; _a32 = am[14]; _a33 = am[15]; var b00 = _a00 * _a11 - _a01 * _a10; var b01 = _a00 * _a12 - _a02 * _a10; var b02 = _a00 * _a13 - _a03 * _a10; var b03 = _a01 * _a12 - _a02 * _a11; var b04 = _a01 * _a13 - _a03 * _a11; var b05 = _a02 * _a13 - _a03 * _a12; var b06 = _a20 * _a31 - _a21 * _a30; var b07 = _a20 * _a32 - _a22 * _a30; var b08 = _a20 * _a33 - _a23 * _a30; var b09 = _a21 * _a32 - _a22 * _a31; var b10 = _a21 * _a33 - _a23 * _a31; var b11 = _a22 * _a33 - _a23 * _a32; var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (0 === det) return null; det = 1 / det; var m = out.m; m[0] = (_a11 * b11 - _a12 * b10 + _a13 * b09) * det; m[1] = (_a02 * b10 - _a01 * b11 - _a03 * b09) * det; m[2] = (_a31 * b05 - _a32 * b04 + _a33 * b03) * det; m[3] = (_a22 * b04 - _a21 * b05 - _a23 * b03) * det; m[4] = (_a12 * b08 - _a10 * b11 - _a13 * b07) * det; m[5] = (_a00 * b11 - _a02 * b08 + _a03 * b07) * det; m[6] = (_a32 * b02 - _a30 * b05 - _a33 * b01) * det; m[7] = (_a20 * b05 - _a22 * b02 + _a23 * b01) * det; m[8] = (_a10 * b10 - _a11 * b08 + _a13 * b06) * det; m[9] = (_a01 * b08 - _a00 * b10 - _a03 * b06) * det; m[10] = (_a30 * b04 - _a31 * b02 + _a33 * b00) * det; m[11] = (_a21 * b02 - _a20 * b04 - _a23 * b00) * det; m[12] = (_a11 * b07 - _a10 * b09 - _a12 * b06) * det; m[13] = (_a00 * b09 - _a01 * b07 + _a02 * b06) * det; m[14] = (_a31 * b01 - _a30 * b03 - _a32 * b00) * det; m[15] = (_a20 * b03 - _a21 * b01 + _a22 * b00) * det; return out; }; Mat4.determinant = function determinant(a) { var m = a.m; _a00 = m[0]; _a01 = m[1]; _a02 = m[2]; _a03 = m[3]; _a10 = m[4]; _a11 = m[5]; _a12 = m[6]; _a13 = m[7]; _a20 = m[8]; _a21 = m[9]; _a22 = m[10]; _a23 = m[11]; _a30 = m[12]; _a31 = m[13]; _a32 = m[14]; _a33 = m[15]; var b00 = _a00 * _a11 - _a01 * _a10; var b01 = _a00 * _a12 - _a02 * _a10; var b02 = _a00 * _a13 - _a03 * _a10; var b03 = _a01 * _a12 - _a02 * _a11; var b04 = _a01 * _a13 - _a03 * _a11; var b05 = _a02 * _a13 - _a03 * _a12; var b06 = _a20 * _a31 - _a21 * _a30; var b07 = _a20 * _a32 - _a22 * _a30; var b08 = _a20 * _a33 - _a23 * _a30; var b09 = _a21 * _a32 - _a22 * _a31; var b10 = _a21 * _a33 - _a23 * _a31; var b11 = _a22 * _a33 - _a23 * _a32; return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; }; Mat4.multiply = function multiply(out, a, b) { var m = out.m, am = a.m, bm = b.m; _a00 = am[0]; _a01 = am[1]; _a02 = am[2]; _a03 = am[3]; _a10 = am[4]; _a11 = am[5]; _a12 = am[6]; _a13 = am[7]; _a20 = am[8]; _a21 = am[9]; _a22 = am[10]; _a23 = am[11]; _a30 = am[12]; _a31 = am[13]; _a32 = am[14]; _a33 = am[15]; var b0 = bm[0], b1 = bm[1], b2 = bm[2], b3 = bm[3]; m[0] = b0 * _a00 + b1 * _a10 + b2 * _a20 + b3 * _a30; m[1] = b0 * _a01 + b1 * _a11 + b2 * _a21 + b3 * _a31; m[2] = b0 * _a02 + b1 * _a12 + b2 * _a22 + b3 * _a32; m[3] = b0 * _a03 + b1 * _a13 + b2 * _a23 + b3 * _a33; b0 = bm[4]; b1 = bm[5]; b2 = bm[6]; b3 = bm[7]; m[4] = b0 * _a00 + b1 * _a10 + b2 * _a20 + b3 * _a30; m[5] = b0 * _a01 + b1 * _a11 + b2 * _a21 + b3 * _a31; m[6] = b0 * _a02 + b1 * _a12 + b2 * _a22 + b3 * _a32; m[7] = b0 * _a03 + b1 * _a13 + b2 * _a23 + b3 * _a33; b0 = bm[8]; b1 = bm[9]; b2 = bm[10]; b3 = bm[11]; m[8] = b0 * _a00 + b1 * _a10 + b2 * _a20 + b3 * _a30; m[9] = b0 * _a01 + b1 * _a11 + b2 * _a21 + b3 * _a31; m[10] = b0 * _a02 + b1 * _a12 + b2 * _a22 + b3 * _a32; m[11] = b0 * _a03 + b1 * _a13 + b2 * _a23 + b3 * _a33; b0 = bm[12]; b1 = bm[13]; b2 = bm[14]; b3 = bm[15]; m[12] = b0 * _a00 + b1 * _a10 + b2 * _a20 + b3 * _a30; m[13] = b0 * _a01 + b1 * _a11 + b2 * _a21 + b3 * _a31; m[14] = b0 * _a02 + b1 * _a12 + b2 * _a22 + b3 * _a32; m[15] = b0 * _a03 + b1 * _a13 + b2 * _a23 + b3 * _a33; return out; }; Mat4.transform = function transform(out, a, v) { var x = v.x, y = v.y, z = v.z; var m = out.m, am = a.m; if (a === out) { m[12] = am[0] * x + am[4] * y + am[8] * z + am[12]; m[13] = am[1] * x + am[5] * y + am[9] * z + am[13]; m[14] = am[2] * x + am[6] * y + am[10] * z + am[14]; m[15] = am[3] * x + am[7] * y + am[11] * z + am[15]; } else { _a00 = am[0]; _a01 = am[1]; _a02 = am[2]; _a03 = am[3]; _a10 = am[4]; _a11 = am[5]; _a12 = am[6]; _a13 = am[7]; _a20 = am[8]; _a21 = am[9]; _a22 = am[10]; _a23 = am[11]; _a30 = am[12]; _a31 = am[13]; _a32 = am[14]; _a33 = am[15]; m[0] = _a00; m[1] = _a01; m[2] = _a02; m[3] = _a03; m[4] = _a10; m[5] = _a11; m[6] = _a12; m[7] = _a13; m[8] = _a20; m[9] = _a21; m[10] = _a22; m[11] = _a23; m[12] = _a00 * x + _a10 * y + _a20 * z + am[12]; m[13] = _a01 * x + _a11 * y + _a21 * z + am[13]; m[14] = _a02 * x + _a12 * y + _a22 * z + am[14]; m[15] = _a03 * x + _a13 * y + _a23 * z + am[15]; } return out; }; Mat4.translate = function translate(out, a, v) { var m = out.m, am = a.m; if (a === out) { m[12] += v.x; m[13] += v.y; m[14] += v.z; } else { m[0] = am[0]; m[1] = am[1]; m[2] = am[2]; m[3] = am[3]; m[4] = am[4]; m[5] = am[5]; m[6] = am[6]; m[7] = am[7]; m[8] = am[8]; m[9] = am[9]; m[10] = am[10]; m[11] = am[11]; m[12] += v.x; m[13] += v.y; m[14] += v.z; m[15] = am[15]; } return out; }; Mat4.scale = function scale(out, a, v) { var x = v.x, y = v.y, z = v.z; var m = out.m, am = a.m; m[0] = am[0] * x; m[1] = am[1] * x; m[2] = am[2] * x; m[3] = am[3] * x; m[4] = am[4] * y; m[5] = am[5] * y; m[6] = am[6] * y; m[7] = am[7] * y; m[8] = am[8] * z; m[9] = am[9] * z; m[10] = am[10] * z; m[11] = am[11] * z; m[12] = am[12]; m[13] = am[13]; m[14] = am[14]; m[15] = am[15]; return out; }; Mat4.rotate = function rotate(out, a, rad, axis) { var x = axis.x, y = axis.y, z = axis.z; var len = Math.sqrt(x * x + y * y + z * z); if (Math.abs(len) < _utils.EPSILON) return null; len = 1 / len; x *= len; y *= len; z *= len; var s = Math.sin(rad); var c = Math.cos(rad); var t = 1 - c; var am = a.m; _a00 = am[0]; _a01 = am[1]; _a02 = am[2]; _a03 = am[3]; _a10 = am[4]; _a11 = am[5]; _a12 = am[6]; _a13 = am[7]; _a20 = am[8]; _a21 = am[9]; _a22 = am[10]; _a23 = am[11]; var b00 = x * x * t + c, b01 = y * x * t + z * s, b02 = z * x * t - y * s; var b10 = x * y * t - z * s, b11 = y * y * t + c, b12 = z * y * t + x * s; var b20 = x * z * t + y * s, b21 = y * z * t - x * s, b22 = z * z * t + c; var m = out.m; m[0] = _a00 * b00 + _a10 * b01 + _a20 * b02; m[1] = _a01 * b00 + _a11 * b01 + _a21 * b02; m[2] = _a02 * b00 + _a12 * b01 + _a22 * b02; m[3] = _a03 * b00 + _a13 * b01 + _a23 * b02; m[4] = _a00 * b10 + _a10 * b11 + _a20 * b12; m[5] = _a01 * b10 + _a11 * b11 + _a21 * b12; m[6] = _a02 * b10 + _a12 * b11 + _a22 * b12; m[7] = _a03 * b10 + _a13 * b11 + _a23 * b12; m[8] = _a00 * b20 + _a10 * b21 + _a20 * b22; m[9] = _a01 * b20 + _a11 * b21 + _a21 * b22; m[10] = _a02 * b20 + _a12 * b21 + _a22 * b22; m[11] = _a03 * b20 + _a13 * b21 + _a23 * b22; if (a !== out) { m[12] = am[12]; m[13] = am[13]; m[14] = am[14]; m[15] = am[15]; } return out; }; Mat4.rotateX = function rotateX(out, a, rad) { var m = out.m, am = a.m; var s = Math.sin(rad), c = Math.cos(rad), a10 = am[4], a11 = am[5], a12 = am[6], a13 = am[7], a20 = am[8], a21 = am[9], a22 = am[10], a23 = am[11]; if (a !== out) { m[0] = am[0]; m[1] = am[1]; m[2] = am[2]; m[3] = am[3]; m[12] = am[12]; m[13] = am[13]; m[14] = am[14]; m[15] = am[15]; } m[4] = a10 * c + a20 * s; m[5] = a11 * c + a21 * s; m[6] = a12 * c + a22 * s; m[7] = a13 * c + a23 * s; m[8] = a20 * c - a10 * s; m[9] = a21 * c - a11 * s; m[10] = a22 * c - a12 * s; m[11] = a23 * c - a13 * s; return out; }; Mat4.rotateY = function rotateY(out, a, rad) { var m = out.m, am = a.m; var s = Math.sin(rad), c = Math.cos(rad), a00 = am[0], a01 = am[1], a02 = am[2], a03 = am[3], a20 = am[8], a21 = am[9], a22 = am[10], a23 = am[11]; if (a !== out) { m[4] = am[4]; m[5] = am[5]; m[6] = am[6]; m[7] = am[7]; m[12] = am[12]; m[13] = am[13]; m[14] = am[14]; m[15] = am[15]; } m[0] = a00 * c - a20 * s; m[1] = a01 * c - a21 * s; m[2] = a02 * c - a22 * s; m[3] = a03 * c - a23 * s; m[8] = a00 * s + a20 * c; m[9] = a01 * s + a21 * c; m[10] = a02 * s + a22 * c; m[11] = a03 * s + a23 * c; return out; }; Mat4.rotateZ = function rotateZ(out, a, rad) { var am = a.m; var m = out.m; var s = Math.sin(rad), c = Math.cos(rad), a00 = a.m[0], a01 = a.m[1], a02 = a.m[2], a03 = a.m[3], a10 = a.m[4], a11 = a.m[5], a12 = a.m[6], a13 = a.m[7]; if (a !== out) { m[8] = am[8]; m[9] = am[9]; m[10] = am[10]; m[11] = am[11]; m[12] = am[12]; m[13] = am[13]; m[14] = am[14]; m[15] = am[15]; } m[0] = a00 * c + a10 * s; m[1] = a01 * c + a11 * s; m[2] = a02 * c + a12 * s; m[3] = a03 * c + a13 * s; m[4] = a10 * c - a00 * s; m[5] = a11 * c - a01 * s; m[6] = a12 * c - a02 * s; m[7] = a13 * c - a03 * s; return out; }; Mat4.fromTranslation = function fromTranslation(out, v) { var m = out.m; m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = v.x; m[13] = v.y; m[14] = v.z; m[15] = 1; return out; }; Mat4.fromScaling = function fromScaling(out, v) { var m = out.m; m[0] = v.x; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = v.y; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = v.z; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.fromRotation = function fromRotation(out, rad, axis) { var x = axis.x, y = axis.y, z = axis.z; var len = Math.sqrt(x * x + y * y + z * z); if (Math.abs(len) < _utils.EPSILON) return null; len = 1 / len; x *= len; y *= len; z *= len; var s = Math.sin(rad); var c = Math.cos(rad); var t = 1 - c; var m = out.m; m[0] = x * x * t + c; m[1] = y * x * t + z * s; m[2] = z * x * t - y * s; m[3] = 0; m[4] = x * y * t - z * s; m[5] = y * y * t + c; m[6] = z * y * t + x * s; m[7] = 0; m[8] = x * z * t + y * s; m[9] = y * z * t - x * s; m[10] = z * z * t + c; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.fromXRotation = function fromXRotation(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); var m = out.m; m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = c; m[6] = s; m[7] = 0; m[8] = 0; m[9] = -s; m[10] = c; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.fromYRotation = function fromYRotation(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); var m = out.m; m[0] = c; m[1] = 0; m[2] = -s; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = s; m[9] = 0; m[10] = c; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.fromZRotation = function fromZRotation(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); var m = out.m; m[0] = c; m[1] = s; m[2] = 0; m[3] = 0; m[4] = -s; m[5] = c; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.fromRT = function fromRT(out, q, v) { var x = q.x, y = q.y, z = q.z, w = q.w; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var xy = x * y2; var xz = x * z2; var yy = y * y2; var yz = y * z2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; var m = out.m; m[0] = 1 - (yy + zz); m[1] = xy + wz; m[2] = xz - wy; m[3] = 0; m[4] = xy - wz; m[5] = 1 - (xx + zz); m[6] = yz + wx; m[7] = 0; m[8] = xz + wy; m[9] = yz - wx; m[10] = 1 - (xx + yy); m[11] = 0; m[12] = v.x; m[13] = v.y; m[14] = v.z; m[15] = 1; return out; }; Mat4.getTranslation = function getTranslation(out, mat) { var m = mat.m; out.x = m[12]; out.y = m[13]; out.z = m[14]; return out; }; Mat4.getScaling = function getScaling(out, mat) { var m = mat.m; var m3 = m3_1.m; var m00 = m3[0] = m[0]; var m01 = m3[1] = m[1]; var m02 = m3[2] = m[2]; var m04 = m3[3] = m[4]; var m05 = m3[4] = m[5]; var m06 = m3[5] = m[6]; var m08 = m3[6] = m[8]; var m09 = m3[7] = m[9]; var m10 = m3[8] = m[10]; out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06); out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10); _mat["default"].determinant(m3_1) < 0 && (out.x *= -1); return out; }; Mat4.getRotation = function getRotation(out, mat) { var m = mat.m; var trace = m[0] + m[5] + m[10]; var S = 0; if (trace > 0) { S = 2 * Math.sqrt(trace + 1); out.w = .25 * S; out.x = (m[6] - m[9]) / S; out.y = (m[8] - m[2]) / S; out.z = (m[1] - m[4]) / S; } else if (m[0] > m[5] && m[0] > m[10]) { S = 2 * Math.sqrt(1 + m[0] - m[5] - m[10]); out.w = (m[6] - m[9]) / S; out.x = .25 * S; out.y = (m[1] + m[4]) / S; out.z = (m[8] + m[2]) / S; } else if (m[5] > m[10]) { S = 2 * Math.sqrt(1 + m[5] - m[0] - m[10]); out.w = (m[8] - m[2]) / S; out.x = (m[1] + m[4]) / S; out.y = .25 * S; out.z = (m[6] + m[9]) / S; } else { S = 2 * Math.sqrt(1 + m[10] - m[0] - m[5]); out.w = (m[1] - m[4]) / S; out.x = (m[8] + m[2]) / S; out.y = (m[6] + m[9]) / S; out.z = .25 * S; } return out; }; Mat4.toRTS = function toRTS(mat, q, v, s) { var m = mat.m; var m3 = m3_1.m; s.x = _vec["default"].set(v3_1, m[0], m[1], m[2]).mag(); m3[0] = m[0] / s.x; m3[1] = m[1] / s.x; m3[2] = m[2] / s.x; s.y = _vec["default"].set(v3_1, m[4], m[5], m[6]).mag(); m3[3] = m[4] / s.y; m3[4] = m[5] / s.y; m3[5] = m[6] / s.y; s.z = _vec["default"].set(v3_1, m[8], m[9], m[10]).mag(); m3[6] = m[8] / s.z; m3[7] = m[9] / s.z; m3[8] = m[10] / s.z; var det = _mat["default"].determinant(m3_1); if (det < 0) { s.x *= -1; m3[0] *= -1; m3[1] *= -1; m3[2] *= -1; } _quat["default"].fromMat3(q, m3_1); _vec["default"].set(v, m[12], m[13], m[14]); }; Mat4.fromRTS = function fromRTS(out, q, v, s) { var x = q.x, y = q.y, z = q.z, w = q.w; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var xy = x * y2; var xz = x * z2; var yy = y * y2; var yz = y * z2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; var sx = s.x; var sy = s.y; var sz = s.z; var m = out.m; m[0] = (1 - (yy + zz)) * sx; m[1] = (xy + wz) * sx; m[2] = (xz - wy) * sx; m[3] = 0; m[4] = (xy - wz) * sy; m[5] = (1 - (xx + zz)) * sy; m[6] = (yz + wx) * sy; m[7] = 0; m[8] = (xz + wy) * sz; m[9] = (yz - wx) * sz; m[10] = (1 - (xx + yy)) * sz; m[11] = 0; m[12] = v.x; m[13] = v.y; m[14] = v.z; m[15] = 1; return out; }; Mat4.fromRTSOrigin = function fromRTSOrigin(out, q, v, s, o) { var x = q.x, y = q.y, z = q.z, w = q.w; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var xy = x * y2; var xz = x * z2; var yy = y * y2; var yz = y * z2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; var sx = s.x; var sy = s.y; var sz = s.z; var ox = o.x; var oy = o.y; var oz = o.z; var m = out.m; m[0] = (1 - (yy + zz)) * sx; m[1] = (xy + wz) * sx; m[2] = (xz - wy) * sx; m[3] = 0; m[4] = (xy - wz) * sy; m[5] = (1 - (xx + zz)) * sy; m[6] = (yz + wx) * sy; m[7] = 0; m[8] = (xz + wy) * sz; m[9] = (yz - wx) * sz; m[10] = (1 - (xx + yy)) * sz; m[11] = 0; m[12] = v.x + ox - (m[0] * ox + m[4] * oy + m[8] * oz); m[13] = v.y + oy - (m[1] * ox + m[5] * oy + m[9] * oz); m[14] = v.z + oz - (m[2] * ox + m[6] * oy + m[10] * oz); m[15] = 1; return out; }; Mat4.fromQuat = function fromQuat(out, q) { var x = q.x, y = q.y, z = q.z, w = q.w; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var yx = y * x2; var yy = y * y2; var zx = z * x2; var zy = z * y2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; var m = out.m; m[0] = 1 - yy - zz; m[1] = yx + wz; m[2] = zx - wy; m[3] = 0; m[4] = yx - wz; m[5] = 1 - xx - zz; m[6] = zy + wx; m[7] = 0; m[8] = zx + wy; m[9] = zy - wx; m[10] = 1 - xx - yy; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.frustum = function frustum(out, left, right, bottom, top, near, far) { var rl = 1 / (right - left); var tb = 1 / (top - bottom); var nf = 1 / (near - far); var m = out.m; m[0] = 2 * near * rl; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 2 * near * tb; m[6] = 0; m[7] = 0; m[8] = (right + left) * rl; m[9] = (top + bottom) * tb; m[10] = (far + near) * nf; m[11] = -1; m[12] = 0; m[13] = 0; m[14] = far * near * 2 * nf; m[15] = 0; return out; }; Mat4.perspective = function perspective(out, fovy, aspect, near, far) { var f = 1 / Math.tan(fovy / 2); var nf = 1 / (near - far); var m = out.m; m[0] = f / aspect; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = f; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = (far + near) * nf; m[11] = -1; m[12] = 0; m[13] = 0; m[14] = 2 * far * near * nf; m[15] = 0; return out; }; Mat4.ortho = function ortho(out, left, right, bottom, top, near, far) { var lr = 1 / (left - right); var bt = 1 / (bottom - top); var nf = 1 / (near - far); var m = out.m; m[0] = -2 * lr; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = -2 * bt; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 2 * nf; m[11] = 0; m[12] = (left + right) * lr; m[13] = (top + bottom) * bt; m[14] = (far + near) * nf; m[15] = 1; return out; }; Mat4.lookAt = function lookAt(out, eye, center, up) { var eyex = eye.x; var eyey = eye.y; var eyez = eye.z; var upx = up.x; var upy = up.y; var upz = up.z; var centerx = center.x; var centery = center.y; var centerz = center.z; var z0 = eyex - centerx; var z1 = eyey - centery; var z2 = eyez - centerz; var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); z0 *= len; z1 *= len; z2 *= len; var x0 = upy * z2 - upz * z1; var x1 = upz * z0 - upx * z2; var x2 = upx * z1 - upy * z0; len = 1 / Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); x0 *= len; x1 *= len; x2 *= len; var y0 = z1 * x2 - z2 * x1; var y1 = z2 * x0 - z0 * x2; var y2 = z0 * x1 - z1 * x0; var m = out.m; m[0] = x0; m[1] = y0; m[2] = z0; m[3] = 0; m[4] = x1; m[5] = y1; m[6] = z1; m[7] = 0; m[8] = x2; m[9] = y2; m[10] = z2; m[11] = 0; m[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); m[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); m[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); m[15] = 1; return out; }; Mat4.inverseTranspose = function inverseTranspose(out, a) { var m = a.m; _a00 = m[0]; _a01 = m[1]; _a02 = m[2]; _a03 = m[3]; _a10 = m[4]; _a11 = m[5]; _a12 = m[6]; _a13 = m[7]; _a20 = m[8]; _a21 = m[9]; _a22 = m[10]; _a23 = m[11]; _a30 = m[12]; _a31 = m[13]; _a32 = m[14]; _a33 = m[15]; var b00 = _a00 * _a11 - _a01 * _a10; var b01 = _a00 * _a12 - _a02 * _a10; var b02 = _a00 * _a13 - _a03 * _a10; var b03 = _a01 * _a12 - _a02 * _a11; var b04 = _a01 * _a13 - _a03 * _a11; var b05 = _a02 * _a13 - _a03 * _a12; var b06 = _a20 * _a31 - _a21 * _a30; var b07 = _a20 * _a32 - _a22 * _a30; var b08 = _a20 * _a33 - _a23 * _a30; var b09 = _a21 * _a32 - _a22 * _a31; var b10 = _a21 * _a33 - _a23 * _a31; var b11 = _a22 * _a33 - _a23 * _a32; var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) return null; det = 1 / det; m = out.m; m[0] = (_a11 * b11 - _a12 * b10 + _a13 * b09) * det; m[1] = (_a12 * b08 - _a10 * b11 - _a13 * b07) * det; m[2] = (_a10 * b10 - _a11 * b08 + _a13 * b06) * det; m[3] = 0; m[4] = (_a02 * b10 - _a01 * b11 - _a03 * b09) * det; m[5] = (_a00 * b11 - _a02 * b08 + _a03 * b07) * det; m[6] = (_a01 * b08 - _a00 * b10 - _a03 * b06) * det; m[7] = 0; m[8] = (_a31 * b05 - _a32 * b04 + _a33 * b03) * det; m[9] = (_a32 * b02 - _a30 * b05 - _a33 * b01) * det; m[10] = (_a30 * b04 - _a31 * b02 + _a33 * b00) * det; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; return out; }; Mat4.add = function add(out, a, b) { var m = out.m, am = a.m, bm = b.m; m[0] = am[0] + bm[0]; m[1] = am[1] + bm[1]; m[2] = am[2] + bm[2]; m[3] = am[3] + bm[3]; m[4] = am[4] + bm[4]; m[5] = am[5] + bm[5]; m[6] = am[6] + bm[6]; m[7] = am[7] + bm[7]; m[8] = am[8] + bm[8]; m[9] = am[9] + bm[9]; m[10] = am[10] + bm[10]; m[11] = am[11] + bm[11]; m[12] = am[12] + bm[12]; m[13] = am[13] + bm[13]; m[14] = am[14] + bm[14]; m[15] = am[15] + bm[15]; return out; }; Mat4.subtract = function subtract(out, a, b) { var m = out.m, am = a.m, bm = b.m; m[0] = am[0] - bm[0]; m[1] = am[1] - bm[1]; m[2] = am[2] - bm[2]; m[3] = am[3] - bm[3]; m[4] = am[4] - bm[4]; m[5] = am[5] - bm[5]; m[6] = am[6] - bm[6]; m[7] = am[7] - bm[7]; m[8] = am[8] - bm[8]; m[9] = am[9] - bm[9]; m[10] = am[10] - bm[10]; m[11] = am[11] - bm[11]; m[12] = am[12] - bm[12]; m[13] = am[13] - bm[13]; m[14] = am[14] - bm[14]; m[15] = am[15] - bm[15]; return out; }; Mat4.multiplyScalar = function multiplyScalar(out, a, b) { var m = out.m, am = a.m; m[0] = am[0] * b; m[1] = am[1] * b; m[2] = am[2] * b; m[3] = am[3] * b; m[4] = am[4] * b; m[5] = am[5] * b; m[6] = am[6] * b; m[7] = am[7] * b; m[8] = am[8] * b; m[9] = am[9] * b; m[10] = am[10] * b; m[11] = am[11] * b; m[12] = am[12] * b; m[13] = am[13] * b; m[14] = am[14] * b; m[15] = am[15] * b; return out; }; Mat4.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) { var m = out.m, am = a.m, bm = b.m; m[0] = am[0] + bm[0] * scale; m[1] = am[1] + bm[1] * scale; m[2] = am[2] + bm[2] * scale; m[3] = am[3] + bm[3] * scale; m[4] = am[4] + bm[4] * scale; m[5] = am[5] + bm[5] * scale; m[6] = am[6] + bm[6] * scale; m[7] = am[7] + bm[7] * scale; m[8] = am[8] + bm[8] * scale; m[9] = am[9] + bm[9] * scale; m[10] = am[10] + bm[10] * scale; m[11] = am[11] + bm[11] * scale; m[12] = am[12] + bm[12] * scale; m[13] = am[13] + bm[13] * scale; m[14] = am[14] + bm[14] * scale; m[15] = am[15] + bm[15] * scale; return out; }; Mat4.strictEquals = function strictEquals(a, b) { var am = a.m, bm = b.m; return am[0] === bm[0] && am[1] === bm[1] && am[2] === bm[2] && am[3] === bm[3] && am[4] === bm[4] && am[5] === bm[5] && am[6] === bm[6] && am[7] === bm[7] && am[8] === bm[8] && am[9] === bm[9] && am[10] === bm[10] && am[11] === bm[11] && am[12] === bm[12] && am[13] === bm[13] && am[14] === bm[14] && am[15] === bm[15]; }; Mat4.equals = function equals(a, b, epsilon) { void 0 === epsilon && (epsilon = _utils.EPSILON); var am = a.m, bm = b.m; return Math.abs(am[0] - bm[0]) <= epsilon * Math.max(1, Math.abs(am[0]), Math.abs(bm[0])) && Math.abs(am[1] - bm[1]) <= epsilon * Math.max(1, Math.abs(am[1]), Math.abs(bm[1])) && Math.abs(am[2] - bm[2]) <= epsilon * Math.max(1, Math.abs(am[2]), Math.abs(bm[2])) && Math.abs(am[3] - bm[3]) <= epsilon * Math.max(1, Math.abs(am[3]), Math.abs(bm[3])) && Math.abs(am[4] - bm[4]) <= epsilon * Math.max(1, Math.abs(am[4]), Math.abs(bm[4])) && Math.abs(am[5] - bm[5]) <= epsilon * Math.max(1, Math.abs(am[5]), Math.abs(bm[5])) && Math.abs(am[6] - bm[6]) <= epsilon * Math.max(1, Math.abs(am[6]), Math.abs(bm[6])) && Math.abs(am[7] - bm[7]) <= epsilon * Math.max(1, Math.abs(am[7]), Math.abs(bm[7])) && Math.abs(am[8] - bm[8]) <= epsilon * Math.max(1, Math.abs(am[8]), Math.abs(bm[8])) && Math.abs(am[9] - bm[9]) <= epsilon * Math.max(1, Math.abs(am[9]), Math.abs(bm[9])) && Math.abs(am[10] - bm[10]) <= epsilon * Math.max(1, Math.abs(am[10]), Math.abs(bm[10])) && Math.abs(am[11] - bm[11]) <= epsilon * Math.max(1, Math.abs(am[11]), Math.abs(bm[11])) && Math.abs(am[12] - bm[12]) <= epsilon * Math.max(1, Math.abs(am[12]), Math.abs(bm[12])) && Math.abs(am[13] - bm[13]) <= epsilon * Math.max(1, Math.abs(am[13]), Math.abs(bm[13])) && Math.abs(am[14] - bm[14]) <= epsilon * Math.max(1, Math.abs(am[14]), Math.abs(bm[14])) && Math.abs(am[15] - bm[15]) <= epsilon * Math.max(1, Math.abs(am[15]), Math.abs(bm[15])); }; Mat4.adjoint = function adjoint(out, a) { var am = a.m, outm = out.m; var a00 = am[0], a01 = am[1], a02 = am[2], a03 = am[3], a10 = am[4], a11 = am[5], a12 = am[6], a13 = am[7], a20 = am[8], a21 = am[9], a22 = am[10], a23 = am[11], a30 = am[12], a31 = am[13], a32 = am[14], a33 = am[15]; outm[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); outm[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); outm[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); outm[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); outm[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); outm[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); outm[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); outm[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); outm[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); outm[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); outm[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); outm[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); outm[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); outm[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); outm[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); outm[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); return out; }; Mat4.toArray = function toArray(out, mat, ofs) { void 0 === ofs && (ofs = 0); var m = mat.m; for (var i = 0; i < 16; i++) out[ofs + i] = m[i]; return out; }; Mat4.fromArray = function fromArray(out, arr, ofs) { void 0 === ofs && (ofs = 0); var m = out.m; for (var i = 0; i < 16; i++) m[i] = arr[ofs + i]; return out; }; function Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { var _this; void 0 === m00 && (m00 = 1); void 0 === m01 && (m01 = 0); void 0 === m02 && (m02 = 0); void 0 === m03 && (m03 = 0); void 0 === m10 && (m10 = 0); void 0 === m11 && (m11 = 1); void 0 === m12 && (m12 = 0); void 0 === m13 && (m13 = 0); void 0 === m20 && (m20 = 0); void 0 === m21 && (m21 = 0); void 0 === m22 && (m22 = 1); void 0 === m23 && (m23 = 0); void 0 === m30 && (m30 = 0); void 0 === m31 && (m31 = 0); void 0 === m32 && (m32 = 0); void 0 === m33 && (m33 = 1); _this = _ValueType.call(this) || this; _this.m = void 0; if (m00 instanceof _utils.FLOAT_ARRAY_TYPE) _this.m = m00; else { _this.m = new _utils.FLOAT_ARRAY_TYPE(16); var tm = _this.m; tm[0] = m00; tm[1] = m01; tm[2] = m02; tm[3] = m03; tm[4] = m10; tm[5] = m11; tm[6] = m12; tm[7] = m13; tm[8] = m20; tm[9] = m21; tm[10] = m22; tm[11] = m23; tm[12] = m30; tm[13] = m31; tm[14] = m32; tm[15] = m33; } return _this; } _proto.clone = function clone() { var t = this; var tm = t.m; return new Mat4(tm[0], tm[1], tm[2], tm[3], tm[4], tm[5], tm[6], tm[7], tm[8], tm[9], tm[10], tm[11], tm[12], tm[13], tm[14], tm[15]); }; _proto.set = function set(s) { var t = this; var tm = t.m, sm = s.m; tm[0] = sm[0]; tm[1] = sm[1]; tm[2] = sm[2]; tm[3] = sm[3]; tm[4] = sm[4]; tm[5] = sm[5]; tm[6] = sm[6]; tm[7] = sm[7]; tm[8] = sm[8]; tm[9] = sm[9]; tm[10] = sm[10]; tm[11] = sm[11]; tm[12] = sm[12]; tm[13] = sm[13]; tm[14] = sm[14]; tm[15] = sm[15]; return this; }; _proto.equals = function equals(other) { return Mat4.strictEquals(this, other); }; _proto.fuzzyEquals = function fuzzyEquals(other) { return Mat4.equals(this, other); }; _proto.toString = function toString() { var tm = this.m; return tm ? "[\n" + tm[0] + ", " + tm[1] + ", " + tm[2] + ", " + tm[3] + ",\n" + tm[4] + ", " + tm[5] + ", " + tm[6] + ", " + tm[7] + ",\n" + tm[8] + ", " + tm[9] + ", " + tm[10] + ", " + tm[11] + ",\n" + tm[12] + ", " + tm[13] + ", " + tm[14] + ", " + tm[15] + "\n]" : "[\n1, 0, 0, 0\n0, 1, 0, 0\n0, 0, 1, 0\n0, 0, 0, 1\n]"; }; _proto.identity = function identity() { return Mat4.identity(this); }; _proto.transpose = function transpose(out) { out = out || new Mat4(); return Mat4.transpose(out, this); }; _proto.invert = function invert(out) { out = out || new Mat4(); return Mat4.invert(out, this); }; _proto.adjoint = function adjoint(out) { out = out || new Mat4(); return Mat4.adjoint(out, this); }; _proto.determinant = function determinant() { return Mat4.determinant(this); }; _proto.add = function add(other, out) { out = out || new Mat4(); return Mat4.add(out, this, other); }; _proto.subtract = function subtract(other) { return Mat4.subtract(this, this, other); }; _proto.multiply = function multiply(other) { return Mat4.multiply(this, this, other); }; _proto.multiplyScalar = function multiplyScalar(number) { return Mat4.multiplyScalar(this, this, number); }; _proto.translate = function translate(v, out) { out = out || new Mat4(); return Mat4.translate(out, this, v); }; _proto.scale = function scale(v, out) { out = out || new Mat4(); return Mat4.scale(out, this, v); }; _proto.rotate = function rotate(rad, axis, out) { out = out || new Mat4(); return Mat4.rotate(out, this, rad, axis); }; _proto.getTranslation = function getTranslation(out) { out = out || new _vec["default"](); return Mat4.getTranslation(out, this); }; _proto.getScale = function getScale(out) { out = out || new _vec["default"](); return Mat4.getScaling(out, this); }; _proto.getRotation = function getRotation(out) { out = out || new _quat["default"](); return Mat4.getRotation(out, this); }; _proto.fromRTS = function fromRTS(q, v, s) { return Mat4.fromRTS(this, q, v, s); }; _proto.fromQuat = function fromQuat(quat) { return Mat4.fromQuat(this, quat); }; return Mat4; })(_valueType["default"]); exports["default"] = Mat4; Mat4.mul = Mat4.multiply; Mat4.sub = Mat4.subtract; Mat4.IDENTITY = Object.freeze(new Mat4()); var v3_1 = new _vec["default"](); var m3_1 = new _mat["default"](); _CCClass["default"].fastDefine("cc.Mat4", Mat4, { m00: 1, m01: 0, m02: 0, m03: 0, m04: 0, m05: 1, m06: 0, m07: 0, m08: 0, m09: 0, m10: 1, m11: 0, m12: 0, m13: 0, m14: 0, m15: 1 }); var _loop = function _loop(i) { Object.defineProperty(Mat4.prototype, "m" + i, { get: function get() { return this.m[i]; }, set: function set(value) { this.m[i] = value; } }); }; for (var i = 0; i < 16; i++) _loop(i); cc.mat4 = function(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { var mat = new Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); void 0 === m00 && Mat4.identity(mat); return mat; }; cc.Mat4 = Mat4; module.exports = exports["default"]; }), { "../platform/CCClass": 129, "./mat3": 233, "./quat": 235, "./utils": 239, "./value-type": 240, "./vec3": 242 } ], 235: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueType = _interopRequireDefault(require("./value-type")); var _CCClass = _interopRequireDefault(require("../platform/CCClass")); var _vec = _interopRequireDefault(require("./vec3")); var _mat = _interopRequireDefault(require("./mat3")); var _utils = require("./utils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _x = 0; var _y = 0; var _z = 0; var _w = 0; var Quat = (function(_ValueType) { _inheritsLoose(Quat, _ValueType); var _proto = Quat.prototype; _proto.mul = function mul(other, out) { return Quat.multiply(out || new Quat(), this, other); }; Quat.clone = function clone(a) { return new Quat(a.x, a.y, a.z, a.w); }; Quat.copy = function copy(out, a) { out.x = a.x; out.y = a.y; out.z = a.z; out.w = a.w; return out; }; Quat.set = function set(out, x, y, z, w) { out.x = x; out.y = y; out.z = z; out.w = w; return out; }; Quat.identity = function identity(out) { out.x = 0; out.y = 0; out.z = 0; out.w = 1; return out; }; Quat.rotationTo = function rotationTo(out, a, b) { var dot = _vec["default"].dot(a, b); if (dot < -.999999) { _vec["default"].cross(v3_1, _vec["default"].RIGHT, a); v3_1.mag() < 1e-6 && _vec["default"].cross(v3_1, _vec["default"].UP, a); _vec["default"].normalize(v3_1, v3_1); Quat.fromAxisAngle(out, v3_1, Math.PI); return out; } if (dot > .999999) { out.x = 0; out.y = 0; out.z = 0; out.w = 1; return out; } _vec["default"].cross(v3_1, a, b); out.x = v3_1.x; out.y = v3_1.y; out.z = v3_1.z; out.w = 1 + dot; return Quat.normalize(out, out); }; Quat.getAxisAngle = function getAxisAngle(outAxis, q) { var rad = 2 * Math.acos(q.w); var s = Math.sin(rad / 2); if (0 !== s) { outAxis.x = q.x / s; outAxis.y = q.y / s; outAxis.z = q.z / s; } else { outAxis.x = 1; outAxis.y = 0; outAxis.z = 0; } return rad; }; Quat.multiply = function multiply(out, a, b) { _x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y; _y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z; _z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x; _w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z; out.x = _x; out.y = _y; out.z = _z; out.w = _w; return out; }; Quat.multiplyScalar = function multiplyScalar(out, a, b) { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; out.w = a.w * b; return out; }; Quat.scaleAndAdd = function scaleAndAdd(out, a, b, scale) { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale; out.w = a.w + b.w * scale; return out; }; Quat.rotateX = function rotateX(out, a, rad) { rad *= .5; var bx = Math.sin(rad); var bw = Math.cos(rad); _x = a.x * bw + a.w * bx; _y = a.y * bw + a.z * bx; _z = a.z * bw - a.y * bx; _w = a.w * bw - a.x * bx; out.x = _x; out.y = _y; out.z = _z; out.w = _w; return out; }; Quat.rotateY = function rotateY(out, a, rad) { rad *= .5; var by = Math.sin(rad); var bw = Math.cos(rad); _x = a.x * bw - a.z * by; _y = a.y * bw + a.w * by; _z = a.z * bw + a.x * by; _w = a.w * bw - a.y * by; out.x = _x; out.y = _y; out.z = _z; out.w = _w; return out; }; Quat.rotateZ = function rotateZ(out, a, rad) { rad *= .5; var bz = Math.sin(rad); var bw = Math.cos(rad); _x = a.x * bw + a.y * bz; _y = a.y * bw - a.x * bz; _z = a.z * bw + a.w * bz; _w = a.w * bw - a.z * bz; out.x = _x; out.y = _y; out.z = _z; out.w = _w; return out; }; Quat.rotateAround = function rotateAround(out, rot, axis, rad) { Quat.invert(qt_1, rot); _vec["default"].transformQuat(v3_1, axis, qt_1); Quat.fromAxisAngle(qt_1, v3_1, rad); Quat.multiply(out, rot, qt_1); return out; }; Quat.rotateAroundLocal = function rotateAroundLocal(out, rot, axis, rad) { Quat.fromAxisAngle(qt_1, axis, rad); Quat.multiply(out, rot, qt_1); return out; }; Quat.calculateW = function calculateW(out, a) { out.x = a.x; out.y = a.y; out.z = a.z; out.w = Math.sqrt(Math.abs(1 - a.x * a.x - a.y * a.y - a.z * a.z)); return out; }; Quat.dot = function dot(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }; Quat.lerp = function lerp(out, a, b, t) { out.x = a.x + t * (b.x - a.x); out.y = a.y + t * (b.y - a.y); out.z = a.z + t * (b.z - a.z); out.w = a.w + t * (b.w - a.w); return out; }; Quat.slerp = function slerp(out, a, b, t) { var scale0 = 0; var scale1 = 0; var cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; if (cosom < 0) { cosom = -cosom; b.x = -b.x; b.y = -b.y; b.z = -b.z; b.w = -b.w; } if (1 - cosom > 1e-6) { var omega = Math.acos(cosom); var sinom = Math.sin(omega); scale0 = Math.sin((1 - t) * omega) / sinom; scale1 = Math.sin(t * omega) / sinom; } else { scale0 = 1 - t; scale1 = t; } out.x = scale0 * a.x + scale1 * b.x; out.y = scale0 * a.y + scale1 * b.y; out.z = scale0 * a.z + scale1 * b.z; out.w = scale0 * a.w + scale1 * b.w; return out; }; Quat.sqlerp = function sqlerp(out, a, b, c, d, t) { Quat.slerp(qt_1, a, d, t); Quat.slerp(qt_2, b, c, t); Quat.slerp(out, qt_1, qt_2, 2 * t * (1 - t)); return out; }; Quat.invert = function invert(out, a) { var dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; var invDot = dot ? 1 / dot : 0; out.x = -a.x * invDot; out.y = -a.y * invDot; out.z = -a.z * invDot; out.w = a.w * invDot; return out; }; Quat.conjugate = function conjugate(out, a) { out.x = -a.x; out.y = -a.y; out.z = -a.z; out.w = a.w; return out; }; Quat.len = function len(a) { return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); }; Quat.lengthSqr = function lengthSqr(a) { return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; }; Quat.normalize = function normalize(out, a) { var len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; if (len > 0) { len = 1 / Math.sqrt(len); out.x = a.x * len; out.y = a.y * len; out.z = a.z * len; out.w = a.w * len; } return out; }; Quat.fromAxes = function fromAxes(out, xAxis, yAxis, zAxis) { _mat["default"].set(m3_1, xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, zAxis.x, zAxis.y, zAxis.z); return Quat.normalize(out, Quat.fromMat3(out, m3_1)); }; Quat.fromViewUp = function fromViewUp(out, view, up) { _mat["default"].fromViewUp(m3_1, view, up); return Quat.normalize(out, Quat.fromMat3(out, m3_1)); }; Quat.fromAxisAngle = function fromAxisAngle(out, axis, rad) { rad *= .5; var s = Math.sin(rad); out.x = s * axis.x; out.y = s * axis.y; out.z = s * axis.z; out.w = Math.cos(rad); return out; }; Quat.fromAngleZ = function fromAngleZ(out, z) { z *= halfToRad; out.x = out.y = 0; out.z = Math.sin(z); out.w = Math.cos(z); return out; }; Quat.fromMat3 = function fromMat3(out, mat) { var m = mat.m; var m00 = m[0], m10 = m[1], m20 = m[2], m01 = m[3], m11 = m[4], m21 = m[5], m02 = m[6], m12 = m[7], m22 = m[8]; var trace = m00 + m11 + m22; if (trace > 0) { var s = .5 / Math.sqrt(trace + 1); out.w = .25 / s; out.x = (m21 - m12) * s; out.y = (m02 - m20) * s; out.z = (m10 - m01) * s; } else if (m00 > m11 && m00 > m22) { var _s = 2 * Math.sqrt(1 + m00 - m11 - m22); out.w = (m21 - m12) / _s; out.x = .25 * _s; out.y = (m01 + m10) / _s; out.z = (m02 + m20) / _s; } else if (m11 > m22) { var _s2 = 2 * Math.sqrt(1 + m11 - m00 - m22); out.w = (m02 - m20) / _s2; out.x = (m01 + m10) / _s2; out.y = .25 * _s2; out.z = (m12 + m21) / _s2; } else { var _s3 = 2 * Math.sqrt(1 + m22 - m00 - m11); out.w = (m10 - m01) / _s3; out.x = (m02 + m20) / _s3; out.y = (m12 + m21) / _s3; out.z = .25 * _s3; } return out; }; Quat.fromEuler = function fromEuler(out, x, y, z) { x *= halfToRad; y *= halfToRad; z *= halfToRad; var sx = Math.sin(x); var cx = Math.cos(x); var sy = Math.sin(y); var cy = Math.cos(y); var sz = Math.sin(z); var cz = Math.cos(z); out.x = sx * cy * cz + cx * sy * sz; out.y = cx * sy * cz + sx * cy * sz; out.z = cx * cy * sz - sx * sy * cz; out.w = cx * cy * cz - sx * sy * sz; return out; }; Quat.toAxisX = function toAxisX(out, q) { var fy = 2 * q.y; var fz = 2 * q.z; out.x = 1 - fy * q.y - fz * q.z; out.y = fy * q.x + fz * q.w; out.z = fz * q.x + fy * q.w; return out; }; Quat.toAxisY = function toAxisY(out, q) { var fx = 2 * q.x; var fy = 2 * q.y; var fz = 2 * q.z; out.x = fy * q.x - fz * q.w; out.y = 1 - fx * q.x - fz * q.z; out.z = fz * q.y + fx * q.w; return out; }; Quat.toAxisZ = function toAxisZ(out, q) { var fx = 2 * q.x; var fy = 2 * q.y; var fz = 2 * q.z; out.x = fz * q.x - fy * q.w; out.y = fz * q.y - fx * q.w; out.z = 1 - fx * q.x - fy * q.y; return out; }; Quat.toEuler = function toEuler(out, q, outerZ) { var x = q.x, y = q.y, z = q.z, w = q.w; var bank = 0; var heading = 0; var attitude = 0; var test = x * y + z * w; if (test > .499999) { bank = 0; heading = (0, _utils.toDegree)(2 * Math.atan2(x, w)); attitude = 90; } else if (test < -.499999) { bank = 0; heading = -(0, _utils.toDegree)(2 * Math.atan2(x, w)); attitude = -90; } else { var sqx = x * x; var sqy = y * y; var sqz = z * z; bank = (0, _utils.toDegree)(Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz)); heading = (0, _utils.toDegree)(Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz)); attitude = (0, _utils.toDegree)(Math.asin(2 * test)); if (outerZ) { bank = -180 * Math.sign(bank + 1e-6) + bank; heading = -180 * Math.sign(heading + 1e-6) + heading; attitude = 180 * Math.sign(attitude + 1e-6) - attitude; } } out.x = bank; out.y = heading; out.z = attitude; return out; }; Quat.strictEquals = function strictEquals(a, b) { return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; }; Quat.equals = function equals(a, b, epsilon) { void 0 === epsilon && (epsilon = _utils.EPSILON); return Math.abs(a.x - b.x) <= epsilon * Math.max(1, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1, Math.abs(a.w), Math.abs(b.w)); }; Quat.toArray = function toArray(out, q, ofs) { void 0 === ofs && (ofs = 0); out[ofs + 0] = q.x; out[ofs + 1] = q.y; out[ofs + 2] = q.z; out[ofs + 3] = q.w; return out; }; Quat.fromArray = function fromArray(out, arr, ofs) { void 0 === ofs && (ofs = 0); out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; out.z = arr[ofs + 2]; out.w = arr[ofs + 3]; return out; }; function Quat(x, y, z, w) { var _this; void 0 === x && (x = 0); void 0 === y && (y = 0); void 0 === z && (z = 0); void 0 === w && (w = 1); _this = _ValueType.call(this) || this; _this.x = void 0; _this.y = void 0; _this.z = void 0; _this.w = void 0; if (x && "object" === typeof x) { _this.x = x.x; _this.y = x.y; _this.z = x.z; _this.w = x.w; } else { _this.x = x; _this.y = y; _this.z = z; _this.w = w; } return _this; } _proto.clone = function clone() { return new Quat(this.x, this.y, this.z, this.w); }; _proto.set = function set(newValue) { this.x = newValue.x; this.y = newValue.y; this.z = newValue.z; this.w = newValue.w; return this; }; _proto.equals = function equals(other) { return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; }; _proto.toEuler = function toEuler(out) { return Quat.toEuler(out, this); }; _proto.fromEuler = function fromEuler(euler) { return Quat.fromEuler(this, euler.x, euler.y, euler.z); }; _proto.lerp = function lerp(to, ratio, out) { out = out || new Quat(); Quat.slerp(out, this, to, ratio); return out; }; _proto.multiply = function multiply(other) { return Quat.multiply(this, this, other); }; _proto.rotateAround = function rotateAround(rot, axis, rad, out) { out = out || new Quat(); return Quat.rotateAround(out, rot, axis, rad); }; return Quat; })(_valueType["default"]); exports["default"] = Quat; Quat.mul = Quat.multiply; Quat.scale = Quat.multiplyScalar; Quat.mag = Quat.len; Quat.IDENTITY = Object.freeze(new Quat()); var qt_1 = new Quat(); var qt_2 = new Quat(); var v3_1 = new _vec["default"](); var m3_1 = new _mat["default"](); var halfToRad = .5 * Math.PI / 180; _CCClass["default"].fastDefine("cc.Quat", Quat, { x: 0, y: 0, z: 0, w: 1 }); cc.quat = function quat(x, y, z, w) { return new Quat(x, y, z, w); }; cc.Quat = Quat; module.exports = exports["default"]; }), { "../platform/CCClass": 129, "./mat3": 233, "./utils": 239, "./value-type": 240, "./vec3": 242 } ], 236: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueType = _interopRequireDefault(require("./value-type")); var _CCClass = _interopRequireDefault(require("../platform/CCClass")); var _vec = _interopRequireDefault(require("./vec2")); var _size = _interopRequireDefault(require("./size")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Rect = (function(_ValueType) { _inheritsLoose(Rect, _ValueType); Rect.fromMinMax = function fromMinMax(v1, v2) { var min_x = Math.min(v1.x, v2.x); var min_y = Math.min(v1.y, v2.y); var max_x = Math.max(v1.x, v2.x); var max_y = Math.max(v1.y, v2.y); return new Rect(min_x, min_y, max_x - min_x, max_y - min_y); }; function Rect(x, y, w, h) { var _this; void 0 === x && (x = 0); void 0 === y && (y = 0); void 0 === w && (w = 0); void 0 === h && (h = 0); _this = _ValueType.call(this) || this; _this.x = void 0; _this.y = void 0; _this.width = void 0; _this.height = void 0; if (x && "object" === typeof x) { y = x.y; w = x.width; h = x.height; x = x.x; } _this.x = x || 0; _this.y = y || 0; _this.width = w || 0; _this.height = h || 0; return _this; } var _proto = Rect.prototype; _proto.clone = function clone() { return new Rect(this.x, this.y, this.width, this.height); }; _proto.equals = function equals(other) { return other && this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height; }; _proto.lerp = function lerp(to, ratio, out) { out = out || new Rect(); var x = this.x; var y = this.y; var width = this.width; var height = this.height; out.x = x + (to.x - x) * ratio; out.y = y + (to.y - y) * ratio; out.width = width + (to.width - width) * ratio; out.height = height + (to.height - height) * ratio; return out; }; _proto.set = function set(source) { this.x = source.x; this.y = source.y; this.width = source.width; this.height = source.height; return this; }; _proto.intersects = function intersects(rect) { var maxax = this.x + this.width, maxay = this.y + this.height, maxbx = rect.x + rect.width, maxby = rect.y + rect.height; return !(maxax < rect.x || maxbx < this.x || maxay < rect.y || maxby < this.y); }; _proto.intersection = function intersection(out, rectB) { var axMin = this.x, ayMin = this.y, axMax = this.x + this.width, ayMax = this.y + this.height; var bxMin = rectB.x, byMin = rectB.y, bxMax = rectB.x + rectB.width, byMax = rectB.y + rectB.height; out.x = Math.max(axMin, bxMin); out.y = Math.max(ayMin, byMin); out.width = Math.min(axMax, bxMax) - out.x; out.height = Math.min(ayMax, byMax) - out.y; return out; }; _proto.contains = function contains(point) { return this.x <= point.x && this.x + this.width >= point.x && this.y <= point.y && this.y + this.height >= point.y; }; _proto.containsRect = function containsRect(rect) { return this.x <= rect.x && this.x + this.width >= rect.x + rect.width && this.y <= rect.y && this.y + this.height >= rect.y + rect.height; }; _proto.union = function union(out, rectB) { var ax = this.x, ay = this.y, aw = this.width, ah = this.height; var bx = rectB.x, by = rectB.y, bw = rectB.width, bh = rectB.height; out.x = Math.min(ax, bx); out.y = Math.min(ay, by); out.width = Math.max(ax + aw, bx + bw) - out.x; out.height = Math.max(ay + ah, by + bh) - out.y; return out; }; _proto.transformMat4 = function transformMat4(out, mat) { var ol = this.x; var ob = this.y; var or = ol + this.width; var ot = ob + this.height; var matm = mat.m; var lbx = matm[0] * ol + matm[4] * ob + matm[12]; var lby = matm[1] * ol + matm[5] * ob + matm[13]; var rbx = matm[0] * or + matm[4] * ob + matm[12]; var rby = matm[1] * or + matm[5] * ob + matm[13]; var ltx = matm[0] * ol + matm[4] * ot + matm[12]; var lty = matm[1] * ol + matm[5] * ot + matm[13]; var rtx = matm[0] * or + matm[4] * ot + matm[12]; var rty = matm[1] * or + matm[5] * ot + matm[13]; var minX = Math.min(lbx, rbx, ltx, rtx); var maxX = Math.max(lbx, rbx, ltx, rtx); var minY = Math.min(lby, rby, lty, rty); var maxY = Math.max(lby, rby, lty, rty); out.x = minX; out.y = minY; out.width = maxX - minX; out.height = maxY - minY; return out; }; _proto.toString = function toString() { return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")"; }; _createClass(Rect, [ { key: "xMin", get: function get() { return this.x; }, set: function set(v) { this.width += this.x - v; this.x = v; } }, { key: "yMin", get: function get() { return this.y; }, set: function set(v) { this.height += this.y - v; this.y = v; } }, { key: "xMax", get: function get() { return this.x + this.width; }, set: function set(value) { this.width = value - this.x; } }, { key: "yMax", get: function get() { return this.y + this.height; }, set: function set(value) { this.height = value - this.y; } }, { key: "center", get: function get() { return new _vec["default"](this.x + .5 * this.width, this.y + .5 * this.height); }, set: function set(value) { this.x = value.x - .5 * this.width; this.y = value.y - .5 * this.height; } }, { key: "origin", get: function get() { return new _vec["default"](this.x, this.y); }, set: function set(value) { this.x = value.x; this.y = value.y; } }, { key: "size", get: function get() { return new _size["default"](this.width, this.height); }, set: function set(value) { this.width = value.width; this.height = value.height; } } ]); return Rect; })(_valueType["default"]); exports["default"] = Rect; _CCClass["default"].fastDefine("cc.Rect", Rect, { x: 0, y: 0, width: 0, height: 0 }); cc.Rect = Rect; cc.rect = function rect(x, y, w, h) { return new Rect(x, y, w, h); }; module.exports = exports["default"]; }), { "../platform/CCClass": 129, "./size": 237, "./value-type": 240, "./vec2": 241 } ], 237: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueType = _interopRequireDefault(require("./value-type")); var _CCClass = _interopRequireDefault(require("../platform/CCClass")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Size = (function(_ValueType) { _inheritsLoose(Size, _ValueType); function Size(width, height) { var _this; void 0 === width && (width = 0); void 0 === height && (height = 0); _this = _ValueType.call(this) || this; _this.width = void 0; _this.height = void 0; if (width && "object" === typeof width) { _this.width = width.width; _this.height = width.height; } else { _this.width = width || 0; _this.height = height || 0; } return _this; } var _proto = Size.prototype; _proto.clone = function clone() { return new Size(this.width, this.height); }; _proto.equals = function equals(other) { return other && this.width === other.width && this.height === other.height; }; _proto.lerp = function lerp(to, ratio, out) { out = out || new Size(); var width = this.width; var height = this.height; out.width = width + (to.width - width) * ratio; out.height = height + (to.height - height) * ratio; return out; }; _proto.set = function set(source) { this.width = source.width; this.height = source.height; return this; }; _proto.toString = function toString() { return "(" + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")"; }; _createClass(Size, null, [ { key: "ZERO", get: function get() { return new Size(); } } ]); return Size; })(_valueType["default"]); exports["default"] = Size; Size.ZERO_R = Size.ZERO; _CCClass["default"].fastDefine("cc.Size", Size, { width: 0, height: 0 }); cc.size = function(w, h) { return new Size(w, h); }; cc.Size = Size; module.exports = exports["default"]; }), { "../platform/CCClass": 129, "./value-type": 240 } ], 238: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _quat = _interopRequireDefault(require("./quat")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var tmp_quat = new _quat["default"](); var Trs = (function() { function Trs() {} Trs.toRotation = function toRotation(out, a) { out.x = a[3]; out.y = a[4]; out.z = a[5]; out.w = a[6]; return out; }; Trs.fromRotation = function fromRotation(out, a) { out[3] = a.x; out[4] = a.y; out[5] = a.z; out[6] = a.w; return out; }; Trs.toEuler = function toEuler(out, a) { Trs.toRotation(tmp_quat, a); _quat["default"].toEuler(out, tmp_quat); return out; }; Trs.fromEuler = function fromEuler(out, a) { _quat["default"].fromEuler(tmp_quat, a.x, a.y, a.z); Trs.fromRotation(out, tmp_quat); return out; }; Trs.fromEulerNumber = function fromEulerNumber(out, x, y, z) { _quat["default"].fromEuler(tmp_quat, x, y, z); Trs.fromRotation(out, tmp_quat); return out; }; Trs.toScale = function toScale(out, a) { out.x = a[7]; out.y = a[8]; out.z = a[9]; return out; }; Trs.fromScale = function fromScale(out, a) { out[7] = a.x; out[8] = a.y; out[9] = a.z; return out; }; Trs.toPosition = function toPosition(out, a) { out.x = a[0]; out.y = a[1]; out.z = a[2]; return out; }; Trs.fromPosition = function fromPosition(out, a) { out[0] = a.x; out[1] = a.y; out[2] = a.z; return out; }; Trs.fromAngleZ = function fromAngleZ(out, a) { _quat["default"].fromAngleZ(tmp_quat, a); Trs.fromRotation(out, tmp_quat); return out; }; Trs.toMat4 = function toMat4(out, trs) { var x = trs[3], y = trs[4], z = trs[5], w = trs[6]; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var xy = x * y2; var xz = x * z2; var yy = y * y2; var yz = y * z2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; var sx = trs[7]; var sy = trs[8]; var sz = trs[9]; var m = out.m; m[0] = (1 - (yy + zz)) * sx; m[1] = (xy + wz) * sx; m[2] = (xz - wy) * sx; m[3] = 0; m[4] = (xy - wz) * sy; m[5] = (1 - (xx + zz)) * sy; m[6] = (yz + wx) * sy; m[7] = 0; m[8] = (xz + wy) * sz; m[9] = (yz - wx) * sz; m[10] = (1 - (xx + yy)) * sz; m[11] = 0; m[12] = trs[0]; m[13] = trs[1]; m[14] = trs[2]; m[15] = 1; return out; }; return Trs; })(); exports["default"] = Trs; cc.Trs = Trs; module.exports = exports["default"]; }), { "./quat": 235 } ], 239: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.INT_MIN = exports.INT_MAX = exports.INT_BITS = exports.FLOAT_BYTES = exports.FLOAT_ARRAY_TYPE = exports.EPSILON = void 0; exports.approx = approx; exports.clamp = clamp; exports.clamp01 = clamp01; exports.equals = equals; exports.inverseLerp = inverseLerp; exports.lerp = lerp; exports.nextPow2 = nextPow2; exports.pingPong = pingPong; exports.pseudoRandom = pseudoRandom; exports.pseudoRandomRange = pseudoRandomRange; exports.pseudoRandomRangeInt = pseudoRandomRangeInt; exports.random = void 0; exports.randomRange = randomRange; exports.randomRangeInt = randomRangeInt; exports.repeat = repeat; exports.sign = sign; exports.toDegree = toDegree; exports.toRadian = toRadian; var _d2r = Math.PI / 180; var _r2d = 180 / Math.PI; var EPSILON = 1e-6; exports.EPSILON = EPSILON; var INT_BITS = 32; exports.INT_BITS = INT_BITS; var INT_MAX = 2147483647; exports.INT_MAX = INT_MAX; var INT_MIN = -1 << INT_BITS - 1; exports.INT_MIN = INT_MIN; var FLOAT_ARRAY_TYPE = Float64Array; exports.FLOAT_ARRAY_TYPE = FLOAT_ARRAY_TYPE; var FLOAT_BYTES = 8; exports.FLOAT_BYTES = FLOAT_BYTES; function equals(a, b) { return Math.abs(a - b) <= EPSILON * Math.max(1, Math.abs(a), Math.abs(b)); } function approx(a, b, maxDiff) { maxDiff = maxDiff || EPSILON; return Math.abs(a - b) <= maxDiff; } function clamp(val, min, max) { return val < min ? min : val > max ? max : val; } function clamp01(val) { return val < 0 ? 0 : val > 1 ? 1 : val; } function lerp(from, to, ratio) { return from + (to - from) * ratio; } function toRadian(a) { return a * _d2r; } function toDegree(a) { return a * _r2d; } var random = Math.random; exports.random = random; function randomRange(min, max) { return Math.random() * (max - min) + min; } function randomRangeInt(min, max) { return Math.floor(randomRange(min, max)); } function pseudoRandom(seed) { seed = (9301 * seed + 49297) % 233280; return seed / 233280; } function pseudoRandomRange(seed, min, max) { return pseudoRandom(seed) * (max - min) + min; } function pseudoRandomRangeInt(seed, min, max) { return Math.floor(pseudoRandomRange(seed, min, max)); } function nextPow2(val) { --val; val |= val >> 1; val |= val >> 2; val |= val >> 4; val |= val >> 8; val |= val >> 16; ++val; return val; } function repeat(t, length) { return t - Math.floor(t / length) * length; } function pingPong(t, length) { t = repeat(t, 2 * length); t = length - Math.abs(t - length); return t; } function inverseLerp(from, to, value) { return (value - from) / (to - from); } function sign(v) { return (v > 0) - (v < 0); } }), {} ], 240: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _js = _interopRequireDefault(require("../platform/js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ValueType = (function() { function ValueType() {} var _proto = ValueType.prototype; _proto.clone = function clone() { cc.errorID("0100", _js["default"].getClassName(this) + ".clone"); return null; }; _proto.equals = function equals(other) { cc.errorID("0100", _js["default"].getClassName(this) + ".equals"); return false; }; _proto.lerp = function lerp(to, ratio) { cc.errorID("0100", _js["default"].getClassName(this) + ".lerp"); return this.clone(); }; _proto.set = function set(source) { cc.errorID("0100", _js["default"].getClassName(this) + ".set"); }; _proto.toString = function toString() { return "" + {}; }; return ValueType; })(); exports["default"] = ValueType; _js["default"].setClassName("cc.ValueType", ValueType); cc.ValueType = ValueType; module.exports = exports["default"]; }), { "../platform/js": 150 } ], 241: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueType = _interopRequireDefault(require("./value-type")); var _CCClass = _interopRequireDefault(require("../platform/CCClass")); var _misc = _interopRequireDefault(require("../utils/misc")); var _utils = require("./utils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _x = 0; var _y = 0; var Vec2 = (function(_ValueType) { _inheritsLoose(Vec2, _ValueType); var _proto = Vec2.prototype; _proto.sub = function sub(vector, out) { return Vec2.subtract(out || new Vec2(), this, vector); }; _proto.mul = function mul(num, out) { return Vec2.multiplyScalar(out || new Vec2(), this, num); }; _proto.div = function div(num, out) { return Vec2.multiplyScalar(out || new Vec2(), this, 1 / num); }; _proto.scale = function scale(vector, out) { return Vec2.multiply(out || new Vec2(), this, vector); }; _proto.neg = function neg(out) { return Vec2.negate(out || new Vec2(), this); }; Vec2.clone = function clone(a) { return new Vec2(a.x, a.y); }; Vec2.copy = function copy(out, a) { out.x = a.x; out.y = a.y; return out; }; Vec2.set = function set(out, x, y) { out.x = x; out.y = y; return out; }; Vec2.add = function add(out, a, b) { out.x = a.x + b.x; out.y = a.y + b.y; return out; }; Vec2.subtract = function subtract(out, a, b) { out.x = a.x - b.x; out.y = a.y - b.y; return out; }; Vec2.multiply = function multiply(out, a, b) { out.x = a.x * b.x; out.y = a.y * b.y; return out; }; Vec2.divide = function divide(out, a, b) { out.x = a.x / b.x; out.y = a.y / b.y; return out; }; Vec2.ceil = function ceil(out, a) { out.x = Math.ceil(a.x); out.y = Math.ceil(a.y); return out; }; Vec2.floor = function floor(out, a) { out.x = Math.floor(a.x); out.y = Math.floor(a.y); return out; }; Vec2.min = function min(out, a, b) { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); return out; }; Vec2.max = function max(out, a, b) { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); return out; }; Vec2.round = function round(out, a) { out.x = Math.round(a.x); out.y = Math.round(a.y); return out; }; Vec2.multiplyScalar = function multiplyScalar(out, a, b) { out.x = a.x * b; out.y = a.y * b; return out; }; Vec2.scaleAndAdd = function scaleAndAdd(out, a, b, scale) { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; return out; }; Vec2.distance = function distance(a, b) { _x = b.x - a.x; _y = b.y - a.y; return Math.sqrt(_x * _x + _y * _y); }; Vec2.squaredDistance = function squaredDistance(a, b) { _x = b.x - a.x; _y = b.y - a.y; return _x * _x + _y * _y; }; Vec2.len = function len(a) { _x = a.x; _y = a.y; return Math.sqrt(_x * _x + _y * _y); }; Vec2.lengthSqr = function lengthSqr(a) { _x = a.x; _y = a.y; return _x * _x + _y * _y; }; Vec2.negate = function negate(out, a) { out.x = -a.x; out.y = -a.y; return out; }; Vec2.inverse = function inverse(out, a) { out.x = 1 / a.x; out.y = 1 / a.y; return out; }; Vec2.inverseSafe = function inverseSafe(out, a) { _x = a.x; _y = a.y; Math.abs(_x) < _utils.EPSILON ? out.x = 0 : out.x = 1 / _x; Math.abs(_y) < _utils.EPSILON ? out.y = 0 : out.y = 1 / _y; return out; }; Vec2.normalize = function normalize(out, a) { _x = a.x; _y = a.y; var len = _x * _x + _y * _y; if (len > 0) { len = 1 / Math.sqrt(len); out.x = _x * len; out.y = _y * len; } return out; }; Vec2.dot = function dot(a, b) { return a.x * b.x + a.y * b.y; }; Vec2.cross = function cross(out, a, b) { out.x = out.y = 0; out.z = a.x * b.y - a.y * b.x; return out; }; Vec2.lerp = function lerp(out, a, b, t) { _x = a.x; _y = a.y; out.x = _x + t * (b.x - _x); out.y = _y + t * (b.y - _y); return out; }; Vec2.random = function random(out, scale) { scale = scale || 1; var r = 2 * (0, _utils.random)() * Math.PI; out.x = Math.cos(r) * scale; out.y = Math.sin(r) * scale; return out; }; Vec2.transformMat3 = function transformMat3(out, a, mat) { _x = a.x; _y = a.y; var m = mat.m; out.x = m[0] * _x + m[3] * _y + m[6]; out.y = m[1] * _x + m[4] * _y + m[7]; return out; }; Vec2.transformMat4 = function transformMat4(out, a, mat) { _x = a.x; _y = a.y; var m = mat.m; out.x = m[0] * _x + m[4] * _y + m[12]; out.y = m[1] * _x + m[5] * _y + m[13]; return out; }; Vec2.strictEquals = function strictEquals(a, b) { return a.x === b.x && a.y === b.y; }; Vec2.equals = function equals(a, b, epsilon) { void 0 === epsilon && (epsilon = _utils.EPSILON); return Math.abs(a.x - b.x) <= epsilon * Math.max(1, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1, Math.abs(a.y), Math.abs(b.y)); }; Vec2.angle = function angle(a, b) { Vec2.normalize(v2_1, a); Vec2.normalize(v2_2, b); var cosine = Vec2.dot(v2_1, v2_2); if (cosine > 1) return 0; if (cosine < -1) return Math.PI; return Math.acos(cosine); }; Vec2.toArray = function toArray(out, v, ofs) { void 0 === ofs && (ofs = 0); out[ofs + 0] = v.x; out[ofs + 1] = v.y; return out; }; Vec2.fromArray = function fromArray(out, arr, ofs) { void 0 === ofs && (ofs = 0); out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; return out; }; function Vec2(x, y) { var _this; void 0 === x && (x = 0); void 0 === y && (y = 0); _this = _ValueType.call(this) || this; _this.mag = Vec2.prototype.len; _this.magSqr = Vec2.prototype.lengthSqr; _this.subSelf = Vec2.prototype.subtract; _this.mulSelf = Vec2.prototype.multiplyScalar; _this.divSelf = Vec2.prototype.divide; _this.scaleSelf = Vec2.prototype.multiply; _this.negSelf = Vec2.prototype.negate; _this.x = void 0; _this.y = void 0; _this.z = 0; if (x && "object" === typeof x) { _this.x = x.x || 0; _this.y = x.y || 0; } else { _this.x = x || 0; _this.y = y || 0; } return _this; } _proto.clone = function clone() { return new Vec2(this.x, this.y); }; _proto.set = function set(newValue) { this.x = newValue.x; this.y = newValue.y; return this; }; _proto.equals = function equals(other) { return other && this.x === other.x && this.y === other.y; }; _proto.fuzzyEquals = function fuzzyEquals(other, variance) { if (this.x - variance <= other.x && other.x <= this.x + variance && this.y - variance <= other.y && other.y <= this.y + variance) return true; return false; }; _proto.toString = function toString() { return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ")"; }; _proto.lerp = function lerp(to, ratio, out) { out = out || new Vec2(); var x = this.x; var y = this.y; out.x = x + (to.x - x) * ratio; out.y = y + (to.y - y) * ratio; return out; }; _proto.clampf = function clampf(min_inclusive, max_inclusive) { this.x = _misc["default"].clampf(this.x, min_inclusive.x, max_inclusive.x); this.y = _misc["default"].clampf(this.y, min_inclusive.y, max_inclusive.y); return this; }; _proto.add = function add(vector, out) { out = out || new Vec2(); out.x = this.x + vector.x; out.y = this.y + vector.y; return out; }; _proto.addSelf = function addSelf(vector) { this.x += vector.x; this.y += vector.y; return this; }; _proto.subtract = function subtract(vector) { this.x -= vector.x; this.y -= vector.y; return this; }; _proto.multiplyScalar = function multiplyScalar(num) { this.x *= num; this.y *= num; return this; }; _proto.multiply = function multiply(vector) { this.x *= vector.x; this.y *= vector.y; return this; }; _proto.divide = function divide(num) { this.x /= num; this.y /= num; return this; }; _proto.negate = function negate() { this.x = -this.x; this.y = -this.y; return this; }; _proto.dot = function dot(vector) { return this.x * vector.x + this.y * vector.y; }; _proto.cross = function cross(vector) { return this.x * vector.y - this.y * vector.x; }; _proto.len = function len() { return Math.sqrt(this.x * this.x + this.y * this.y); }; _proto.lengthSqr = function lengthSqr() { return this.x * this.x + this.y * this.y; }; _proto.normalizeSelf = function normalizeSelf() { var magSqr = this.x * this.x + this.y * this.y; if (1 === magSqr) return this; if (0 === magSqr) return this; var invsqrt = 1 / Math.sqrt(magSqr); this.x *= invsqrt; this.y *= invsqrt; return this; }; _proto.normalize = function normalize(out) { out = out || new Vec2(); out.x = this.x; out.y = this.y; out.normalizeSelf(); return out; }; _proto.angle = function angle(vector) { var magSqr1 = this.magSqr(); var magSqr2 = vector.magSqr(); if (0 === magSqr1 || 0 === magSqr2) { console.warn("Can't get angle between zero vector"); return 0; } var dot = this.dot(vector); var theta = dot / Math.sqrt(magSqr1 * magSqr2); theta = _misc["default"].clampf(theta, -1, 1); return Math.acos(theta); }; _proto.signAngle = function signAngle(vector) { var angle = this.angle(vector); return this.cross(vector) < 0 ? -angle : angle; }; _proto.rotate = function rotate(radians, out) { out = out || new Vec2(); out.x = this.x; out.y = this.y; return out.rotateSelf(radians); }; _proto.rotateSelf = function rotateSelf(radians) { var sin = Math.sin(radians); var cos = Math.cos(radians); var x = this.x; this.x = cos * x - sin * this.y; this.y = sin * x + cos * this.y; return this; }; _proto.project = function project(vector) { return vector.multiplyScalar(this.dot(vector) / vector.dot(vector)); }; _proto.transformMat4 = function transformMat4(m, out) { out = out || new Vec2(); Vec2.transformMat4(out, this, m); return out; }; _proto.maxAxis = function maxAxis() { return Math.max(this.x, this.y); }; _createClass(Vec2, null, [ { key: "ONE", get: function get() { return new Vec2(1, 1); } }, { key: "ZERO", get: function get() { return new Vec2(0, 0); } }, { key: "UP", get: function get() { return new Vec2(0, 1); } }, { key: "RIGHT", get: function get() { return new Vec2(1, 0); } } ]); return Vec2; })(_valueType["default"]); exports["default"] = Vec2; Vec2.sub = Vec2.subtract; Vec2.mul = Vec2.multiply; Vec2.scale = Vec2.multiplyScalar; Vec2.mag = Vec2.len; Vec2.squaredMagnitude = Vec2.lengthSqr; Vec2.div = Vec2.divide; Vec2.ONE_R = Vec2.ONE; Vec2.ZERO_R = Vec2.ZERO; Vec2.UP_R = Vec2.UP; Vec2.RIGHT_R = Vec2.RIGHT; var v2_1 = new Vec2(); var v2_2 = new Vec2(); _CCClass["default"].fastDefine("cc.Vec2", Vec2, { x: 0, y: 0 }); cc.v2 = function v2(x, y) { return new Vec2(x, y); }; cc.Vec2 = Vec2; module.exports = exports["default"]; }), { "../platform/CCClass": 129, "../utils/misc": 217, "./utils": 239, "./value-type": 240 } ], 242: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueType = _interopRequireDefault(require("./value-type")); var _CCClass = _interopRequireDefault(require("../platform/CCClass")); var _misc = _interopRequireDefault(require("../utils/misc")); var _vec = _interopRequireDefault(require("./vec2")); var _utils = require("./utils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _x = 0; var _y = 0; var _z = 0; var Vec3 = (function(_ValueType) { _inheritsLoose(Vec3, _ValueType); var _proto = Vec3.prototype; _proto.sub = function sub(vector, out) { return Vec3.subtract(out || new Vec3(), this, vector); }; _proto.mul = function mul(num, out) { return Vec3.multiplyScalar(out || new Vec3(), this, num); }; _proto.div = function div(num, out) { return Vec3.multiplyScalar(out || new Vec3(), this, 1 / num); }; _proto.scale = function scale(vector, out) { return Vec3.multiply(out || new Vec3(), this, vector); }; _proto.neg = function neg(out) { return Vec3.negate(out || new Vec3(), this); }; Vec3.zero = function zero(out) { out.x = 0; out.y = 0; out.z = 0; return out; }; Vec3.clone = function clone(a) { return new Vec3(a.x, a.y, a.z); }; Vec3.copy = function copy(out, a) { out.x = a.x; out.y = a.y; out.z = a.z; return out; }; Vec3.set = function set(out, x, y, z) { out.x = x; out.y = y; out.z = z; return out; }; Vec3.add = function add(out, a, b) { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; return out; }; Vec3.subtract = function subtract(out, a, b) { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; return out; }; Vec3.multiply = function multiply(out, a, b) { out.x = a.x * b.x; out.y = a.y * b.y; out.z = a.z * b.z; return out; }; Vec3.divide = function divide(out, a, b) { out.x = a.x / b.x; out.y = a.y / b.y; out.z = a.z / b.z; return out; }; Vec3.ceil = function ceil(out, a) { out.x = Math.ceil(a.x); out.y = Math.ceil(a.y); out.z = Math.ceil(a.z); return out; }; Vec3.floor = function floor(out, a) { out.x = Math.floor(a.x); out.y = Math.floor(a.y); out.z = Math.floor(a.z); return out; }; Vec3.min = function min(out, a, b) { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); out.z = Math.min(a.z, b.z); return out; }; Vec3.max = function max(out, a, b) { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); out.z = Math.max(a.z, b.z); return out; }; Vec3.round = function round(out, a) { out.x = Math.round(a.x); out.y = Math.round(a.y); out.z = Math.round(a.z); return out; }; Vec3.multiplyScalar = function multiplyScalar(out, a, b) { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; return out; }; Vec3.scaleAndAdd = function scaleAndAdd(out, a, b, scale) { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale; return out; }; Vec3.distance = function distance(a, b) { _x = b.x - a.x; _y = b.y - a.y; _z = b.z - a.z; return Math.sqrt(_x * _x + _y * _y + _z * _z); }; Vec3.squaredDistance = function squaredDistance(a, b) { _x = b.x - a.x; _y = b.y - a.y; _z = b.z - a.z; return _x * _x + _y * _y + _z * _z; }; Vec3.len = function len(a) { _x = a.x; _y = a.y; _z = a.z; return Math.sqrt(_x * _x + _y * _y + _z * _z); }; Vec3.lengthSqr = function lengthSqr(a) { _x = a.x; _y = a.y; _z = a.z; return _x * _x + _y * _y + _z * _z; }; Vec3.negate = function negate(out, a) { out.x = -a.x; out.y = -a.y; out.z = -a.z; return out; }; Vec3.inverse = function inverse(out, a) { out.x = 1 / a.x; out.y = 1 / a.y; out.z = 1 / a.z; return out; }; Vec3.inverseSafe = function inverseSafe(out, a) { _x = a.x; _y = a.y; _z = a.z; Math.abs(_x) < _utils.EPSILON ? out.x = 0 : out.x = 1 / _x; Math.abs(_y) < _utils.EPSILON ? out.y = 0 : out.y = 1 / _y; Math.abs(_z) < _utils.EPSILON ? out.z = 0 : out.z = 1 / _z; return out; }; Vec3.normalize = function normalize(out, a) { _x = a.x; _y = a.y; _z = a.z; var len = _x * _x + _y * _y + _z * _z; if (len > 0) { len = 1 / Math.sqrt(len); out.x = _x * len; out.y = _y * len; out.z = _z * len; } return out; }; Vec3.dot = function dot(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; }; Vec3.cross = function cross(out, a, b) { var ax = a.x, ay = a.y, az = a.z; var bx = b.x, by = b.y, bz = b.z; out.x = ay * bz - az * by; out.y = az * bx - ax * bz; out.z = ax * by - ay * bx; return out; }; Vec3.lerp = function lerp(out, a, b, t) { out.x = a.x + t * (b.x - a.x); out.y = a.y + t * (b.y - a.y); out.z = a.z + t * (b.z - a.z); return out; }; Vec3.random = function random(out, scale) { scale = scale || 1; var phi = 2 * (0, _utils.random)() * Math.PI; var cosTheta = 2 * (0, _utils.random)() - 1; var sinTheta = Math.sqrt(1 - cosTheta * cosTheta); out.x = sinTheta * Math.cos(phi) * scale; out.y = sinTheta * Math.sin(phi) * scale; out.z = cosTheta * scale; return out; }; Vec3.transformMat4 = function transformMat4(out, a, mat) { _x = a.x; _y = a.y; _z = a.z; var m = mat.m; var rhw = m[3] * _x + m[7] * _y + m[11] * _z + m[15]; rhw = rhw ? 1 / rhw : 1; out.x = (m[0] * _x + m[4] * _y + m[8] * _z + m[12]) * rhw; out.y = (m[1] * _x + m[5] * _y + m[9] * _z + m[13]) * rhw; out.z = (m[2] * _x + m[6] * _y + m[10] * _z + m[14]) * rhw; return out; }; Vec3.transformMat4Normal = function transformMat4Normal(out, a, mat) { _x = a.x; _y = a.y; _z = a.z; var m = mat.m; var rhw = m[3] * _x + m[7] * _y + m[11] * _z; rhw = rhw ? 1 / rhw : 1; out.x = (m[0] * _x + m[4] * _y + m[8] * _z) * rhw; out.y = (m[1] * _x + m[5] * _y + m[9] * _z) * rhw; out.z = (m[2] * _x + m[6] * _y + m[10] * _z) * rhw; return out; }; Vec3.transformMat3 = function transformMat3(out, a, mat) { _x = a.x; _y = a.y; _z = a.z; var m = mat.m; out.x = _x * m[0] + _y * m[3] + _z * m[6]; out.y = _x * m[1] + _y * m[4] + _z * m[7]; out.z = _x * m[2] + _y * m[5] + _z * m[8]; return out; }; Vec3.transformAffine = function transformAffine(out, v, mat) { _x = v.x; _y = v.y; _z = v.z; var m = mat.m; out.x = m[0] * _x + m[1] * _y + m[2] * _z + m[3]; out.y = m[4] * _x + m[5] * _y + m[6] * _z + m[7]; out.x = m[8] * _x + m[9] * _y + m[10] * _z + m[11]; return out; }; Vec3.transformQuat = function transformQuat(out, a, q) { var ix = q.w * a.x + q.y * a.z - q.z * a.y; var iy = q.w * a.y + q.z * a.x - q.x * a.z; var iz = q.w * a.z + q.x * a.y - q.y * a.x; var iw = -q.x * a.x - q.y * a.y - q.z * a.z; out.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y; out.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z; out.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x; return out; }; Vec3.transformRTS = function transformRTS(out, a, r, t, s) { var x = a.x * s.x; var y = a.y * s.y; var z = a.z * s.z; var ix = r.w * x + r.y * z - r.z * y; var iy = r.w * y + r.z * x - r.x * z; var iz = r.w * z + r.x * y - r.y * x; var iw = -r.x * x - r.y * y - r.z * z; out.x = ix * r.w + iw * -r.x + iy * -r.z - iz * -r.y + t.x; out.y = iy * r.w + iw * -r.y + iz * -r.x - ix * -r.z + t.y; out.z = iz * r.w + iw * -r.z + ix * -r.y - iy * -r.x + t.z; return out; }; Vec3.transformInverseRTS = function transformInverseRTS(out, a, r, t, s) { var x = a.x - t.x; var y = a.y - t.y; var z = a.z - t.z; var ix = r.w * x - r.y * z + r.z * y; var iy = r.w * y - r.z * x + r.x * z; var iz = r.w * z - r.x * y + r.y * x; var iw = r.x * x + r.y * y + r.z * z; out.x = (ix * r.w + iw * r.x + iy * r.z - iz * r.y) / s.x; out.y = (iy * r.w + iw * r.y + iz * r.x - ix * r.z) / s.y; out.z = (iz * r.w + iw * r.z + ix * r.y - iy * r.x) / s.z; return out; }; Vec3.rotateX = function rotateX(out, v, o, a) { _x = v.x - o.x; _y = v.y - o.y; _z = v.z - o.z; var cos = Math.cos(a); var sin = Math.sin(a); var rx = _x; var ry = _y * cos - _z * sin; var rz = _y * sin + _z * cos; out.x = rx + o.x; out.y = ry + o.y; out.z = rz + o.z; return out; }; Vec3.rotateY = function rotateY(out, v, o, a) { _x = v.x - o.x; _y = v.y - o.y; _z = v.z - o.z; var cos = Math.cos(a); var sin = Math.sin(a); var rx = _z * sin + _x * cos; var ry = _y; var rz = _z * cos - _x * sin; out.x = rx + o.x; out.y = ry + o.y; out.z = rz + o.z; return out; }; Vec3.rotateZ = function rotateZ(out, v, o, a) { _x = v.x - o.x; _y = v.y - o.y; _z = v.z - o.z; var cos = Math.cos(a); var sin = Math.sin(a); var rx = _x * cos - _y * sin; var ry = _x * sin + _y * cos; var rz = _z; out.x = rx + o.x; out.y = ry + o.y; out.z = rz + o.z; return out; }; Vec3.strictEquals = function strictEquals(a, b) { return a.x === b.x && a.y === b.y && a.z === b.z; }; Vec3.equals = function equals(a, b, epsilon) { void 0 === epsilon && (epsilon = _utils.EPSILON); var a0 = a.x, a1 = a.y, a2 = a.z; var b0 = b.x, b1 = b.y, b2 = b.z; return Math.abs(a0 - b0) <= epsilon * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= epsilon * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= epsilon * Math.max(1, Math.abs(a2), Math.abs(b2)); }; Vec3.angle = function angle(a, b) { Vec3.normalize(v3_1, a); Vec3.normalize(v3_2, b); var cosine = Vec3.dot(v3_1, v3_2); if (cosine > 1) return 0; if (cosine < -1) return Math.PI; return Math.acos(cosine); }; Vec3.projectOnPlane = function projectOnPlane(out, a, n) { return Vec3.subtract(out, a, Vec3.project(out, a, n)); }; Vec3.project = function project(out, a, b) { var sqrLen = Vec3.lengthSqr(b); return sqrLen < 1e-6 ? Vec3.set(out, 0, 0, 0) : Vec3.multiplyScalar(out, b, Vec3.dot(a, b) / sqrLen); }; Vec3.toArray = function toArray(out, v, ofs) { void 0 === ofs && (ofs = 0); out[ofs + 0] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; return out; }; Vec3.fromArray = function fromArray(out, arr, ofs) { void 0 === ofs && (ofs = 0); out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; out.z = arr[ofs + 2]; return out; }; function Vec3(x, y, z) { var _this; void 0 === x && (x = 0); void 0 === y && (y = 0); void 0 === z && (z = 0); _this = _ValueType.call(this) || this; _this.mag = Vec3.prototype.len; _this.magSqr = Vec3.prototype.lengthSqr; _this.subSelf = Vec3.prototype.subtract; _this.mulSelf = Vec3.prototype.multiplyScalar; _this.divSelf = Vec3.prototype.divide; _this.scaleSelf = Vec3.prototype.multiply; _this.negSelf = Vec3.prototype.negate; _this.x = void 0; _this.y = void 0; _this.z = void 0; _this.angle = _vec["default"].prototype.angle; _this.project = _vec["default"].prototype.project; if (x && "object" === typeof x) { _this.x = x.x; _this.y = x.y; _this.z = x.z; } else { _this.x = x; _this.y = y; _this.z = z; } return _this; } _proto.clone = function clone() { return new Vec3(this.x, this.y, this.z); }; _proto.set = function set(newValue) { this.x = newValue.x; this.y = newValue.y; this.z = newValue.z; return this; }; _proto.equals = function equals(other) { return other && this.x === other.x && this.y === other.y && this.z === other.z; }; _proto.fuzzyEquals = function fuzzyEquals(other, variance) { if (this.x - variance <= other.x && other.x <= this.x + variance && this.y - variance <= other.y && other.y <= this.y + variance && this.z - variance <= other.z && other.z <= this.z + variance) return true; return false; }; _proto.toString = function toString() { return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ")"; }; _proto.lerp = function lerp(to, ratio, out) { out = out || new Vec3(); Vec3.lerp(out, this, to, ratio); return out; }; _proto.clampf = function clampf(min_inclusive, max_inclusive) { this.x = _misc["default"].clampf(this.x, min_inclusive.x, max_inclusive.x); this.y = _misc["default"].clampf(this.y, min_inclusive.y, max_inclusive.y); this.z = _misc["default"].clampf(this.z, min_inclusive.z, max_inclusive.z); return this; }; _proto.addSelf = function addSelf(vector) { this.x += vector.x; this.y += vector.y; this.z += vector.z; return this; }; _proto.add = function add(vector, out) { out = out || new Vec3(); out.x = this.x + vector.x; out.y = this.y + vector.y; out.z = this.z + vector.z; return out; }; _proto.subtract = function subtract(vector) { this.x -= vector.x; this.y -= vector.y; this.z -= vector.z; return this; }; _proto.multiplyScalar = function multiplyScalar(num) { this.x *= num; this.y *= num; this.z *= num; return this; }; _proto.multiply = function multiply(vector) { this.x *= vector.x; this.y *= vector.y; this.z *= vector.z; return this; }; _proto.divide = function divide(num) { this.x /= num; this.y /= num; this.z /= num; return this; }; _proto.negate = function negate() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; _proto.dot = function dot(vector) { return this.x * vector.x + this.y * vector.y + this.z * vector.z; }; _proto.cross = function cross(vector, out) { out = out || new Vec3(); Vec3.cross(out, this, vector); return out; }; _proto.len = function len() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }; _proto.lengthSqr = function lengthSqr() { return this.x * this.x + this.y * this.y + this.z * this.z; }; _proto.normalizeSelf = function normalizeSelf() { Vec3.normalize(this, this); return this; }; _proto.normalize = function normalize(out) { out = out || new Vec3(); Vec3.normalize(out, this); return out; }; _proto.transformMat4 = function transformMat4(m, out) { out = out || new Vec3(); Vec3.transformMat4(out, this, m); return out; }; _proto.maxAxis = function maxAxis() { return Math.max(this.x, this.y, this.z); }; _proto.signAngle = function signAngle(vector) { cc.warnID(1408, "vec3.signAngle", "v2.1", "cc.v2(selfVector).signAngle(vector)"); var vec1 = new _vec["default"](this.x, this.y); var vec2 = new _vec["default"](vector.x, vector.y); return vec1.signAngle(vec2); }; _proto.rotate = function rotate(radians, out) { cc.warnID(1408, "vec3.rotate", "v2.1", "cc.v2(selfVector).rotate(radians, out)"); return _vec["default"].prototype.rotate.call(this, radians, out); }; _proto.rotateSelf = function rotateSelf(radians) { cc.warnID(1408, "vec3.rotateSelf", "v2.1", "cc.v2(selfVector).rotateSelf(radians)"); return _vec["default"].prototype.rotateSelf.call(this, radians); }; _createClass(Vec3, null, [ { key: "ONE", get: function get() { return new Vec3(1, 1, 1); } }, { key: "ZERO", get: function get() { return new Vec3(); } }, { key: "UP", get: function get() { return new Vec3(0, 1, 0); } }, { key: "RIGHT", get: function get() { return new Vec3(1, 0, 0); } }, { key: "FORWARD", get: function get() { return new Vec3(0, 0, 1); } } ]); return Vec3; })(_valueType["default"]); exports["default"] = Vec3; Vec3.sub = Vec3.subtract; Vec3.mul = Vec3.multiply; Vec3.scale = Vec3.multiplyScalar; Vec3.mag = Vec3.len; Vec3.squaredMagnitude = Vec3.lengthSqr; Vec3.div = Vec3.divide; Vec3.ONE_R = Vec3.ONE; Vec3.ZERO_R = Vec3.ZERO; Vec3.UP_R = Vec3.UP; Vec3.RIGHT_R = Vec3.RIGHT; Vec3.FRONT_R = Vec3.FORWARD; var v3_1 = new Vec3(); var v3_2 = new Vec3(); _CCClass["default"].fastDefine("cc.Vec3", Vec3, { x: 0, y: 0, z: 0 }); cc.v3 = function v3(x, y, z) { return new Vec3(x, y, z); }; cc.Vec3 = Vec3; module.exports = exports["default"]; }), { "../platform/CCClass": 129, "../utils/misc": 217, "./utils": 239, "./value-type": 240, "./vec2": 241 } ], 243: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; exports.v4 = v4; var _CCClass = _interopRequireDefault(require("../platform/CCClass")); var _valueType = _interopRequireDefault(require("./value-type")); var _utils = require("./utils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _x = 0; var _y = 0; var _z = 0; var _w = 0; var Vec4 = (function(_ValueType) { _inheritsLoose(Vec4, _ValueType); var _proto = Vec4.prototype; _proto.sub = function sub(vector, out) { return Vec4.subtract(out || new Vec4(), this, vector); }; _proto.mul = function mul(num, out) { return Vec4.multiplyScalar(out || new Vec4(), this, num); }; _proto.div = function div(num, out) { return Vec4.multiplyScalar(out || new Vec4(), this, 1 / num); }; _proto.scale = function scale(vector, out) { return Vec4.multiply(out || new Vec4(), this, vector); }; _proto.neg = function neg(out) { return Vec4.negate(out || new Vec4(), this); }; Vec4.clone = function clone(a) { return new Vec4(a.x, a.y, a.z, a.w); }; Vec4.copy = function copy(out, a) { out.x = a.x; out.y = a.y; out.z = a.z; out.w = a.w; return out; }; Vec4.set = function set(out, x, y, z, w) { out.x = x; out.y = y; out.z = z; out.w = w; return out; }; Vec4.add = function add(out, a, b) { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; out.w = a.w + b.w; return out; }; Vec4.subtract = function subtract(out, a, b) { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; out.w = a.w - b.w; return out; }; Vec4.multiply = function multiply(out, a, b) { out.x = a.x * b.x; out.y = a.y * b.y; out.z = a.z * b.z; out.w = a.w * b.w; return out; }; Vec4.divide = function divide(out, a, b) { out.x = a.x / b.x; out.y = a.y / b.y; out.z = a.z / b.z; out.w = a.w / b.w; return out; }; Vec4.ceil = function ceil(out, a) { out.x = Math.ceil(a.x); out.y = Math.ceil(a.y); out.z = Math.ceil(a.z); out.w = Math.ceil(a.w); return out; }; Vec4.floor = function floor(out, a) { out.x = Math.floor(a.x); out.y = Math.floor(a.y); out.z = Math.floor(a.z); out.w = Math.floor(a.w); return out; }; Vec4.min = function min(out, a, b) { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); out.z = Math.min(a.z, b.z); out.w = Math.min(a.w, b.w); return out; }; Vec4.max = function max(out, a, b) { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); out.z = Math.max(a.z, b.z); out.w = Math.max(a.w, b.w); return out; }; Vec4.round = function round(out, a) { out.x = Math.round(a.x); out.y = Math.round(a.y); out.z = Math.round(a.z); out.w = Math.round(a.w); return out; }; Vec4.multiplyScalar = function multiplyScalar(out, a, b) { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; out.w = a.w * b; return out; }; Vec4.scaleAndAdd = function scaleAndAdd(out, a, b, scale) { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale; out.w = a.w + b.w * scale; return out; }; Vec4.distance = function distance(a, b) { var x = b.x - a.x; var y = b.y - a.y; var z = b.z - a.z; var w = b.w - a.w; return Math.sqrt(x * x + y * y + z * z + w * w); }; Vec4.squaredDistance = function squaredDistance(a, b) { var x = b.x - a.x; var y = b.y - a.y; var z = b.z - a.z; var w = b.w - a.w; return x * x + y * y + z * z + w * w; }; Vec4.len = function len(a) { _x = a.x; _y = a.y; _z = a.z; _w = a.w; return Math.sqrt(_x * _x + _y * _y + _z * _z + _w * _w); }; Vec4.lengthSqr = function lengthSqr(a) { _x = a.x; _y = a.y; _z = a.z; _w = a.w; return _x * _x + _y * _y + _z * _z + _w * _w; }; Vec4.negate = function negate(out, a) { out.x = -a.x; out.y = -a.y; out.z = -a.z; out.w = -a.w; return out; }; Vec4.inverse = function inverse(out, a) { out.x = 1 / a.x; out.y = 1 / a.y; out.z = 1 / a.z; out.w = 1 / a.w; return out; }; Vec4.inverseSafe = function inverseSafe(out, a) { _x = a.x; _y = a.y; _z = a.z; _w = a.w; Math.abs(_x) < _utils.EPSILON ? out.x = 0 : out.x = 1 / _x; Math.abs(_y) < _utils.EPSILON ? out.y = 0 : out.y = 1 / _y; Math.abs(_z) < _utils.EPSILON ? out.z = 0 : out.z = 1 / _z; Math.abs(_w) < _utils.EPSILON ? out.w = 0 : out.w = 1 / _w; return out; }; Vec4.normalize = function normalize(out, a) { _x = a.x; _y = a.y; _z = a.z; _w = a.w; var len = _x * _x + _y * _y + _z * _z + _w * _w; if (len > 0) { len = 1 / Math.sqrt(len); out.x = _x * len; out.y = _y * len; out.z = _z * len; out.w = _w * len; } return out; }; Vec4.dot = function dot(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }; Vec4.lerp = function lerp(out, a, b, t) { out.x = a.x + t * (b.x - a.x); out.y = a.y + t * (b.y - a.y); out.z = a.z + t * (b.z - a.z); out.w = a.w + t * (b.w - a.w); return out; }; Vec4.random = function random(out, scale) { scale = scale || 1; var phi = 2 * (0, _utils.random)() * Math.PI; var cosTheta = 2 * (0, _utils.random)() - 1; var sinTheta = Math.sqrt(1 - cosTheta * cosTheta); out.x = sinTheta * Math.cos(phi) * scale; out.y = sinTheta * Math.sin(phi) * scale; out.z = cosTheta * scale; out.w = 0; return out; }; Vec4.transformMat4 = function transformMat4(out, a, mat) { _x = a.x; _y = a.y; _z = a.z; _w = a.w; var m = mat.m; out.x = m[0] * _x + m[4] * _y + m[8] * _z + m[12] * _w; out.y = m[1] * _x + m[5] * _y + m[9] * _z + m[13] * _w; out.z = m[2] * _x + m[6] * _y + m[10] * _z + m[14] * _w; out.w = m[3] * _x + m[7] * _y + m[11] * _z + m[15] * _w; return out; }; Vec4.transformAffine = function transformAffine(out, v, mat) { _x = v.x; _y = v.y; _z = v.z; _w = v.w; var m = mat.m; out.x = m[0] * _x + m[1] * _y + m[2] * _z + m[3] * _w; out.y = m[4] * _x + m[5] * _y + m[6] * _z + m[7] * _w; out.x = m[8] * _x + m[9] * _y + m[10] * _z + m[11] * _w; out.w = v.w; return out; }; Vec4.transformQuat = function transformQuat(out, a, q) { var x = a.x, y = a.y, z = a.z; _x = q.x; _y = q.y; _z = q.z; _w = q.w; var ix = _w * x + _y * z - _z * y; var iy = _w * y + _z * x - _x * z; var iz = _w * z + _x * y - _y * x; var iw = -_x * x - _y * y - _z * z; out.x = ix * _w + iw * -_x + iy * -_z - iz * -_y; out.y = iy * _w + iw * -_y + iz * -_x - ix * -_z; out.z = iz * _w + iw * -_z + ix * -_y - iy * -_x; out.w = a.w; return out; }; Vec4.strictEquals = function strictEquals(a, b) { return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; }; Vec4.equals = function equals(a, b, epsilon) { void 0 === epsilon && (epsilon = _utils.EPSILON); return Math.abs(a.x - b.x) <= epsilon * Math.max(1, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1, Math.abs(a.w), Math.abs(b.w)); }; Vec4.toArray = function toArray(out, v, ofs) { void 0 === ofs && (ofs = 0); out[ofs + 0] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; out[ofs + 3] = v.w; return out; }; Vec4.fromArray = function fromArray(out, arr, ofs) { void 0 === ofs && (ofs = 0); out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; out.z = arr[ofs + 2]; out.w = arr[ofs + 3]; return out; }; function Vec4(x, y, z, w) { var _this; void 0 === x && (x = 0); void 0 === y && (y = 0); void 0 === z && (z = 0); void 0 === w && (w = 0); _this = _ValueType.call(this) || this; _this.mag = Vec4.prototype.len; _this.magSqr = Vec4.prototype.lengthSqr; _this.subSelf = Vec4.prototype.subtract; _this.mulSelf = Vec4.prototype.multiplyScalar; _this.divSelf = Vec4.prototype.divide; _this.scaleSelf = Vec4.prototype.multiply; _this.negSelf = Vec4.prototype.negate; _this.x = void 0; _this.y = void 0; _this.z = void 0; _this.w = void 0; if (x && "object" === typeof x) { _this.x = x.x; _this.y = x.y; _this.z = x.z; _this.w = x.w; } else { _this.x = x; _this.y = y; _this.z = z; _this.w = w; } return _this; } _proto.clone = function clone() { return new Vec4(this.x, this.y, this.z, this.w); }; _proto.set = function set(x, y, z, w) { if (x && "object" === typeof x) { this.x = x.x; this.y = x.y; this.z = x.z; this.w = x.w; } else { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 0; } return this; }; _proto.equals = function equals(other, epsilon) { void 0 === epsilon && (epsilon = _utils.EPSILON); return Math.abs(this.x - other.x) <= epsilon * Math.max(1, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1, Math.abs(this.z), Math.abs(other.z)) && Math.abs(this.w - other.w) <= epsilon * Math.max(1, Math.abs(this.w), Math.abs(other.w)); }; _proto.equals4f = function equals4f(x, y, z, w, epsilon) { void 0 === epsilon && (epsilon = _utils.EPSILON); return Math.abs(this.x - x) <= epsilon * Math.max(1, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1, Math.abs(this.y), Math.abs(y)) && Math.abs(this.z - z) <= epsilon * Math.max(1, Math.abs(this.z), Math.abs(z)) && Math.abs(this.w - w) <= epsilon * Math.max(1, Math.abs(this.w), Math.abs(w)); }; _proto.strictEquals = function strictEquals(other) { return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; }; _proto.strictEquals4f = function strictEquals4f(x, y, z, w) { return this.x === x && this.y === y && this.z === z && this.w === w; }; _proto.lerp = function lerp(to, ratio) { _x = this.x; _y = this.y; _z = this.z; _w = this.w; this.x = _x + ratio * (to.x - _x); this.y = _y + ratio * (to.y - _y); this.z = _z + ratio * (to.z - _z); this.w = _w + ratio * (to.w - _w); return this; }; _proto.toString = function toString() { return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ", " + this.w.toFixed(2) + ")"; }; _proto.clampf = function clampf(minInclusive, maxInclusive) { this.x = (0, _utils.clamp)(this.x, minInclusive.x, maxInclusive.x); this.y = (0, _utils.clamp)(this.y, minInclusive.y, maxInclusive.y); this.z = (0, _utils.clamp)(this.z, minInclusive.z, maxInclusive.z); this.w = (0, _utils.clamp)(this.w, minInclusive.w, maxInclusive.w); return this; }; _proto.addSelf = function addSelf(vector) { this.x += vector.x; this.y += vector.y; this.z += vector.z; this.w += vector.w; return this; }; _proto.add = function add(vector, out) { out = out || new Vec4(); out.x = this.x + vector.x; out.y = this.y + vector.y; out.z = this.z + vector.z; out.w = this.w + vector.w; return out; }; _proto.subtract = function subtract(vector, out) { out = out || new Vec4(); out.x = this.x - vector.x; out.y = this.y - vector.y; out.z = this.z - vector.z; out.w = this.w - vector.w; return out; }; _proto.multiplyScalar = function multiplyScalar(num) { this.x *= num; this.y *= num; this.z *= num; this.w *= num; return this; }; _proto.multiply = function multiply(vector) { this.x *= vector.x; this.y *= vector.y; this.z *= vector.z; this.w *= vector.w; return this; }; _proto.divide = function divide(num) { this.x /= num; this.y /= num; this.z /= num; this.w /= num; return this; }; _proto.negate = function negate() { this.x = -this.x; this.y = -this.y; this.z = -this.z; this.w = -this.w; return this; }; _proto.dot = function dot(vector) { return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w; }; _proto.cross = function cross(vector, out) { out = out || new Vec4(); var ax = this.x, ay = this.y, az = this.z; var bx = vector.x, by = vector.y, bz = vector.z; out.x = ay * bz - az * by; out.y = az * bx - ax * bz; out.z = ax * by - ay * bx; return out; }; _proto.len = function len() { var x = this.x, y = this.y, z = this.z, w = this.w; return Math.sqrt(x * x + y * y + z * z + w * w); }; _proto.lengthSqr = function lengthSqr() { var x = this.x, y = this.y, z = this.z, w = this.w; return x * x + y * y + z * z + w * w; }; _proto.normalizeSelf = function normalizeSelf() { this.normalize(this); return this; }; _proto.normalize = function normalize(out) { out = out || new Vec4(); _x = this.x; _y = this.y; _z = this.z; _w = this.w; var len = _x * _x + _y * _y + _z * _z + _w * _w; if (len > 0) { len = 1 / Math.sqrt(len); out.x = _x * len; out.y = _y * len; out.z = _z * len; out.w = _w * len; } return out; }; _proto.transformMat4 = function transformMat4(matrix, out) { out = out || new Vec4(); _x = this.x; _y = this.y; _z = this.z; _w = this.w; var m = matrix.m; out.x = m[0] * _x + m[4] * _y + m[8] * _z + m[12] * _w; out.y = m[1] * _x + m[5] * _y + m[9] * _z + m[13] * _w; out.z = m[2] * _x + m[6] * _y + m[10] * _z + m[14] * _w; out.w = m[3] * _x + m[7] * _y + m[11] * _z + m[15] * _w; return out; }; _proto.maxAxis = function maxAxis() { return Math.max(this.x, this.y, this.z, this.w); }; _createClass(Vec4, null, [ { key: "ZERO", get: function get() { return new Vec4(0, 0, 0, 0); } }, { key: "ONE", get: function get() { return new Vec4(1, 1, 1, 1); } }, { key: "NEG_ONE", get: function get() { return new Vec4(-1, -1, -1, -1); } } ]); return Vec4; })(_valueType["default"]); exports["default"] = Vec4; Vec4.sub = Vec4.subtract; Vec4.mul = Vec4.multiply; Vec4.div = Vec4.divide; Vec4.scale = Vec4.multiplyScalar; Vec4.mag = Vec4.len; Vec4.squaredMagnitude = Vec4.lengthSqr; Vec4.ZERO_R = Vec4.ZERO; Vec4.ONE_R = Vec4.ONE; Vec4.NEG_ONE_R = Vec4.NEG_ONE; _CCClass["default"].fastDefine("cc.Vec4", Vec4, { x: 0, y: 0, z: 0, w: 0 }); function v4(x, y, z, w) { return new Vec4(x, y, z, w); } cc.v4 = v4; cc.Vec4 = Vec4; }), { "../platform/CCClass": 129, "./utils": 239, "./value-type": 240 } ], 244: [ (function(require, module, exports) { "use strict"; var js = cc.js; true; var deprecateEnum = function deprecateEnum(obj, oldPath, newPath, hasTypePrefixBefore) { false; hasTypePrefixBefore = false !== hasTypePrefixBefore; var enumDef = Function("return " + newPath)(); var entries = cc.Enum.getList(enumDef); var delimiter = hasTypePrefixBefore ? "_" : "."; for (var i = 0; i < entries.length; i++) { var entry = entries[i].name; var oldPropName; if (hasTypePrefixBefore) { var oldTypeName = oldPath.split(".").slice(-1)[0]; oldPropName = oldTypeName + "_" + entry; } else oldPropName = entry; js.get(obj, oldPropName, function(entry) { cc.errorID(1400, oldPath + delimiter + entry, newPath + "." + entry); return enumDef[entry]; }.bind(null, entry)); } }; var markAsRemoved = function markAsRemoved(ownerCtor, removedProps, ownerName) { if (!ownerCtor) return; ownerName = ownerName || js.getClassName(ownerCtor); removedProps.forEach((function(prop) { function error() { cc.errorID(1406, ownerName, prop); } js.getset(ownerCtor.prototype, prop, error, error); })); }; var markAsDeprecated = function markAsDeprecated(ownerCtor, deprecatedProps, ownerName) { if (!ownerCtor) return; ownerName = ownerName || js.getClassName(ownerCtor); var descriptors = Object.getOwnPropertyDescriptors(ownerCtor.prototype); deprecatedProps.forEach((function(prop) { var deprecatedProp = prop[0]; var newProp = prop[1]; var descriptor = descriptors[deprecatedProp]; js.getset(ownerCtor.prototype, deprecatedProp, (function() { cc.warnID(1400, ownerName + "." + deprecatedProp, ownerName + "." + newProp); return descriptor.get.call(this); }), (function(v) { cc.warnID(1400, ownerName + "." + deprecatedProp, ownerName + "." + newProp); descriptor.set.call(this, v); })); })); }; var markAsRemovedInObject = function markAsRemovedInObject(ownerObj, removedProps, ownerName) { if (!ownerObj) return; removedProps.forEach((function(prop) { function error() { cc.errorID(1406, ownerName, prop); } js.getset(ownerObj, prop, error); })); }; var provideClearError = function provideClearError(owner, obj, ownerName) { if (!owner) return; var className = ownerName || cc.js.getClassName(owner); var Info = "Sorry, " + className + ".%s is removed, please use %s instead."; var _loop = function _loop() { function define(prop, getset) { function accessor(newProp) { cc.error(Info, prop, newProp); } Array.isArray(getset) || (getset = getset.split(",").map((function(x) { return x.trim(); }))); try { js.getset(owner, prop, accessor.bind(null, getset[0]), getset[1] && accessor.bind(null, getset[1])); } catch (e) {} } getset = obj[prop]; if ("*" === prop[0]) { etProp = prop.slice(1); define("g" + etProp, getset); define("s" + etProp, getset); } else prop.split(",").map((function(x) { return x.trim(); })).forEach((function(x) { define(x, getset); })); }; for (var prop in obj) { var getset; var etProp; _loop(); } }; var markFunctionWarning = function markFunctionWarning(ownerCtor, obj, ownerName) { if (!ownerCtor) return; ownerName = ownerName || js.getClassName(ownerCtor); for (var prop in obj) (function() { var propName = prop; var originFunc = ownerCtor[propName]; if (!originFunc) return; function warn() { cc.warn("Sorry, %s.%s is deprecated. Please use %s instead", ownerName, propName, obj[propName]); return originFunc.apply(this, arguments); } ownerCtor[propName] = warn; })(); }; js.get(cc, "info", (function() { cc.errorID(1400, "cc.info", "cc.log"); return cc.log; })); js.get(cc, "spriteFrameCache", (function() { cc.errorID(1404); })); js.get(cc, "vmath", (function() { cc.warnID(1400, "cc.vmath", "cc.math"); return cc.math; })); js.get(cc.math, "vec2", (function() { cc.warnID(1400, "cc.vmath.vec2", "cc.Vec2"); return cc.Vec2; })); js.get(cc.math, "vec3", (function() { cc.warnID(1400, "cc.vmath.vec3", "cc.Vec3"); return cc.Vec3; })); js.get(cc.math, "vec4", (function() { cc.warnID(1400, "cc.vmath.vec4", "cc.Vec4"); return cc.Vec4; })); js.get(cc.math, "mat4", (function() { cc.warnID(1400, "cc.vmath.mat4", "cc.Mat4"); return cc.Mat4; })); js.get(cc.math, "mat3", (function() { cc.warnID(1400, "cc.vmath.mat3", "cc.Mat3"); return cc.Mat3; })); js.get(cc.math, "quat", (function() { cc.warnID(1400, "cc.vmath.quat", "cc.Quat"); return cc.Quat; })); js.get(cc.SpriteFrame.prototype, "_textureLoaded", (function() { cc.errorID(1400, "spriteFrame._textureLoaded", "spriteFrame.textureLoaded()"); return this.textureLoaded(); })); markAsRemoved(cc.SpriteFrame, [ "addLoadedEventListener" ]); markFunctionWarning(cc.Sprite.prototype, { setState: "cc.Sprite.setMaterial", getState: "cc.Sprite.getMaterial" }, "cc.Sprite"); js.get(cc.SpriteFrame.prototype, "clearTexture", (function() { cc.errorID(1406, "cc.SpriteFrame", "clearTexture"); return function() {}; })); js.get(cc, "textureCache", (function() { cc.errorID(1406, "cc", "textureCache"); })); var Texture2D = cc.Texture2D; js.get(Texture2D.prototype, "releaseTexture", (function() { cc.errorID(1400, "texture.releaseTexture()", "texture.destroy()"); return this.destroy; })); js.get(Texture2D.prototype, "getName", (function() { cc.errorID(1400, "texture.getName()", "texture._glID"); return function() { return this._glID || null; }; })); js.get(Texture2D.prototype, "isLoaded", (function() { cc.errorID(1400, "texture.isLoaded function", "texture.loaded property"); return function() { return this.loaded; }; })); js.get(Texture2D.prototype, "setAntiAliasTexParameters", (function() { cc.errorID(1400, "texture.setAntiAliasTexParameters()", "texture.setFilters(cc.Texture2D.Filter.LINEAR, cc.Texture2D.Filter.LINEAR)"); return function() { this.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR); }; })); js.get(Texture2D.prototype, "setAliasTexParameters", (function() { cc.errorID(1400, "texture.setAntiAliasTexParameters()", "texture.setFilters(cc.Texture2D.Filter.NEAREST, cc.Texture2D.Filter.NEAREST)"); return function() { this.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); }; })); markAsRemovedInObject(cc.macro, [ "ENABLE_GL_STATE_CACHE", "FIX_ARTIFACTS_BY_STRECHING_TEXEL" ], "cc.macro"); provideClearError(cc.macro, { PI: "Math.PI", PI2: "Math.PI * 2", FLT_MAX: "Number.MAX_VALUE", FLT_MIN: "Number.MIN_VALUE", UINT_MAX: "Number.MAX_SAFE_INTEGER" }, "cc.macro"); markAsRemovedInObject(cc.game, [ "CONFIG_KEY" ], "cc.game"); markAsRemovedInObject(cc.sys, [ "dumpRoot", "cleanScript", "BROWSER_TYPE_WECHAT_GAME", "BROWSER_TYPE_WECHAT_GAME_SUB", "BROWSER_TYPE_BAIDU_GAME", "BROWSER_TYPE_BAIDU_GAME_SUB", "BROWSER_TYPE_XIAOMI_GAME", "BROWSER_TYPE_ALIPAY_GAME" ], "cc.sys"); provideClearError(cc.Director, { EVENT_PROJECTION_CHANGED: "", EVENT_BEFORE_VISIT: "EVENT_AFTER_UPDATE", EVENT_AFTER_VISIT: "EVENT_BEFORE_DRAW" }, "cc.Director"); markFunctionWarning(cc.Director.prototype, { convertToGL: "cc.view.convertToLocationInView", convertToUI: "", getWinSize: "cc.winSize", getWinSizeInPixels: "cc.winSize", getVisibleSize: "cc.view.getVisibleSize", getVisibleOrigin: "cc.view.getVisibleOrigin", purgeCachedData: "cc.assetManager.releaseAll", setDepthTest: "cc.Camera.main.depth", setClearColor: "cc.Camera.main.backgroundColor", getRunningScene: "cc.director.getScene", getAnimationInterval: "cc.game.getFrameRate", setAnimationInterval: "cc.game.setFrameRate", isDisplayStats: "cc.debug.isDisplayStats", setDisplayStats: "cc.debug.setDisplayStats", stopAnimation: "cc.game.pause", startAnimation: "cc.game.resume" }, "cc.Director"); markAsRemoved(cc.Director, [ "pushScene", "popScene", "popToRootScene", "popToSceneStackLevel", "setProjection", "getProjection" ], "cc.Director"); provideClearError(cc.Scheduler, { scheduleCallbackForTarget: "schedule", scheduleUpdateForTarget: "scheduleUpdate", unscheduleCallbackForTarget: "unschedule", unscheduleUpdateForTarget: "unscheduleUpdate", unscheduleAllCallbacksForTarget: "unscheduleAllForTarget", unscheduleAllCallbacks: "unscheduleAll", unscheduleAllCallbacksWithMinPriority: "unscheduleAllWithMinPriority" }, "cc.Scheduler"); provideClearError(cc.view, { adjustViewPort: "adjustViewportMeta", setViewPortInPoints: "setViewportInPoints", getViewPortRect: "getViewportRect" }, "cc.view"); markAsRemovedInObject(cc.view, [ "isViewReady", "setTargetDensityDPI", "getTargetDensityDPI", "setFrameZoomFactor", "canSetContentScaleFactor", "setContentTranslateLeftTop", "getContentTranslateLeftTop", "setViewName", "getViewName" ], "cc.view"); markAsRemoved(cc.PhysicsManager, [ "attachDebugDrawToCamera", "detachDebugDrawFromCamera" ]); markAsRemoved(cc.CollisionManager, [ "attachDebugDrawToCamera", "detachDebugDrawFromCamera" ]); provideClearError(cc._BaseNode.prototype, { tag: "name", getTag: "name", setTag: "name", getChildByTag: "getChildByName", removeChildByTag: "getChildByName(name).destroy()" }); markAsRemoved(cc.Node, [ "_cascadeColorEnabled", "cascadeColor", "isCascadeColorEnabled", "setCascadeColorEnabled", "_cascadeOpacityEnabled", "cascadeOpacity", "isCascadeOpacityEnabled", "setCascadeOpacityEnabled", "opacityModifyRGB", "isOpacityModifyRGB", "setOpacityModifyRGB", "ignoreAnchor", "isIgnoreAnchorPointForPosition", "ignoreAnchorPointForPosition", "isRunning", "_sgNode" ]); markFunctionWarning(cc.Node.prototype, { getNodeToParentTransform: "getLocalMatrix", getNodeToParentTransformAR: "getLocalMatrix", getNodeToWorldTransform: "getWorldMatrix", getNodeToWorldTransformAR: "getWorldMatrix", getParentToNodeTransform: "getLocalMatrix", getWorldToNodeTransform: "getWorldMatrix", convertTouchToNodeSpace: "convertToNodeSpaceAR", convertTouchToNodeSpaceAR: "convertToNodeSpaceAR", convertToWorldSpace: "convertToWorldSpaceAR", convertToNodeSpace: "convertToNodeSpaceAR" }); provideClearError(cc.Node.prototype, { getRotationX: "rotationX", setRotationX: "rotationX", getRotationY: "rotationY", setRotationY: "rotationY", getPositionX: "x", setPositionX: "x", getPositionY: "y", setPositionY: "y", getSkewX: "skewX", setSkewX: "skewX", getSkewY: "skewY", setSkewY: "skewY", getScaleX: "scaleX", setScaleX: "scaleX", getScaleY: "scaleY", setScaleY: "scaleY", getOpacity: "opacity", setOpacity: "opacity", getColor: "color", setColor: "color", getLocalZOrder: "zIndex", setLocalZOrder: "zIndex" }); provideClearError(cc.Sprite.prototype, { setInsetLeft: "cc.SpriteFrame insetLeft", setInsetRight: "cc.SpriteFrame insetRight", setInsetTop: "cc.SpriteFrame insetTop", setInsetBottom: "cc.SpriteFrame insetBottom" }); cc.Material.getInstantiatedBuiltinMaterial = cc.MaterialVariant.createWithBuiltin; cc.Material.getInstantiatedMaterial = cc.MaterialVariant.create; markFunctionWarning(cc.Material, { getInstantiatedBuiltinMaterial: "cc.MaterialVariant.createWithBuiltin", getInstantiatedMaterial: "cc.MaterialVariant.create" }); cc.js.getset(cc.RenderComponent.prototype, "sharedMaterials", (function() { cc.warnID(1400, "sharedMaterials", "getMaterials"); return this.materials; }), (function(v) { cc.warnID(1400, "sharedMaterials", "setMaterial"); this.materials = v; })); markFunctionWarning(cc.Follow.prototype, { setBoudarySet: "cc.Follow.setBoundarySet" }); markFunctionWarning(cc.Camera.prototype, { getNodeToCameraTransform: "getWorldToScreenMatrix2D", getCameraToWorldPoint: "getScreenToWorldPoint", getWorldToCameraPoint: "getWorldToScreenPoint", getCameraToWorldMatrix: "getScreenToWorldMatrix2D", getWorldToCameraMatrix: "getWorldToScreenMatrix2D" }); markAsRemoved(cc.Camera, [ "addTarget", "removeTarget", "getTargets" ]); var ERR = '"%s" is not defined in the Scene, it is only defined in normal nodes.'; false, Object.defineProperties(cc.Scene.prototype, { active: { get: function get() { cc.error(ERR, "active"); return true; }, set: function set() { cc.error(ERR, "active"); } }, activeInHierarchy: { get: function get() { cc.error(ERR, "activeInHierarchy"); return true; } }, getComponent: { get: function get() { cc.error(ERR, "getComponent"); return function() { return null; }; } }, addComponent: { get: function get() { cc.error(ERR, "addComponent"); return function() { return null; }; } } }); markAsRemovedInObject(cc.dynamicAtlasManager, [ "minFrameSize" ], "cc.dynamicAtlasManager"); cc.Light && markAsRemovedInObject(cc.Light.prototype, [ "shadowDepthScale" ], "cc.Light.prototype"); provideClearError(cc, { affineTransformMake: "cc.AffineTransform.create", affineTransformMakeIdentity: "cc.AffineTransform.identity", affineTransformClone: "cc.AffineTransform.clone", affineTransformConcat: "cc.AffineTransform.concat", affineTransformConcatIn: "cc.AffineTransform.concat", affineTransformInvert: "cc.AffineTransform.invert", affineTransformInvertIn: "cc.AffineTransform.invert", affineTransformInvertOut: "cc.AffineTransform.invert", affineTransformEqualToTransform: "cc.AffineTransform.equal", pointApplyAffineTransform: "cc.AffineTransform.transformVec2", sizeApplyAffineTransform: "cc.AffineTransform.transformSize", rectApplyAffineTransform: "cc.AffineTransform.transformRect", obbApplyAffineTransform: "cc.AffineTransform.transformObb", pointEqualToPoint: "cc.Vec2 equals", sizeEqualToSize: "cc.Size equals", rectEqualToRect: "rectA.equals(rectB)", rectContainsRect: "rectA.containsRect(rectB)", rectContainsPoint: "rect.contains(vec2)", rectOverlapsRect: "rectA.intersects(rectB)", rectIntersectsRect: "rectA.intersects(rectB)", rectIntersection: "rectA.intersection(intersection, rectB)", rectUnion: "rectA.union(union, rectB)", rectGetMaxX: "rect.xMax", rectGetMidX: "rect.center.x", rectGetMinX: "rect.xMin", rectGetMaxY: "rect.yMax", rectGetMidY: "rect.center.y", rectGetMinY: "rect.yMin", colorEqual: "colorA.equals(colorB)", hexToColor: "color.fromHEX(hexColor)", colorToHex: "color.toHEX()", TextAlignment: "cc.macro.TextAlignment", VerticalTextAlignment: "cc.macro.VerticalTextAlignment", pNeg: "p.neg()", pAdd: "p1.add(p2)", pSub: "p1.sub(p2)", pMult: "p.mul(factor)", pMidpoint: "p1.add(p2).mul(0.5)", pDot: "p1.dot(p2)", pCross: "p1.cross(p2)", pPerp: "p.rotate(-90 * Math.PI / 180)", pRPerp: "p.rotate(90 * Math.PI / 180)", pProject: "p1.project(p2)", pLengthSQ: "p.magSqr()", pDistanceSQ: "p1.sub(p2).magSqr()", pLength: "p.mag()", pDistance: "p1.sub(p2).mag()", pNormalize: "p.normalize()", pForAngle: "cc.v2(Math.cos(a), Math.sin(a))", pToAngle: "Math.atan2(v.y, v.x)", pZeroIn: "p.x = p.y = 0", pIn: "p1.set(p2)", pMultIn: "p.mulSelf(factor)", pSubIn: "p1.subSelf(p2)", pAddIn: "p1.addSelf(p2)", pNormalizeIn: "p.normalizeSelf()", pSameAs: "p1.equals(p2)", pAngle: "v1.angle(v2)", pAngleSigned: "v1.signAngle(v2)", pRotateByAngle: "p.rotate(radians)", pCompMult: "v1.multiply(v2)", pFuzzyEqual: "v1.fuzzyEquals(v2, tolerance)", pLerp: "p.lerp(endPoint, ratio)", pClamp: "p.clampf(min_inclusive, max_inclusive)", rand: "Math.random() * 0xffffff", randomMinus1To1: "(Math.random() - 0.5) * 2", container: "cc.game.container", _canvas: "cc.game.canvas", _renderType: "cc.game.renderType", _getError: "cc.debug.getError", _initDebugSetting: "cc.debug._resetDebugSetting", DebugMode: "cc.debug.DebugMode" }, "cc"); markAsRemovedInObject(cc, [ "blendFuncDisable", "pFromSize", "pCompOp", "pIntersectPoint", "pSegmentIntersect", "pLineIntersect", "obbApplyMatrix", "getImageFormatByData", "initEngine" ], "cc"); markFunctionWarning(cc, { p: "cc.v2" }, "cc"); provideClearError(cc.Rect, { contain: "rectA.contains(rectB)", transformMat4: "rect.transformMat4(out, mat4)" }); provideClearError(cc.Color, { rgb2hsv: "color.toHSV()", hsv2rgb: "color.fromHSV(h, s, v)" }); markFunctionWarning(cc.Color, { fromHex: "cc.Color.fromHEX" }); js.get(cc, "lerp", (function() { cc.errorID(1400, "cc.lerp", "cc.misc.lerp"); return cc.misc.lerp; })); js.get(cc, "random0To1", (function() { cc.errorID(1400, "cc.random0To1", "Math.random"); return Math.random; })); js.get(cc, "degreesToRadians", (function() { cc.errorID(1400, "cc.degreesToRadians", "cc.misc.degreesToRadians"); return cc.misc.degreesToRadians; })); js.get(cc, "radiansToDegrees", (function() { cc.errorID(1400, "cc.radiansToDegrees", "cc.misc.radiansToDegrees"); return cc.misc.radiansToDegrees; })); js.get(cc, "clampf", (function() { cc.errorID(1400, "cc.clampf", "cc.misc.clampf"); return cc.misc.clampf; })); js.get(cc, "clamp01", (function() { cc.errorID(1400, "cc.clamp01", "cc.misc.clamp01"); return cc.misc.clamp01; })); js.get(cc, "ImageFormat", (function() { cc.errorID(1400, "cc.ImageFormat", "cc.macro.ImageFormat"); return cc.macro.ImageFormat; })); js.get(cc, "KEY", (function() { cc.errorID(1400, "cc.KEY", "cc.macro.KEY"); return cc.macro.KEY; })); js.get(cc, "Easing", (function() { cc.errorID(1400, "cc.Easing", "cc.easing"); return cc.easing; })); js.get(cc, "isChildClassOf", (function() { cc.errorID(1400, "cc.isChildClassOf", "cc.js.isChildClassOf"); return cc.js.isChildClassOf; })); "object" === typeof dragonBones && "undefined" !== typeof dragonBones.CCFactory && js.get(dragonBones.CCFactory, "getFactory", (function() { cc.errorID(1400, "dragonBones.CCFactory.getFactory", "dragonBones.CCFactory.getInstance"); return dragonBones.CCFactory.getInstance; })); cc.renderer.renderEngine = { get gfx() { cc.warnID(1400, "cc.renderer.renderEngine.gfx", "cc.gfx"); return cc.gfx; }, get math() { cc.warnID(1400, "cc.renderer.renderEngine.math", "cc.math"); return cc.vmath; }, get InputAssembler() { cc.warnID(1400, "cc.renderer.renderEngine.InputAssembler", "cc.renderer.InputAssembler"); return cc.renderer.InputAssembler; } }; markAsRemovedInObject(cc.audioEngine, [ "getProfile", "preload", "setMaxWebAudioSize" ], "cc.audioEngine"); }), {} ], 245: [ (function(require, module, exports) { "use strict"; require("./core/CCGame"); require("./actions"); }), { "./actions": 8, "./core/CCGame": 23 } ], 246: [ (function(require, module, exports) { "use strict"; var Asset = require("../core/assets/CCAsset"); var CCSpriteFrame = require("../core/assets/CCSpriteFrame"); var ParticleAsset = cc.Class({ name: "cc.ParticleAsset", extends: Asset, properties: { spriteFrame: { default: null, type: CCSpriteFrame } } }); cc.ParticleAsset = module.exports = ParticleAsset; }), { "../core/assets/CCAsset": 57, "../core/assets/CCSpriteFrame": 69 } ], 247: [ (function(require, module, exports) { "use strict"; var enums = { USAGE_STATIC: 35044, USAGE_DYNAMIC: 35048, USAGE_STREAM: 35040, INDEX_FMT_UINT8: 5121, INDEX_FMT_UINT16: 5123, INDEX_FMT_UINT32: 5125, ATTR_POSITION: "a_position", ATTR_NORMAL: "a_normal", ATTR_TANGENT: "a_tangent", ATTR_BITANGENT: "a_bitangent", ATTR_WEIGHTS: "a_weights", ATTR_JOINTS: "a_joints", ATTR_COLOR: "a_color", ATTR_COLOR0: "a_color0", ATTR_COLOR1: "a_color1", ATTR_UV: "a_uv", ATTR_UV0: "a_uv0", ATTR_UV1: "a_uv1", ATTR_UV2: "a_uv2", ATTR_UV3: "a_uv3", ATTR_UV4: "a_uv4", ATTR_UV5: "a_uv5", ATTR_UV6: "a_uv6", ATTR_UV7: "a_uv7", ATTR_TYPE_INT8: 5120, ATTR_TYPE_UINT8: 5121, ATTR_TYPE_INT16: 5122, ATTR_TYPE_UINT16: 5123, ATTR_TYPE_INT32: 5124, ATTR_TYPE_UINT32: 5125, ATTR_TYPE_FLOAT32: 5126, FILTER_NEAREST: 0, FILTER_LINEAR: 1, WRAP_REPEAT: 10497, WRAP_CLAMP: 33071, WRAP_MIRROR: 33648, TEXTURE_FMT_RGB_DXT1: 0, TEXTURE_FMT_RGBA_DXT1: 1, TEXTURE_FMT_RGBA_DXT3: 2, TEXTURE_FMT_RGBA_DXT5: 3, TEXTURE_FMT_RGB_ETC1: 4, TEXTURE_FMT_RGB_PVRTC_2BPPV1: 5, TEXTURE_FMT_RGBA_PVRTC_2BPPV1: 6, TEXTURE_FMT_RGB_PVRTC_4BPPV1: 7, TEXTURE_FMT_RGBA_PVRTC_4BPPV1: 8, TEXTURE_FMT_A8: 9, TEXTURE_FMT_L8: 10, TEXTURE_FMT_L8_A8: 11, TEXTURE_FMT_R5_G6_B5: 12, TEXTURE_FMT_R5_G5_B5_A1: 13, TEXTURE_FMT_R4_G4_B4_A4: 14, TEXTURE_FMT_RGB8: 15, TEXTURE_FMT_RGBA8: 16, TEXTURE_FMT_RGB16F: 17, TEXTURE_FMT_RGBA16F: 18, TEXTURE_FMT_RGB32F: 19, TEXTURE_FMT_RGBA32F: 20, TEXTURE_FMT_R32F: 21, TEXTURE_FMT_111110F: 22, TEXTURE_FMT_SRGB: 23, TEXTURE_FMT_SRGBA: 24, TEXTURE_FMT_D16: 25, TEXTURE_FMT_D32: 26, TEXTURE_FMT_D24S8: 27, TEXTURE_FMT_RGB_ETC2: 28, TEXTURE_FMT_RGBA_ETC2: 29, DS_FUNC_NEVER: 512, DS_FUNC_LESS: 513, DS_FUNC_EQUAL: 514, DS_FUNC_LEQUAL: 515, DS_FUNC_GREATER: 516, DS_FUNC_NOTEQUAL: 517, DS_FUNC_GEQUAL: 518, DS_FUNC_ALWAYS: 519, RB_FMT_RGBA4: 32854, RB_FMT_RGB5_A1: 32855, RB_FMT_RGB565: 36194, RB_FMT_D16: 33189, RB_FMT_S8: 36168, RB_FMT_D24S8: 34041, BLEND_FUNC_ADD: 32774, BLEND_FUNC_SUBTRACT: 32778, BLEND_FUNC_REVERSE_SUBTRACT: 32779, BLEND_ZERO: 0, BLEND_ONE: 1, BLEND_SRC_COLOR: 768, BLEND_ONE_MINUS_SRC_COLOR: 769, BLEND_DST_COLOR: 774, BLEND_ONE_MINUS_DST_COLOR: 775, BLEND_SRC_ALPHA: 770, BLEND_ONE_MINUS_SRC_ALPHA: 771, BLEND_DST_ALPHA: 772, BLEND_ONE_MINUS_DST_ALPHA: 773, BLEND_CONSTANT_COLOR: 32769, BLEND_ONE_MINUS_CONSTANT_COLOR: 32770, BLEND_CONSTANT_ALPHA: 32771, BLEND_ONE_MINUS_CONSTANT_ALPHA: 32772, BLEND_SRC_ALPHA_SATURATE: 776, STENCIL_DISABLE: 0, STENCIL_ENABLE: 1, STENCIL_INHERIT: 2, STENCIL_OP_KEEP: 7680, STENCIL_OP_ZERO: 0, STENCIL_OP_REPLACE: 7681, STENCIL_OP_INCR: 7682, STENCIL_OP_INCR_WRAP: 34055, STENCIL_OP_DECR: 7683, STENCIL_OP_DECR_WRAP: 34056, STENCIL_OP_INVERT: 5386, CULL_NONE: 0, CULL_FRONT: 1028, CULL_BACK: 1029, CULL_FRONT_AND_BACK: 1032, PT_POINTS: 0, PT_LINES: 1, PT_LINE_LOOP: 2, PT_LINE_STRIP: 3, PT_TRIANGLES: 4, PT_TRIANGLE_STRIP: 5, PT_TRIANGLE_FAN: 6 }; var RenderQueue = { OPAQUE: 0, TRANSPARENT: 1, OVERLAY: 2 }; function murmurhash2_32_gc(str, seed) { var l = str.length, h = seed ^ l, i = 0, k; while (l >= 4) { k = 255 & str.charCodeAt(i) | (255 & str.charCodeAt(++i)) << 8 | (255 & str.charCodeAt(++i)) << 16 | (255 & str.charCodeAt(++i)) << 24; k = 1540483477 * (65535 & k) + ((1540483477 * (k >>> 16) & 65535) << 16); k ^= k >>> 24; k = 1540483477 * (65535 & k) + ((1540483477 * (k >>> 16) & 65535) << 16); h = 1540483477 * (65535 & h) + ((1540483477 * (h >>> 16) & 65535) << 16) ^ k; l -= 4; ++i; } switch (l) { case 3: h ^= (255 & str.charCodeAt(i + 2)) << 16; case 2: h ^= (255 & str.charCodeAt(i + 1)) << 8; case 1: h ^= 255 & str.charCodeAt(i); h = 1540483477 * (65535 & h) + ((1540483477 * (h >>> 16) & 65535) << 16); } h ^= h >>> 13; h = 1540483477 * (65535 & h) + ((1540483477 * (h >>> 16) & 65535) << 16); h ^= h >>> 15; return h >>> 0; } var WebGLEXT; (function(WebGLEXT) { WebGLEXT[WebGLEXT["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; WebGLEXT[WebGLEXT["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; WebGLEXT[WebGLEXT["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; WebGLEXT[WebGLEXT["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; WebGLEXT[WebGLEXT["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; WebGLEXT[WebGLEXT["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; })(WebGLEXT || (WebGLEXT = {})); var GFXObjectType; (function(GFXObjectType) { GFXObjectType[GFXObjectType["UNKNOWN"] = 0] = "UNKNOWN"; GFXObjectType[GFXObjectType["BUFFER"] = 1] = "BUFFER"; GFXObjectType[GFXObjectType["TEXTURE"] = 2] = "TEXTURE"; GFXObjectType[GFXObjectType["TEXTURE_VIEW"] = 3] = "TEXTURE_VIEW"; GFXObjectType[GFXObjectType["RENDER_PASS"] = 4] = "RENDER_PASS"; GFXObjectType[GFXObjectType["FRAMEBUFFER"] = 5] = "FRAMEBUFFER"; GFXObjectType[GFXObjectType["SAMPLER"] = 6] = "SAMPLER"; GFXObjectType[GFXObjectType["SHADER"] = 7] = "SHADER"; GFXObjectType[GFXObjectType["PIPELINE_LAYOUT"] = 8] = "PIPELINE_LAYOUT"; GFXObjectType[GFXObjectType["PIPELINE_STATE"] = 9] = "PIPELINE_STATE"; GFXObjectType[GFXObjectType["BINDING_LAYOUT"] = 10] = "BINDING_LAYOUT"; GFXObjectType[GFXObjectType["INPUT_ASSEMBLER"] = 11] = "INPUT_ASSEMBLER"; GFXObjectType[GFXObjectType["COMMAND_ALLOCATOR"] = 12] = "COMMAND_ALLOCATOR"; GFXObjectType[GFXObjectType["COMMAND_BUFFER"] = 13] = "COMMAND_BUFFER"; GFXObjectType[GFXObjectType["QUEUE"] = 14] = "QUEUE"; GFXObjectType[GFXObjectType["WINDOW"] = 15] = "WINDOW"; })(GFXObjectType || (GFXObjectType = {})); var GFXStatus; (function(GFXStatus) { GFXStatus[GFXStatus["UNREADY"] = 0] = "UNREADY"; GFXStatus[GFXStatus["FAILED"] = 1] = "FAILED"; GFXStatus[GFXStatus["SUCCESS"] = 2] = "SUCCESS"; })(GFXStatus || (GFXStatus = {})); var GFXObject = (function() { function GFXObject(gfxType) { this._gfxType = GFXObjectType.UNKNOWN; this._status = GFXStatus.UNREADY; this._gfxType = gfxType; } Object.defineProperty(GFXObject.prototype, "gfxType", { get: function get() { return this._gfxType; }, enumerable: true, configurable: true }); Object.defineProperty(GFXObject.prototype, "status", { get: function get() { return this._status; }, enumerable: true, configurable: true }); return GFXObject; })(); var GFXAttributeName; (function(GFXAttributeName) { GFXAttributeName["ATTR_POSITION"] = "a_position"; GFXAttributeName["ATTR_NORMAL"] = "a_normal"; GFXAttributeName["ATTR_TANGENT"] = "a_tangent"; GFXAttributeName["ATTR_BITANGENT"] = "a_bitangent"; GFXAttributeName["ATTR_WEIGHTS"] = "a_weights"; GFXAttributeName["ATTR_JOINTS"] = "a_joints"; GFXAttributeName["ATTR_COLOR"] = "a_color"; GFXAttributeName["ATTR_COLOR1"] = "a_color1"; GFXAttributeName["ATTR_COLOR2"] = "a_color2"; GFXAttributeName["ATTR_TEX_COORD"] = "a_texCoord"; GFXAttributeName["ATTR_TEX_COORD1"] = "a_texCoord1"; GFXAttributeName["ATTR_TEX_COORD2"] = "a_texCoord2"; GFXAttributeName["ATTR_TEX_COORD3"] = "a_texCoord3"; GFXAttributeName["ATTR_TEX_COORD4"] = "a_texCoord4"; GFXAttributeName["ATTR_TEX_COORD5"] = "a_texCoord5"; GFXAttributeName["ATTR_TEX_COORD6"] = "a_texCoord6"; GFXAttributeName["ATTR_TEX_COORD7"] = "a_texCoord7"; GFXAttributeName["ATTR_TEX_COORD8"] = "a_texCoord8"; })(GFXAttributeName || (GFXAttributeName = {})); var GFXType; (function(GFXType) { GFXType[GFXType["UNKNOWN"] = 0] = "UNKNOWN"; GFXType[GFXType["BOOL"] = 1] = "BOOL"; GFXType[GFXType["BOOL2"] = 2] = "BOOL2"; GFXType[GFXType["BOOL3"] = 3] = "BOOL3"; GFXType[GFXType["BOOL4"] = 4] = "BOOL4"; GFXType[GFXType["INT"] = 5] = "INT"; GFXType[GFXType["INT2"] = 6] = "INT2"; GFXType[GFXType["INT3"] = 7] = "INT3"; GFXType[GFXType["INT4"] = 8] = "INT4"; GFXType[GFXType["UINT"] = 9] = "UINT"; GFXType[GFXType["UINT2"] = 10] = "UINT2"; GFXType[GFXType["UINT3"] = 11] = "UINT3"; GFXType[GFXType["UINT4"] = 12] = "UINT4"; GFXType[GFXType["FLOAT"] = 13] = "FLOAT"; GFXType[GFXType["FLOAT2"] = 14] = "FLOAT2"; GFXType[GFXType["FLOAT3"] = 15] = "FLOAT3"; GFXType[GFXType["FLOAT4"] = 16] = "FLOAT4"; GFXType[GFXType["COLOR4"] = 17] = "COLOR4"; GFXType[GFXType["MAT2"] = 18] = "MAT2"; GFXType[GFXType["MAT2X3"] = 19] = "MAT2X3"; GFXType[GFXType["MAT2X4"] = 20] = "MAT2X4"; GFXType[GFXType["MAT3X2"] = 21] = "MAT3X2"; GFXType[GFXType["MAT3"] = 22] = "MAT3"; GFXType[GFXType["MAT3X4"] = 23] = "MAT3X4"; GFXType[GFXType["MAT4X2"] = 24] = "MAT4X2"; GFXType[GFXType["MAT4X3"] = 25] = "MAT4X3"; GFXType[GFXType["MAT4"] = 26] = "MAT4"; GFXType[GFXType["SAMPLER1D"] = 27] = "SAMPLER1D"; GFXType[GFXType["SAMPLER1D_ARRAY"] = 28] = "SAMPLER1D_ARRAY"; GFXType[GFXType["SAMPLER2D"] = 29] = "SAMPLER2D"; GFXType[GFXType["SAMPLER2D_ARRAY"] = 30] = "SAMPLER2D_ARRAY"; GFXType[GFXType["SAMPLER3D"] = 31] = "SAMPLER3D"; GFXType[GFXType["SAMPLER_CUBE"] = 32] = "SAMPLER_CUBE"; GFXType[GFXType["COUNT"] = 33] = "COUNT"; })(GFXType || (GFXType = {})); var GFXFormat; (function(GFXFormat) { GFXFormat[GFXFormat["UNKNOWN"] = 0] = "UNKNOWN"; GFXFormat[GFXFormat["A8"] = 1] = "A8"; GFXFormat[GFXFormat["L8"] = 2] = "L8"; GFXFormat[GFXFormat["LA8"] = 3] = "LA8"; GFXFormat[GFXFormat["R8"] = 4] = "R8"; GFXFormat[GFXFormat["R8SN"] = 5] = "R8SN"; GFXFormat[GFXFormat["R8UI"] = 6] = "R8UI"; GFXFormat[GFXFormat["R8I"] = 7] = "R8I"; GFXFormat[GFXFormat["R16F"] = 8] = "R16F"; GFXFormat[GFXFormat["R16UI"] = 9] = "R16UI"; GFXFormat[GFXFormat["R16I"] = 10] = "R16I"; GFXFormat[GFXFormat["R32F"] = 11] = "R32F"; GFXFormat[GFXFormat["R32UI"] = 12] = "R32UI"; GFXFormat[GFXFormat["R32I"] = 13] = "R32I"; GFXFormat[GFXFormat["RG8"] = 14] = "RG8"; GFXFormat[GFXFormat["RG8SN"] = 15] = "RG8SN"; GFXFormat[GFXFormat["RG8UI"] = 16] = "RG8UI"; GFXFormat[GFXFormat["RG8I"] = 17] = "RG8I"; GFXFormat[GFXFormat["RG16F"] = 18] = "RG16F"; GFXFormat[GFXFormat["RG16UI"] = 19] = "RG16UI"; GFXFormat[GFXFormat["RG16I"] = 20] = "RG16I"; GFXFormat[GFXFormat["RG32F"] = 21] = "RG32F"; GFXFormat[GFXFormat["RG32UI"] = 22] = "RG32UI"; GFXFormat[GFXFormat["RG32I"] = 23] = "RG32I"; GFXFormat[GFXFormat["RGB8"] = 24] = "RGB8"; GFXFormat[GFXFormat["SRGB8"] = 25] = "SRGB8"; GFXFormat[GFXFormat["RGB8SN"] = 26] = "RGB8SN"; GFXFormat[GFXFormat["RGB8UI"] = 27] = "RGB8UI"; GFXFormat[GFXFormat["RGB8I"] = 28] = "RGB8I"; GFXFormat[GFXFormat["RGB16F"] = 29] = "RGB16F"; GFXFormat[GFXFormat["RGB16UI"] = 30] = "RGB16UI"; GFXFormat[GFXFormat["RGB16I"] = 31] = "RGB16I"; GFXFormat[GFXFormat["RGB32F"] = 32] = "RGB32F"; GFXFormat[GFXFormat["RGB32UI"] = 33] = "RGB32UI"; GFXFormat[GFXFormat["RGB32I"] = 34] = "RGB32I"; GFXFormat[GFXFormat["RGBA8"] = 35] = "RGBA8"; GFXFormat[GFXFormat["SRGB8_A8"] = 36] = "SRGB8_A8"; GFXFormat[GFXFormat["RGBA8SN"] = 37] = "RGBA8SN"; GFXFormat[GFXFormat["RGBA8UI"] = 38] = "RGBA8UI"; GFXFormat[GFXFormat["RGBA8I"] = 39] = "RGBA8I"; GFXFormat[GFXFormat["RGBA16F"] = 40] = "RGBA16F"; GFXFormat[GFXFormat["RGBA16UI"] = 41] = "RGBA16UI"; GFXFormat[GFXFormat["RGBA16I"] = 42] = "RGBA16I"; GFXFormat[GFXFormat["RGBA32F"] = 43] = "RGBA32F"; GFXFormat[GFXFormat["RGBA32UI"] = 44] = "RGBA32UI"; GFXFormat[GFXFormat["RGBA32I"] = 45] = "RGBA32I"; GFXFormat[GFXFormat["R5G6B5"] = 46] = "R5G6B5"; GFXFormat[GFXFormat["R11G11B10F"] = 47] = "R11G11B10F"; GFXFormat[GFXFormat["RGB5A1"] = 48] = "RGB5A1"; GFXFormat[GFXFormat["RGBA4"] = 49] = "RGBA4"; GFXFormat[GFXFormat["RGB10A2"] = 50] = "RGB10A2"; GFXFormat[GFXFormat["RGB10A2UI"] = 51] = "RGB10A2UI"; GFXFormat[GFXFormat["RGB9E5"] = 52] = "RGB9E5"; GFXFormat[GFXFormat["D16"] = 53] = "D16"; GFXFormat[GFXFormat["D16S8"] = 54] = "D16S8"; GFXFormat[GFXFormat["D24"] = 55] = "D24"; GFXFormat[GFXFormat["D24S8"] = 56] = "D24S8"; GFXFormat[GFXFormat["D32F"] = 57] = "D32F"; GFXFormat[GFXFormat["D32F_S8"] = 58] = "D32F_S8"; GFXFormat[GFXFormat["BC1"] = 59] = "BC1"; GFXFormat[GFXFormat["BC1_ALPHA"] = 60] = "BC1_ALPHA"; GFXFormat[GFXFormat["BC1_SRGB"] = 61] = "BC1_SRGB"; GFXFormat[GFXFormat["BC1_SRGB_ALPHA"] = 62] = "BC1_SRGB_ALPHA"; GFXFormat[GFXFormat["BC2"] = 63] = "BC2"; GFXFormat[GFXFormat["BC2_SRGB"] = 64] = "BC2_SRGB"; GFXFormat[GFXFormat["BC3"] = 65] = "BC3"; GFXFormat[GFXFormat["BC3_SRGB"] = 66] = "BC3_SRGB"; GFXFormat[GFXFormat["BC4"] = 67] = "BC4"; GFXFormat[GFXFormat["BC4_SNORM"] = 68] = "BC4_SNORM"; GFXFormat[GFXFormat["BC5"] = 69] = "BC5"; GFXFormat[GFXFormat["BC5_SNORM"] = 70] = "BC5_SNORM"; GFXFormat[GFXFormat["BC6H_UF16"] = 71] = "BC6H_UF16"; GFXFormat[GFXFormat["BC6H_SF16"] = 72] = "BC6H_SF16"; GFXFormat[GFXFormat["BC7"] = 73] = "BC7"; GFXFormat[GFXFormat["BC7_SRGB"] = 74] = "BC7_SRGB"; GFXFormat[GFXFormat["ETC_RGB8"] = 75] = "ETC_RGB8"; GFXFormat[GFXFormat["ETC2_RGB8"] = 76] = "ETC2_RGB8"; GFXFormat[GFXFormat["ETC2_SRGB8"] = 77] = "ETC2_SRGB8"; GFXFormat[GFXFormat["ETC2_RGB8_A1"] = 78] = "ETC2_RGB8_A1"; GFXFormat[GFXFormat["ETC2_SRGB8_A1"] = 79] = "ETC2_SRGB8_A1"; GFXFormat[GFXFormat["ETC2_RGBA8"] = 80] = "ETC2_RGBA8"; GFXFormat[GFXFormat["ETC2_SRGB8_A8"] = 81] = "ETC2_SRGB8_A8"; GFXFormat[GFXFormat["EAC_R11"] = 82] = "EAC_R11"; GFXFormat[GFXFormat["EAC_R11SN"] = 83] = "EAC_R11SN"; GFXFormat[GFXFormat["EAC_RG11"] = 84] = "EAC_RG11"; GFXFormat[GFXFormat["EAC_RG11SN"] = 85] = "EAC_RG11SN"; GFXFormat[GFXFormat["PVRTC_RGB2"] = 86] = "PVRTC_RGB2"; GFXFormat[GFXFormat["PVRTC_RGBA2"] = 87] = "PVRTC_RGBA2"; GFXFormat[GFXFormat["PVRTC_RGB4"] = 88] = "PVRTC_RGB4"; GFXFormat[GFXFormat["PVRTC_RGBA4"] = 89] = "PVRTC_RGBA4"; GFXFormat[GFXFormat["PVRTC2_2BPP"] = 90] = "PVRTC2_2BPP"; GFXFormat[GFXFormat["PVRTC2_4BPP"] = 91] = "PVRTC2_4BPP"; })(GFXFormat || (GFXFormat = {})); var GFXBufferUsageBit; (function(GFXBufferUsageBit) { GFXBufferUsageBit[GFXBufferUsageBit["NONE"] = 0] = "NONE"; GFXBufferUsageBit[GFXBufferUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC"; GFXBufferUsageBit[GFXBufferUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST"; GFXBufferUsageBit[GFXBufferUsageBit["INDEX"] = 4] = "INDEX"; GFXBufferUsageBit[GFXBufferUsageBit["VERTEX"] = 8] = "VERTEX"; GFXBufferUsageBit[GFXBufferUsageBit["UNIFORM"] = 16] = "UNIFORM"; GFXBufferUsageBit[GFXBufferUsageBit["STORAGE"] = 32] = "STORAGE"; GFXBufferUsageBit[GFXBufferUsageBit["INDIRECT"] = 64] = "INDIRECT"; })(GFXBufferUsageBit || (GFXBufferUsageBit = {})); var GFXMemoryUsageBit; (function(GFXMemoryUsageBit) { GFXMemoryUsageBit[GFXMemoryUsageBit["NONE"] = 0] = "NONE"; GFXMemoryUsageBit[GFXMemoryUsageBit["DEVICE"] = 1] = "DEVICE"; GFXMemoryUsageBit[GFXMemoryUsageBit["HOST"] = 2] = "HOST"; })(GFXMemoryUsageBit || (GFXMemoryUsageBit = {})); var GFXBufferAccessBit; (function(GFXBufferAccessBit) { GFXBufferAccessBit[GFXBufferAccessBit["NONE"] = 0] = "NONE"; GFXBufferAccessBit[GFXBufferAccessBit["READ"] = 1] = "READ"; GFXBufferAccessBit[GFXBufferAccessBit["WRITE"] = 2] = "WRITE"; })(GFXBufferAccessBit || (GFXBufferAccessBit = {})); var GFXPrimitiveMode; (function(GFXPrimitiveMode) { GFXPrimitiveMode[GFXPrimitiveMode["POINT_LIST"] = 0] = "POINT_LIST"; GFXPrimitiveMode[GFXPrimitiveMode["LINE_LIST"] = 1] = "LINE_LIST"; GFXPrimitiveMode[GFXPrimitiveMode["LINE_STRIP"] = 2] = "LINE_STRIP"; GFXPrimitiveMode[GFXPrimitiveMode["LINE_LOOP"] = 3] = "LINE_LOOP"; GFXPrimitiveMode[GFXPrimitiveMode["LINE_LIST_ADJACENCY"] = 4] = "LINE_LIST_ADJACENCY"; GFXPrimitiveMode[GFXPrimitiveMode["LINE_STRIP_ADJACENCY"] = 5] = "LINE_STRIP_ADJACENCY"; GFXPrimitiveMode[GFXPrimitiveMode["ISO_LINE_LIST"] = 6] = "ISO_LINE_LIST"; GFXPrimitiveMode[GFXPrimitiveMode["TRIANGLE_LIST"] = 7] = "TRIANGLE_LIST"; GFXPrimitiveMode[GFXPrimitiveMode["TRIANGLE_STRIP"] = 8] = "TRIANGLE_STRIP"; GFXPrimitiveMode[GFXPrimitiveMode["TRIANGLE_FAN"] = 9] = "TRIANGLE_FAN"; GFXPrimitiveMode[GFXPrimitiveMode["TRIANGLE_LIST_ADJACENCY"] = 10] = "TRIANGLE_LIST_ADJACENCY"; GFXPrimitiveMode[GFXPrimitiveMode["TRIANGLE_STRIP_ADJACENCY"] = 11] = "TRIANGLE_STRIP_ADJACENCY"; GFXPrimitiveMode[GFXPrimitiveMode["TRIANGLE_PATCH_ADJACENCY"] = 12] = "TRIANGLE_PATCH_ADJACENCY"; GFXPrimitiveMode[GFXPrimitiveMode["QUAD_PATCH_LIST"] = 13] = "QUAD_PATCH_LIST"; })(GFXPrimitiveMode || (GFXPrimitiveMode = {})); var GFXPolygonMode; (function(GFXPolygonMode) { GFXPolygonMode[GFXPolygonMode["FILL"] = 0] = "FILL"; GFXPolygonMode[GFXPolygonMode["POINT"] = 1] = "POINT"; GFXPolygonMode[GFXPolygonMode["LINE"] = 2] = "LINE"; })(GFXPolygonMode || (GFXPolygonMode = {})); var GFXShadeModel; (function(GFXShadeModel) { GFXShadeModel[GFXShadeModel["GOURAND"] = 0] = "GOURAND"; GFXShadeModel[GFXShadeModel["FLAT"] = 1] = "FLAT"; })(GFXShadeModel || (GFXShadeModel = {})); var GFXCullMode; (function(GFXCullMode) { GFXCullMode[GFXCullMode["NONE"] = 0] = "NONE"; GFXCullMode[GFXCullMode["FRONT"] = 1] = "FRONT"; GFXCullMode[GFXCullMode["BACK"] = 2] = "BACK"; })(GFXCullMode || (GFXCullMode = {})); var GFXComparisonFunc; (function(GFXComparisonFunc) { GFXComparisonFunc[GFXComparisonFunc["NEVER"] = 0] = "NEVER"; GFXComparisonFunc[GFXComparisonFunc["LESS"] = 1] = "LESS"; GFXComparisonFunc[GFXComparisonFunc["EQUAL"] = 2] = "EQUAL"; GFXComparisonFunc[GFXComparisonFunc["LESS_EQUAL"] = 3] = "LESS_EQUAL"; GFXComparisonFunc[GFXComparisonFunc["GREATER"] = 4] = "GREATER"; GFXComparisonFunc[GFXComparisonFunc["NOT_EQUAL"] = 5] = "NOT_EQUAL"; GFXComparisonFunc[GFXComparisonFunc["GREATER_EQUAL"] = 6] = "GREATER_EQUAL"; GFXComparisonFunc[GFXComparisonFunc["ALWAYS"] = 7] = "ALWAYS"; })(GFXComparisonFunc || (GFXComparisonFunc = {})); var GFXStencilOp; (function(GFXStencilOp) { GFXStencilOp[GFXStencilOp["ZERO"] = 0] = "ZERO"; GFXStencilOp[GFXStencilOp["KEEP"] = 1] = "KEEP"; GFXStencilOp[GFXStencilOp["REPLACE"] = 2] = "REPLACE"; GFXStencilOp[GFXStencilOp["INCR"] = 3] = "INCR"; GFXStencilOp[GFXStencilOp["DECR"] = 4] = "DECR"; GFXStencilOp[GFXStencilOp["INVERT"] = 5] = "INVERT"; GFXStencilOp[GFXStencilOp["INCR_WRAP"] = 6] = "INCR_WRAP"; GFXStencilOp[GFXStencilOp["DECR_WRAP"] = 7] = "DECR_WRAP"; })(GFXStencilOp || (GFXStencilOp = {})); var GFXBlendOp; (function(GFXBlendOp) { GFXBlendOp[GFXBlendOp["ADD"] = 0] = "ADD"; GFXBlendOp[GFXBlendOp["SUB"] = 1] = "SUB"; GFXBlendOp[GFXBlendOp["REV_SUB"] = 2] = "REV_SUB"; GFXBlendOp[GFXBlendOp["MIN"] = 3] = "MIN"; GFXBlendOp[GFXBlendOp["MAX"] = 4] = "MAX"; })(GFXBlendOp || (GFXBlendOp = {})); var GFXBlendFactor; (function(GFXBlendFactor) { GFXBlendFactor[GFXBlendFactor["ZERO"] = 0] = "ZERO"; GFXBlendFactor[GFXBlendFactor["ONE"] = 1] = "ONE"; GFXBlendFactor[GFXBlendFactor["SRC_ALPHA"] = 2] = "SRC_ALPHA"; GFXBlendFactor[GFXBlendFactor["DST_ALPHA"] = 3] = "DST_ALPHA"; GFXBlendFactor[GFXBlendFactor["ONE_MINUS_SRC_ALPHA"] = 4] = "ONE_MINUS_SRC_ALPHA"; GFXBlendFactor[GFXBlendFactor["ONE_MINUS_DST_ALPHA"] = 5] = "ONE_MINUS_DST_ALPHA"; GFXBlendFactor[GFXBlendFactor["SRC_COLOR"] = 6] = "SRC_COLOR"; GFXBlendFactor[GFXBlendFactor["DST_COLOR"] = 7] = "DST_COLOR"; GFXBlendFactor[GFXBlendFactor["ONE_MINUS_SRC_COLOR"] = 8] = "ONE_MINUS_SRC_COLOR"; GFXBlendFactor[GFXBlendFactor["ONE_MINUS_DST_COLOR"] = 9] = "ONE_MINUS_DST_COLOR"; GFXBlendFactor[GFXBlendFactor["SRC_ALPHA_SATURATE"] = 10] = "SRC_ALPHA_SATURATE"; GFXBlendFactor[GFXBlendFactor["CONSTANT_COLOR"] = 11] = "CONSTANT_COLOR"; GFXBlendFactor[GFXBlendFactor["ONE_MINUS_CONSTANT_COLOR"] = 12] = "ONE_MINUS_CONSTANT_COLOR"; GFXBlendFactor[GFXBlendFactor["CONSTANT_ALPHA"] = 13] = "CONSTANT_ALPHA"; GFXBlendFactor[GFXBlendFactor["ONE_MINUS_CONSTANT_ALPHA"] = 14] = "ONE_MINUS_CONSTANT_ALPHA"; })(GFXBlendFactor || (GFXBlendFactor = {})); var GFXColorMask; (function(GFXColorMask) { GFXColorMask[GFXColorMask["NONE"] = 0] = "NONE"; GFXColorMask[GFXColorMask["R"] = 1] = "R"; GFXColorMask[GFXColorMask["G"] = 2] = "G"; GFXColorMask[GFXColorMask["B"] = 4] = "B"; GFXColorMask[GFXColorMask["A"] = 8] = "A"; GFXColorMask[GFXColorMask["ALL"] = 15] = "ALL"; })(GFXColorMask || (GFXColorMask = {})); var GFXFilter; (function(GFXFilter) { GFXFilter[GFXFilter["NONE"] = 0] = "NONE"; GFXFilter[GFXFilter["POINT"] = 1] = "POINT"; GFXFilter[GFXFilter["LINEAR"] = 2] = "LINEAR"; GFXFilter[GFXFilter["ANISOTROPIC"] = 3] = "ANISOTROPIC"; })(GFXFilter || (GFXFilter = {})); var GFXAddress; (function(GFXAddress) { GFXAddress[GFXAddress["WRAP"] = 0] = "WRAP"; GFXAddress[GFXAddress["MIRROR"] = 1] = "MIRROR"; GFXAddress[GFXAddress["CLAMP"] = 2] = "CLAMP"; GFXAddress[GFXAddress["BORDER"] = 3] = "BORDER"; })(GFXAddress || (GFXAddress = {})); var GFXTextureType; (function(GFXTextureType) { GFXTextureType[GFXTextureType["TEX1D"] = 0] = "TEX1D"; GFXTextureType[GFXTextureType["TEX2D"] = 1] = "TEX2D"; GFXTextureType[GFXTextureType["TEX3D"] = 2] = "TEX3D"; })(GFXTextureType || (GFXTextureType = {})); var GFXTextureUsageBit; (function(GFXTextureUsageBit) { GFXTextureUsageBit[GFXTextureUsageBit["NONE"] = 0] = "NONE"; GFXTextureUsageBit[GFXTextureUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC"; GFXTextureUsageBit[GFXTextureUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST"; GFXTextureUsageBit[GFXTextureUsageBit["SAMPLED"] = 4] = "SAMPLED"; GFXTextureUsageBit[GFXTextureUsageBit["STORAGE"] = 8] = "STORAGE"; GFXTextureUsageBit[GFXTextureUsageBit["COLOR_ATTACHMENT"] = 16] = "COLOR_ATTACHMENT"; GFXTextureUsageBit[GFXTextureUsageBit["DEPTH_STENCIL_ATTACHMENT"] = 32] = "DEPTH_STENCIL_ATTACHMENT"; GFXTextureUsageBit[GFXTextureUsageBit["TRANSIENT_ATTACHMENT"] = 64] = "TRANSIENT_ATTACHMENT"; GFXTextureUsageBit[GFXTextureUsageBit["INPUT_ATTACHMENT"] = 128] = "INPUT_ATTACHMENT"; })(GFXTextureUsageBit || (GFXTextureUsageBit = {})); var GFXSampleCount; (function(GFXSampleCount) { GFXSampleCount[GFXSampleCount["X1"] = 0] = "X1"; GFXSampleCount[GFXSampleCount["X2"] = 1] = "X2"; GFXSampleCount[GFXSampleCount["X4"] = 2] = "X4"; GFXSampleCount[GFXSampleCount["X8"] = 3] = "X8"; GFXSampleCount[GFXSampleCount["X16"] = 4] = "X16"; GFXSampleCount[GFXSampleCount["X32"] = 5] = "X32"; GFXSampleCount[GFXSampleCount["X64"] = 6] = "X64"; })(GFXSampleCount || (GFXSampleCount = {})); var GFXTextureFlagBit; (function(GFXTextureFlagBit) { GFXTextureFlagBit[GFXTextureFlagBit["NONE"] = 0] = "NONE"; GFXTextureFlagBit[GFXTextureFlagBit["GEN_MIPMAP"] = 1] = "GEN_MIPMAP"; GFXTextureFlagBit[GFXTextureFlagBit["CUBEMAP"] = 2] = "CUBEMAP"; GFXTextureFlagBit[GFXTextureFlagBit["BAKUP_BUFFER"] = 4] = "BAKUP_BUFFER"; })(GFXTextureFlagBit || (GFXTextureFlagBit = {})); var GFXTextureViewType; (function(GFXTextureViewType) { GFXTextureViewType[GFXTextureViewType["TV1D"] = 0] = "TV1D"; GFXTextureViewType[GFXTextureViewType["TV2D"] = 1] = "TV2D"; GFXTextureViewType[GFXTextureViewType["TV3D"] = 2] = "TV3D"; GFXTextureViewType[GFXTextureViewType["CUBE"] = 3] = "CUBE"; GFXTextureViewType[GFXTextureViewType["TV1D_ARRAY"] = 4] = "TV1D_ARRAY"; GFXTextureViewType[GFXTextureViewType["TV2D_ARRAY"] = 5] = "TV2D_ARRAY"; })(GFXTextureViewType || (GFXTextureViewType = {})); var GFXShaderType; (function(GFXShaderType) { GFXShaderType[GFXShaderType["VERTEX"] = 0] = "VERTEX"; GFXShaderType[GFXShaderType["HULL"] = 1] = "HULL"; GFXShaderType[GFXShaderType["DOMAIN"] = 2] = "DOMAIN"; GFXShaderType[GFXShaderType["GEOMETRY"] = 3] = "GEOMETRY"; GFXShaderType[GFXShaderType["FRAGMENT"] = 4] = "FRAGMENT"; GFXShaderType[GFXShaderType["COMPUTE"] = 5] = "COMPUTE"; GFXShaderType[GFXShaderType["COUNT"] = 6] = "COUNT"; })(GFXShaderType || (GFXShaderType = {})); var GFXBindingType; (function(GFXBindingType) { GFXBindingType[GFXBindingType["UNKNOWN"] = 0] = "UNKNOWN"; GFXBindingType[GFXBindingType["UNIFORM_BUFFER"] = 1] = "UNIFORM_BUFFER"; GFXBindingType[GFXBindingType["SAMPLER"] = 2] = "SAMPLER"; GFXBindingType[GFXBindingType["STORAGE_BUFFER"] = 3] = "STORAGE_BUFFER"; })(GFXBindingType || (GFXBindingType = {})); var GFXCommandBufferType; (function(GFXCommandBufferType) { GFXCommandBufferType[GFXCommandBufferType["PRIMARY"] = 0] = "PRIMARY"; GFXCommandBufferType[GFXCommandBufferType["SECONDARY"] = 1] = "SECONDARY"; })(GFXCommandBufferType || (GFXCommandBufferType = {})); var GFXLoadOp; (function(GFXLoadOp) { GFXLoadOp[GFXLoadOp["LOAD"] = 0] = "LOAD"; GFXLoadOp[GFXLoadOp["CLEAR"] = 1] = "CLEAR"; GFXLoadOp[GFXLoadOp["DISCARD"] = 2] = "DISCARD"; })(GFXLoadOp || (GFXLoadOp = {})); var GFXStoreOp; (function(GFXStoreOp) { GFXStoreOp[GFXStoreOp["STORE"] = 0] = "STORE"; GFXStoreOp[GFXStoreOp["DISCARD"] = 1] = "DISCARD"; })(GFXStoreOp || (GFXStoreOp = {})); var GFXTextureLayout; (function(GFXTextureLayout) { GFXTextureLayout[GFXTextureLayout["UNDEFINED"] = 0] = "UNDEFINED"; GFXTextureLayout[GFXTextureLayout["GENERAL"] = 1] = "GENERAL"; GFXTextureLayout[GFXTextureLayout["COLOR_ATTACHMENT_OPTIMAL"] = 2] = "COLOR_ATTACHMENT_OPTIMAL"; GFXTextureLayout[GFXTextureLayout["DEPTH_STENCIL_ATTACHMENT_OPTIMAL"] = 3] = "DEPTH_STENCIL_ATTACHMENT_OPTIMAL"; GFXTextureLayout[GFXTextureLayout["DEPTH_STENCIL_READONLY_OPTIMAL"] = 4] = "DEPTH_STENCIL_READONLY_OPTIMAL"; GFXTextureLayout[GFXTextureLayout["SHADER_READONLY_OPTIMAL"] = 5] = "SHADER_READONLY_OPTIMAL"; GFXTextureLayout[GFXTextureLayout["TRANSFER_SRC_OPTIMAL"] = 6] = "TRANSFER_SRC_OPTIMAL"; GFXTextureLayout[GFXTextureLayout["TRANSFER_DST_OPTIMAL"] = 7] = "TRANSFER_DST_OPTIMAL"; GFXTextureLayout[GFXTextureLayout["PREINITIALIZED"] = 8] = "PREINITIALIZED"; GFXTextureLayout[GFXTextureLayout["PRESENT_SRC"] = 9] = "PRESENT_SRC"; })(GFXTextureLayout || (GFXTextureLayout = {})); var GFXPipelineBindPoint; (function(GFXPipelineBindPoint) { GFXPipelineBindPoint[GFXPipelineBindPoint["GRAPHICS"] = 0] = "GRAPHICS"; GFXPipelineBindPoint[GFXPipelineBindPoint["COMPUTE"] = 1] = "COMPUTE"; GFXPipelineBindPoint[GFXPipelineBindPoint["RAY_TRACING"] = 2] = "RAY_TRACING"; })(GFXPipelineBindPoint || (GFXPipelineBindPoint = {})); var GFXDynamicState; (function(GFXDynamicState) { GFXDynamicState[GFXDynamicState["VIEWPORT"] = 0] = "VIEWPORT"; GFXDynamicState[GFXDynamicState["SCISSOR"] = 1] = "SCISSOR"; GFXDynamicState[GFXDynamicState["LINE_WIDTH"] = 2] = "LINE_WIDTH"; GFXDynamicState[GFXDynamicState["DEPTH_BIAS"] = 3] = "DEPTH_BIAS"; GFXDynamicState[GFXDynamicState["BLEND_CONSTANTS"] = 4] = "BLEND_CONSTANTS"; GFXDynamicState[GFXDynamicState["DEPTH_BOUNDS"] = 5] = "DEPTH_BOUNDS"; GFXDynamicState[GFXDynamicState["STENCIL_WRITE_MASK"] = 6] = "STENCIL_WRITE_MASK"; GFXDynamicState[GFXDynamicState["STENCIL_COMPARE_MASK"] = 7] = "STENCIL_COMPARE_MASK"; })(GFXDynamicState || (GFXDynamicState = {})); var GFXStencilFace; (function(GFXStencilFace) { GFXStencilFace[GFXStencilFace["FRONT"] = 0] = "FRONT"; GFXStencilFace[GFXStencilFace["BACK"] = 1] = "BACK"; GFXStencilFace[GFXStencilFace["ALL"] = 2] = "ALL"; })(GFXStencilFace || (GFXStencilFace = {})); var GFXQueueType; (function(GFXQueueType) { GFXQueueType[GFXQueueType["GRAPHICS"] = 0] = "GRAPHICS"; GFXQueueType[GFXQueueType["COMPUTE"] = 1] = "COMPUTE"; GFXQueueType[GFXQueueType["TRANSFER"] = 2] = "TRANSFER"; })(GFXQueueType || (GFXQueueType = {})); var GFXClearFlag; (function(GFXClearFlag) { GFXClearFlag[GFXClearFlag["NONE"] = 0] = "NONE"; GFXClearFlag[GFXClearFlag["COLOR"] = 1] = "COLOR"; GFXClearFlag[GFXClearFlag["DEPTH"] = 2] = "DEPTH"; GFXClearFlag[GFXClearFlag["STENCIL"] = 4] = "STENCIL"; GFXClearFlag[GFXClearFlag["DEPTH_STENCIL"] = 6] = "DEPTH_STENCIL"; GFXClearFlag[GFXClearFlag["ALL"] = 7] = "ALL"; })(GFXClearFlag || (GFXClearFlag = {})); function GFXGetTypeSize(type) { switch (type) { case GFXType.BOOL: case GFXType.INT: case GFXType.UINT: case GFXType.FLOAT: return 4; case GFXType.BOOL2: case GFXType.INT2: case GFXType.UINT2: case GFXType.FLOAT2: return 8; case GFXType.BOOL3: case GFXType.INT3: case GFXType.UINT3: case GFXType.FLOAT3: return 12; case GFXType.BOOL4: case GFXType.INT4: case GFXType.UINT4: case GFXType.FLOAT4: case GFXType.MAT2: return 16; case GFXType.MAT2X3: return 24; case GFXType.MAT2X4: return 32; case GFXType.MAT3X2: return 24; case GFXType.MAT3: return 36; case GFXType.MAT3X4: return 48; case GFXType.MAT4X2: case GFXType.MAT4X2: return 32; case GFXType.MAT4: return 64; case GFXType.SAMPLER1D: case GFXType.SAMPLER1D_ARRAY: case GFXType.SAMPLER2D: case GFXType.SAMPLER2D_ARRAY: case GFXType.SAMPLER3D: case GFXType.SAMPLER_CUBE: return 4; default: return 0; } } var RenderPassStage; (function(RenderPassStage) { RenderPassStage[RenderPassStage["DEFAULT"] = 100] = "DEFAULT"; })(RenderPassStage || (RenderPassStage = {})); var RenderPriority; (function(RenderPriority) { RenderPriority[RenderPriority["MIN"] = 0] = "MIN"; RenderPriority[RenderPriority["MAX"] = 255] = "MAX"; RenderPriority[RenderPriority["DEFAULT"] = 128] = "DEFAULT"; })(RenderPriority || (RenderPriority = {})); var MAX_BINDING_SUPPORTED = 24; var UniformBinding; (function(UniformBinding) { UniformBinding[UniformBinding["UBO_GLOBAL"] = MAX_BINDING_SUPPORTED - 1] = "UBO_GLOBAL"; UniformBinding[UniformBinding["UBO_SHADOW"] = MAX_BINDING_SUPPORTED - 2] = "UBO_SHADOW"; UniformBinding[UniformBinding["UBO_LOCAL"] = MAX_BINDING_SUPPORTED - 3] = "UBO_LOCAL"; UniformBinding[UniformBinding["UBO_FORWARD_LIGHTS"] = MAX_BINDING_SUPPORTED - 4] = "UBO_FORWARD_LIGHTS"; UniformBinding[UniformBinding["UBO_SKINNING"] = MAX_BINDING_SUPPORTED - 5] = "UBO_SKINNING"; UniformBinding[UniformBinding["UBO_SKINNING_TEXTURE"] = MAX_BINDING_SUPPORTED - 6] = "UBO_SKINNING_TEXTURE"; UniformBinding[UniformBinding["UBO_UI"] = MAX_BINDING_SUPPORTED - 7] = "UBO_UI"; UniformBinding[UniformBinding["SAMPLER_JOINTS"] = MAX_BINDING_SUPPORTED + 1] = "SAMPLER_JOINTS"; UniformBinding[UniformBinding["SAMPLER_ENVIRONMENT"] = MAX_BINDING_SUPPORTED + 2] = "SAMPLER_ENVIRONMENT"; UniformBinding[UniformBinding["CUSTUM_UBO_BINDING_END_POINT"] = MAX_BINDING_SUPPORTED - 7] = "CUSTUM_UBO_BINDING_END_POINT"; UniformBinding[UniformBinding["CUSTOM_SAMPLER_BINDING_START_POINT"] = MAX_BINDING_SUPPORTED + 6] = "CUSTOM_SAMPLER_BINDING_START_POINT"; })(UniformBinding || (UniformBinding = {})); var _a, _b; var SamplerInfoIndex; (function(SamplerInfoIndex) { SamplerInfoIndex[SamplerInfoIndex["minFilter"] = 0] = "minFilter"; SamplerInfoIndex[SamplerInfoIndex["magFilter"] = 1] = "magFilter"; SamplerInfoIndex[SamplerInfoIndex["mipFilter"] = 2] = "mipFilter"; SamplerInfoIndex[SamplerInfoIndex["addressU"] = 3] = "addressU"; SamplerInfoIndex[SamplerInfoIndex["addressV"] = 4] = "addressV"; SamplerInfoIndex[SamplerInfoIndex["addressW"] = 5] = "addressW"; SamplerInfoIndex[SamplerInfoIndex["maxAnisotropy"] = 6] = "maxAnisotropy"; SamplerInfoIndex[SamplerInfoIndex["cmpFunc"] = 7] = "cmpFunc"; SamplerInfoIndex[SamplerInfoIndex["minLOD"] = 8] = "minLOD"; SamplerInfoIndex[SamplerInfoIndex["maxLOD"] = 9] = "maxLOD"; SamplerInfoIndex[SamplerInfoIndex["mipLODBias"] = 10] = "mipLODBias"; SamplerInfoIndex[SamplerInfoIndex["borderColor"] = 11] = "borderColor"; SamplerInfoIndex[SamplerInfoIndex["total"] = 15] = "total"; })(SamplerInfoIndex || (SamplerInfoIndex = {})); var typeMap = {}; typeMap[typeMap["bool"] = GFXType.BOOL] = "bool"; typeMap[typeMap["int"] = GFXType.INT] = "int"; typeMap[typeMap["ivec2"] = GFXType.INT2] = "ivec2invTypeParams"; typeMap[typeMap["ivec3"] = GFXType.INT3] = "ivec3"; typeMap[typeMap["ivec4"] = GFXType.INT4] = "ivec4"; typeMap[typeMap["float"] = GFXType.FLOAT] = "float"; typeMap[typeMap["vec2"] = GFXType.FLOAT2] = "vec2"; typeMap[typeMap["vec3"] = GFXType.FLOAT3] = "vec3"; typeMap[typeMap["vec4"] = GFXType.FLOAT4] = "vec4"; typeMap[typeMap["mat2"] = GFXType.MAT2] = "mat2"; typeMap[typeMap["mat3"] = GFXType.MAT3] = "mat3"; typeMap[typeMap["mat4"] = GFXType.MAT4] = "mat4"; typeMap[typeMap["sampler2D"] = GFXType.SAMPLER2D] = "sampler2D"; typeMap[typeMap["samplerCube"] = GFXType.SAMPLER_CUBE] = "samplerCube"; var sizeMap = (_a = {}, _a[GFXType.BOOL] = 4, _a[GFXType.INT] = 4, _a[GFXType.INT2] = 8, _a[GFXType.INT3] = 12, _a[GFXType.INT4] = 16, _a[GFXType.FLOAT] = 4, _a[GFXType.FLOAT2] = 8, _a[GFXType.FLOAT3] = 12, _a[GFXType.FLOAT4] = 16, _a[GFXType.MAT2] = 16, _a[GFXType.MAT3] = 36, _a[GFXType.MAT4] = 64, _a[GFXType.SAMPLER2D] = 4, _a[GFXType.SAMPLER_CUBE] = 4, _a); var formatMap = (_b = {}, _b[GFXType.BOOL] = GFXFormat.R32I, _b[GFXType.INT] = GFXFormat.R32I, _b[GFXType.INT2] = GFXFormat.RG32I, _b[GFXType.INT3] = GFXFormat.RGB32I, _b[GFXType.INT4] = GFXFormat.RGBA32I, _b[GFXType.FLOAT] = GFXFormat.R32F, _b[GFXType.FLOAT2] = GFXFormat.RG32F, _b[GFXType.FLOAT3] = GFXFormat.RGB32F, _b[GFXType.FLOAT4] = GFXFormat.RGBA32F, _b); var passParams = { BACK: enums.CULL_BACK, FRONT: enums.CULL_FRONT, NONE: enums.CULL_NONE, ADD: enums.BLEND_FUNC_ADD, SUB: enums.BLEND_FUNC_SUBTRACT, REV_SUB: enums.BLEND_FUNC_REVERSE_SUBTRACT, ZERO: enums.BLEND_ZERO, ONE: enums.BLEND_ONE, SRC_COLOR: enums.BLEND_SRC_COLOR, ONE_MINUS_SRC_COLOR: enums.BLEND_ONE_MINUS_SRC_COLOR, DST_COLOR: enums.BLEND_DST_COLOR, ONE_MINUS_DST_COLOR: enums.BLEND_ONE_MINUS_DST_COLOR, SRC_ALPHA: enums.BLEND_SRC_ALPHA, ONE_MINUS_SRC_ALPHA: enums.BLEND_ONE_MINUS_SRC_ALPHA, DST_ALPHA: enums.BLEND_DST_ALPHA, ONE_MINUS_DST_ALPHA: enums.BLEND_ONE_MINUS_DST_ALPHA, CONSTANT_COLOR: enums.BLEND_CONSTANT_COLOR, ONE_MINUS_CONSTANT_COLOR: enums.BLEND_ONE_MINUS_CONSTANT_COLOR, CONSTANT_ALPHA: enums.BLEND_CONSTANT_ALPHA, ONE_MINUS_CONSTANT_ALPHA: enums.BLEND_ONE_MINUS_CONSTANT_ALPHA, SRC_ALPHA_SATURATE: enums.BLEND_SRC_ALPHA_SATURATE, NEVER: enums.DS_FUNC_NEVER, LESS: enums.DS_FUNC_LESS, EQUAL: enums.DS_FUNC_EQUAL, LEQUAL: enums.DS_FUNC_LEQUAL, GREATER: enums.DS_FUNC_GREATER, NOTEQUAL: enums.DS_FUNC_NOTEQUAL, GEQUAL: enums.DS_FUNC_GEQUAL, ALWAYS: enums.DS_FUNC_ALWAYS, KEEP: enums.STENCIL_OP_KEEP, REPLACE: enums.STENCIL_OP_REPLACE, INCR: enums.STENCIL_OP_INCR, INCR_WRAP: enums.STENCIL_OP_INCR_WRAP, DECR: enums.STENCIL_OP_DECR, DECR_WRAP: enums.STENCIL_OP_DECR_WRAP, INVERT: enums.STENCIL_OP_INVERT }; Object.assign(passParams, RenderPassStage); var effectStructure = { $techniques: [ { $passes: [ { depthStencilState: {}, rasterizerState: {}, blendState: { targets: [ {} ] }, properties: { any: { sampler: {}, inspector: {} } } } ] } ] }; var mappings = { murmurhash2_32_gc: murmurhash2_32_gc, SamplerInfoIndex: SamplerInfoIndex, effectStructure: effectStructure, typeMap: typeMap, sizeMap: sizeMap, formatMap: formatMap, passParams: passParams, RenderQueue: RenderQueue, RenderPriority: RenderPriority, GFXGetTypeSize: GFXGetTypeSize, UniformBinding: UniformBinding }; module.exports = mappings; }), {} ], 248: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _memop = require("../memop"); var _enums = _interopRequireDefault(require("../enums")); var _valueTypes = require("../../core/value-types"); var _programLib = _interopRequireDefault(require("./program-lib")); var _view = _interopRequireDefault(require("./view")); var _gfx = _interopRequireDefault(require("../gfx")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _m4_tmp = new _valueTypes.Mat4(); var _stageInfos = new _memop.RecyclePool(function() { return { stage: null, items: null }; }, 8); var _float2_pool = new _memop.RecyclePool(function() { return new Float32Array(2); }, 8); var _float3_pool = new _memop.RecyclePool(function() { return new Float32Array(3); }, 8); var _float4_pool = new _memop.RecyclePool(function() { return new Float32Array(4); }, 8); var _float9_pool = new _memop.RecyclePool(function() { return new Float32Array(9); }, 8); var _float16_pool = new _memop.RecyclePool(function() { return new Float32Array(16); }, 8); var _float64_pool = new _memop.RecyclePool(function() { return new Float32Array(64); }, 8); var _int2_pool = new _memop.RecyclePool(function() { return new Int32Array(2); }, 8); var _int3_pool = new _memop.RecyclePool(function() { return new Int32Array(3); }, 8); var _int4_pool = new _memop.RecyclePool(function() { return new Int32Array(4); }, 8); var _int64_pool = new _memop.RecyclePool(function() { return new Int32Array(64); }, 8); var Base = (function() { function Base(device, opts) { var _this$_type2defaultVa; this._device = device; this._programLib = new _programLib["default"](device); this._opts = opts; this._type2defaultValue = (_this$_type2defaultVa = {}, _this$_type2defaultVa[_enums["default"].PARAM_INT] = 0, _this$_type2defaultVa[_enums["default"].PARAM_INT2] = new _valueTypes.Vec2(0, 0), _this$_type2defaultVa[_enums["default"].PARAM_INT3] = new _valueTypes.Vec3(0, 0, 0), _this$_type2defaultVa[_enums["default"].PARAM_INT4] = new _valueTypes.Vec4(0, 0, 0, 0), _this$_type2defaultVa[_enums["default"].PARAM_FLOAT] = 0, _this$_type2defaultVa[_enums["default"].PARAM_FLOAT2] = new _valueTypes.Vec2(0, 0), _this$_type2defaultVa[_enums["default"].PARAM_FLOAT3] = new _valueTypes.Vec3(0, 0, 0), _this$_type2defaultVa[_enums["default"].PARAM_FLOAT4] = new _valueTypes.Vec4(0, 0, 0, 0), _this$_type2defaultVa[_enums["default"].PARAM_COLOR4] = new _valueTypes.Color(0, 0, 0, 1), _this$_type2defaultVa[_enums["default"].PARAM_MAT3] = new _valueTypes.Mat3(), _this$_type2defaultVa[_enums["default"].PARAM_MAT4] = new _valueTypes.Mat4(), _this$_type2defaultVa[_enums["default"].PARAM_TEXTURE_2D] = opts.defaultTexture, _this$_type2defaultVa[_enums["default"].PARAM_TEXTURE_CUBE] = opts.defaultTextureCube, _this$_type2defaultVa); this._stage2fn = {}; this._usedTextureUnits = 0; this._viewPools = new _memop.RecyclePool(function() { return new _view["default"](); }, 8); this._drawItemsPools = new _memop.RecyclePool(function() { return { model: null, node: null, ia: null, effect: null, defines: null, uniforms: null }; }, 100); this._stageItemsPools = new _memop.RecyclePool(function() { return new _memop.RecyclePool(function() { return { model: null, node: null, ia: null, effect: null, defines: null, passes: [], sortKey: -1, uniforms: null }; }, 100); }, 16); this._definesChanged = false; } var _proto = Base.prototype; _proto._resetTextuerUnit = function _resetTextuerUnit() { this._usedTextureUnits = 0; }; _proto._allocTextureUnit = function _allocTextureUnit() { var device = this._device; var unit = this._usedTextureUnits; unit >= device._caps.maxTextureUnits && console.warn("Trying to use " + unit + " texture units while this GPU supports only " + device._caps.maxTextureUnits); this._usedTextureUnits += 1; return unit; }; _proto._registerStage = function _registerStage(name, fn) { this._stage2fn[name] = fn; }; _proto.clear = function clear() { this._programLib.clear(); this.reset(); }; _proto.reset = function reset() { this._viewPools.reset(); this._stageItemsPools.reset(); this._definesChanged = false; }; _proto._requestView = function _requestView() { return this._viewPools.add(); }; _proto._render = function _render(view, scene) { var device = this._device; device.setFrameBuffer(view._framebuffer); device.setViewport(view._rect.x, view._rect.y, view._rect.w, view._rect.h); var clearOpts = {}; view._clearFlags & _enums["default"].CLEAR_COLOR && (clearOpts.color = _valueTypes.Vec4.toArray([], view._color)); view._clearFlags & _enums["default"].CLEAR_DEPTH && (clearOpts.depth = view._depth); view._clearFlags & _enums["default"].CLEAR_STENCIL && (clearOpts.stencil = view._stencil); device.clear(clearOpts); this._drawItemsPools.reset(); for (var i = 0; i < scene._models.length; ++i) { var model = scene._models.data[i]; if (0 === (model._cullingMask & view._cullingMask)) continue; var drawItem = this._drawItemsPools.add(); model.extractDrawItem(drawItem); } _stageInfos.reset(); for (var _i = 0; _i < view._stages.length; ++_i) { var stage = view._stages[_i]; var stageItems = this._stageItemsPools.add(); stageItems.reset(); for (var j = 0; j < this._drawItemsPools.length; ++j) { var _drawItem = this._drawItemsPools.data[j]; var passes = _drawItem.effect.stagePasses[stage]; if (!passes || 0 === passes.length) continue; var stageItem = stageItems.add(); stageItem.passes = passes; stageItem.model = _drawItem.model; stageItem.node = _drawItem.node; stageItem.ia = _drawItem.ia; stageItem.effect = _drawItem.effect; stageItem.defines = _drawItem.defines; stageItem.sortKey = -1; stageItem.uniforms = _drawItem.uniforms; } var stageInfo = _stageInfos.add(); stageInfo.stage = stage; stageInfo.items = stageItems; } for (var _i2 = 0; _i2 < _stageInfos.length; ++_i2) { var info = _stageInfos.data[_i2]; var fn = this._stage2fn[info.stage]; fn(view, info.items); } }; _proto._setProperty = function _setProperty(prop) { var device = this._device; var param = prop.value; void 0 === param && (param = prop.val); void 0 === param && (param = this._type2defaultValue[prop.type]); if (void 0 === param) { console.warn("Failed to set technique property " + prop.name + ", value not found."); return; } if (prop.type === _enums["default"].PARAM_TEXTURE_2D || prop.type === _enums["default"].PARAM_TEXTURE_CUBE) if (Array.isArray(param)) { if (param.length > prop.count) { console.error("Failed to set property [" + prop.name + "] : The length of texture array [" + param.length + "] is bigger than [" + prop.count + "]."); return; } var slots = _int64_pool.add(); for (var index = 0; index < param.length; ++index) slots[index] = this._allocTextureUnit(); device.setTextureArray(prop.name, param, slots); } else device.setTexture(prop.name, param, this._allocTextureUnit()); else prop.directly ? device.setUniformDirectly(prop.name, param) : device.setUniform(prop.name, param); }; _proto._draw = function _draw(item) { var device = this._device; var programLib = this._programLib; var node = item.node, ia = item.ia, passes = item.passes, effect = item.effect; _float2_pool.reset(); _float3_pool.reset(); _float4_pool.reset(); _float9_pool.reset(); _float16_pool.reset(); _float64_pool.reset(); _int2_pool.reset(); _int3_pool.reset(); _int4_pool.reset(); _int64_pool.reset(); node.getWorldMatrix(_m4_tmp); device.setUniform("cc_matWorld", _valueTypes.Mat4.toArray(_float16_pool.add(), _m4_tmp)); _valueTypes.Mat4.invert(_m4_tmp, _m4_tmp); _valueTypes.Mat4.transpose(_m4_tmp, _m4_tmp); device.setUniform("cc_matWorldIT", _valueTypes.Mat4.toArray(_float16_pool.add(), _m4_tmp)); var defines = this._defines; for (var i = 0; i < passes.length; ++i) { var pass = passes[i]; this._definesChanged && (pass._programKey = null); var count = ia.count; ia._vertexBuffer && device.setVertexBuffer(0, ia._vertexBuffer); ia._indexBuffer && device.setIndexBuffer(ia._indexBuffer); device.setPrimitiveType(ia._primitiveType); Object.setPrototypeOf(defines, pass._defines); var program = programLib.getProgram(pass, defines, effect.name); device.setProgram(program); var uniforms = program._uniforms; var variants = pass._properties; for (var j = 0; j < uniforms.length; j++) { var prop = variants[uniforms[j].name]; void 0 !== prop && this._setProperty(prop); } device.setCullMode(pass._cullMode); if (pass._blend) { device.enableBlend(); device.setBlendFuncSep(pass._blendSrc, pass._blendDst, pass._blendSrcAlpha, pass._blendDstAlpha); device.setBlendEqSep(pass._blendEq, pass._blendAlphaEq); device.setBlendColor32(pass._blendColor); } if (pass._depthTest) { device.enableDepthTest(); device.setDepthFunc(pass._depthFunc); } pass._depthWrite && device.enableDepthWrite(); device.setStencilTest(pass._stencilTest); if (pass._stencilTest === _gfx["default"].STENCIL_ENABLE) { device.setStencilFuncFront(pass._stencilFuncFront, pass._stencilRefFront, pass._stencilMaskFront); device.setStencilOpFront(pass._stencilFailOpFront, pass._stencilZFailOpFront, pass._stencilZPassOpFront, pass._stencilWriteMaskFront); device.setStencilFuncBack(pass._stencilFuncBack, pass._stencilRefBack, pass._stencilMaskBack); device.setStencilOpBack(pass._stencilFailOpBack, pass._stencilZFailOpBack, pass._stencilZPassOpBack, pass._stencilWriteMaskBack); } device.draw(ia._start, count); this._resetTextuerUnit(); } }; return Base; })(); exports["default"] = Base; module.exports = exports["default"]; }), { "../../core/value-types": 232, "../enums": 254, "../gfx": 259, "../memop": 271, "./program-lib": 251, "./view": 253 } ], 249: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _gfx = _interopRequireDefault(require("../gfx")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var InputAssembler = (function() { function InputAssembler(vb, ib, pt) { void 0 === pt && (pt = _gfx["default"].PT_TRIANGLES); this._vertexBuffer = vb; this._indexBuffer = ib; this._primitiveType = pt; this._start = 0; this._count = -1; } _createClass(InputAssembler, [ { key: "count", get: function get() { if (-1 !== this._count) return this._count; if (this._indexBuffer) return this._indexBuffer.count; if (this._vertexBuffer) return this._vertexBuffer.count; return 0; } } ]); return InputAssembler; })(); exports["default"] = InputAssembler; module.exports = exports["default"]; }), { "../gfx": 259 } ], 250: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _gfx = _interopRequireDefault(require("../gfx")); var _enums = _interopRequireDefault(require("../enums")); var _valueType = _interopRequireDefault(require("../../core/value-types/value-type")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Pass = (function() { function Pass(name, detailName, programName, stage, properties, defines) { void 0 === properties && (properties = {}); void 0 === defines && (defines = {}); this._name = name; this._detailName = detailName; this._programName = programName; this._programKey = null; this._stage = stage; this._properties = properties; this._defines = defines; this._propertyNames = Object.keys(properties); this._defineNames = Object.keys(defines); this._cullMode = _gfx["default"].CULL_BACK; this._blend = false; this._blendEq = _gfx["default"].BLEND_FUNC_ADD; this._blendAlphaEq = _gfx["default"].BLEND_FUNC_ADD; this._blendSrc = _gfx["default"].BLEND_SRC_ALPHA; this._blendDst = _gfx["default"].BLEND_ONE_MINUS_SRC_ALPHA; this._blendSrcAlpha = _gfx["default"].BLEND_SRC_ALPHA; this._blendDstAlpha = _gfx["default"].BLEND_ONE_MINUS_SRC_ALPHA; this._blendColor = 4294967295; this._depthTest = false; this._depthWrite = false; this._depthFunc = _gfx["default"].DS_FUNC_LESS, this._stencilTest = _gfx["default"].STENCIL_INHERIT; this._stencilFuncFront = _gfx["default"].DS_FUNC_ALWAYS; this._stencilRefFront = 0; this._stencilMaskFront = 255; this._stencilFailOpFront = _gfx["default"].STENCIL_OP_KEEP; this._stencilZFailOpFront = _gfx["default"].STENCIL_OP_KEEP; this._stencilZPassOpFront = _gfx["default"].STENCIL_OP_KEEP; this._stencilWriteMaskFront = 255; this._stencilFuncBack = _gfx["default"].DS_FUNC_ALWAYS; this._stencilRefBack = 0; this._stencilMaskBack = 255; this._stencilFailOpBack = _gfx["default"].STENCIL_OP_KEEP; this._stencilZFailOpBack = _gfx["default"].STENCIL_OP_KEEP; this._stencilZPassOpBack = _gfx["default"].STENCIL_OP_KEEP; this._stencilWriteMaskBack = 255; } var _proto = Pass.prototype; _proto.setCullMode = function setCullMode(cullMode) { void 0 === cullMode && (cullMode = _gfx["default"].CULL_BACK); this._cullMode = cullMode; }; _proto.setBlend = function setBlend(enabled, blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor) { void 0 === enabled && (enabled = false); void 0 === blendEq && (blendEq = _gfx["default"].BLEND_FUNC_ADD); void 0 === blendSrc && (blendSrc = _gfx["default"].BLEND_SRC_ALPHA); void 0 === blendDst && (blendDst = _gfx["default"].BLEND_ONE_MINUS_SRC_ALPHA); void 0 === blendAlphaEq && (blendAlphaEq = _gfx["default"].BLEND_FUNC_ADD); void 0 === blendSrcAlpha && (blendSrcAlpha = _gfx["default"].BLEND_SRC_ALPHA); void 0 === blendDstAlpha && (blendDstAlpha = _gfx["default"].BLEND_ONE_MINUS_SRC_ALPHA); void 0 === blendColor && (blendColor = 4294967295); this._blend = enabled; this._blendEq = blendEq; this._blendSrc = blendSrc; this._blendDst = blendDst; this._blendAlphaEq = blendAlphaEq; this._blendSrcAlpha = blendSrcAlpha; this._blendDstAlpha = blendDstAlpha; this._blendColor = blendColor; }; _proto.setDepth = function setDepth(depthTest, depthWrite, depthFunc) { void 0 === depthTest && (depthTest = false); void 0 === depthWrite && (depthWrite = false); void 0 === depthFunc && (depthFunc = _gfx["default"].DS_FUNC_LESS); this._depthTest = depthTest; this._depthWrite = depthWrite; this._depthFunc = depthFunc; }; _proto.setStencilFront = function setStencilFront(enabled, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask) { void 0 === enabled && (enabled = _gfx["default"].STENCIL_INHERIT); void 0 === stencilFunc && (stencilFunc = _gfx["default"].DS_FUNC_ALWAYS); void 0 === stencilRef && (stencilRef = 0); void 0 === stencilMask && (stencilMask = 255); void 0 === stencilFailOp && (stencilFailOp = _gfx["default"].STENCIL_OP_KEEP); void 0 === stencilZFailOp && (stencilZFailOp = _gfx["default"].STENCIL_OP_KEEP); void 0 === stencilZPassOp && (stencilZPassOp = _gfx["default"].STENCIL_OP_KEEP); void 0 === stencilWriteMask && (stencilWriteMask = 255); this._stencilTest = enabled; this._stencilFuncFront = stencilFunc; this._stencilRefFront = stencilRef; this._stencilMaskFront = stencilMask; this._stencilFailOpFront = stencilFailOp; this._stencilZFailOpFront = stencilZFailOp; this._stencilZPassOpFront = stencilZPassOp; this._stencilWriteMaskFront = stencilWriteMask; }; _proto.setStencilEnabled = function setStencilEnabled(stencilTest) { void 0 === stencilTest && (stencilTest = _gfx["default"].STENCIL_INHERIT); this._stencilTest = stencilTest; }; _proto.setStencilBack = function setStencilBack(stencilTest, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask) { void 0 === stencilTest && (stencilTest = _gfx["default"].STENCIL_INHERIT); void 0 === stencilFunc && (stencilFunc = _gfx["default"].DS_FUNC_ALWAYS); void 0 === stencilRef && (stencilRef = 0); void 0 === stencilMask && (stencilMask = 255); void 0 === stencilFailOp && (stencilFailOp = _gfx["default"].STENCIL_OP_KEEP); void 0 === stencilZFailOp && (stencilZFailOp = _gfx["default"].STENCIL_OP_KEEP); void 0 === stencilZPassOp && (stencilZPassOp = _gfx["default"].STENCIL_OP_KEEP); void 0 === stencilWriteMask && (stencilWriteMask = 255); this._stencilTest = stencilTest; this._stencilFuncBack = stencilFunc; this._stencilRefBack = stencilRef; this._stencilMaskBack = stencilMask; this._stencilFailOpBack = stencilFailOp; this._stencilZFailOpBack = stencilZFailOp; this._stencilZPassOpBack = stencilZPassOp; this._stencilWriteMaskBack = stencilWriteMask; }; _proto.setStage = function setStage(stage) { this._stage = stage; }; _proto.setProperties = function setProperties(properties) { this._properties = properties; }; _proto.getProperty = function getProperty(name) { if (!this._properties[name]) return; return this._properties[name].value; }; _proto.setProperty = function setProperty(name, value, directly) { var prop = this._properties[name]; if (!prop) return false; prop.directly = directly; if (Array.isArray(value)) { var array = prop.value; if (array.length !== value.length) { cc.warnID(9105, this._name, name); return; } for (var i = 0; i < value.length; i++) array[i] = value[i]; } else if (value && !ArrayBuffer.isView(value)) if (prop.type === _enums["default"].PARAM_TEXTURE_2D) prop.value = value.getImpl(); else if (value instanceof _valueType["default"]) value.constructor.toArray(prop.value, value); else { "object" === typeof value && cc.warnID(9106, this._name, name); prop.value = value; } else prop.value = value; return true; }; _proto.getDefine = function getDefine(name) { return this._defines[name]; }; _proto.define = function define(name, value, force) { var oldValue = this._defines[name]; if (!force && void 0 === oldValue) return false; if (oldValue !== value) { this._defines[name] = value; this._programKey = null; } return true; }; _proto.clone = function clone() { var pass = new Pass(this._programName); Object.assign(pass, this); var newProperties = {}; var properties = this._properties; for (var name in properties) { var prop = properties[name]; var newProp = newProperties[name] = {}; var value = prop.value; Array.isArray(value) ? newProp.value = value.concat() : ArrayBuffer.isView(value) ? newProp.value = new value.__proto__.constructor(value) : newProp.value = value; for (var _name in prop) { if ("value" === _name) continue; newProp[_name] = prop[_name]; } } pass._properties = newProperties; pass._defines = Object.assign({}, this._defines); pass._propertyNames = this._propertyNames; pass._defineNames = this._defineNames; return pass; }; return Pass; })(); exports["default"] = Pass; module.exports = exports["default"]; }), { "../../core/value-types/value-type": 240, "../enums": 254, "../gfx": 259 } ], 251: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _gfx = _interopRequireDefault(require("../gfx")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _shdID = 0; function _generateDefines(tmpDefines, defines) { var results = []; for (var i = 0; i < tmpDefines.length; i++) { var name = tmpDefines[i].name; var value = defines[name]; "number" !== typeof value && (value = value ? 1 : 0); results.push("#define " + name + " " + value); } return results.join("\n") + "\n"; } function _replaceMacroNums(string, tmpDefines, defines) { var tmp = string; for (var i = 0; i < tmpDefines.length; i++) { var name = tmpDefines[i].name; var value = defines[name]; if (Number.isInteger(value)) { var reg = new RegExp(name, "g"); tmp = tmp.replace(reg, value); } } return tmp; } function _unrollLoops(string) { var pattern = /#pragma for (\w+) in range\(\s*(\d+)\s*,\s*(\d+)\s*\)([\s\S]+?)#pragma endFor/g; function replace(match, index, begin, end, snippet) { var unroll = ""; var parsedBegin = parseInt(begin); var parsedEnd = parseInt(end); (parsedBegin.isNaN || parsedEnd.isNaN) && console.error("Unroll For Loops Error: begin and end of range must be an int num."); for (var i = parsedBegin; i < parsedEnd; ++i) unroll += snippet.replace(new RegExp("{" + index + "}", "g"), i); return unroll; } return string.replace(pattern, replace); } function _replaceHighp(string) { return string.replace(/\bhighp\b/g, "mediump"); } var ProgramLib = (function() { function ProgramLib(device) { this._device = device; this._templates = {}; this._cache = {}; this._checkPrecision(); } var _proto = ProgramLib.prototype; _proto.clear = function clear() { this._templates = {}; this._cache = {}; }; _proto.define = function define(prog) { var name = prog.name, defines = prog.defines, glsl1 = prog.glsl1; var _ref = glsl1 || prog, vert = _ref.vert, frag = _ref.frag; if (this._templates[name]) return; var id = ++_shdID; var offset = 0; for (var i = 0; i < defines.length; ++i) { var def = defines[i]; var cnt = 1; if ("number" === def.type) { var range = def.range || []; def.min = range[0] || 0; def.max = range[1] || 4; cnt = Math.ceil(Math.log2(def.max - def.min)); def._map = function(value) { return value - this.min << this._offset; }.bind(def); } else def._map = function(value) { if (value) return 1 << this._offset; return 0; }.bind(def); def._offset = offset; offset += cnt; } var uniforms = prog.uniforms || []; if (prog.samplers) for (var _i = 0; _i < prog.samplers.length; _i++) uniforms.push(prog.samplers[_i]); if (prog.blocks) for (var _i2 = 0; _i2 < prog.blocks.length; _i2++) { var _defines = prog.blocks[_i2].defines; var members = prog.blocks[_i2].members; for (var j = 0; j < members.length; j++) uniforms.push({ defines: _defines, name: members[j].name, type: members[j].type }); } this._templates[name] = { id: id, name: name, vert: vert, frag: frag, defines: defines, attributes: prog.attributes, uniforms: uniforms, extensions: prog.extensions }; }; _proto.getTemplate = function getTemplate(name) { return this._templates[name]; }; _proto.hasProgram = function hasProgram(name) { return void 0 !== this._templates[name]; }; _proto.getKey = function getKey(name, defines) { var tmpl = this._templates[name]; var key = 0; for (var i = 0; i < tmpl.defines.length; ++i) { var tmplDefs = tmpl.defines[i]; var value = defines[tmplDefs.name]; if (void 0 === value) continue; key |= tmplDefs._map(value); } return tmpl.id + ":" + key; }; _proto.getProgram = function getProgram(pass, defines, errPrefix) { var key = pass._programKey = pass._programKey || this.getKey(pass._programName, defines); var program = this._cache[key]; if (program) return program; var tmpl = this._templates[pass._programName]; var customDef = _generateDefines(tmpl.defines, defines); var vert = _replaceMacroNums(tmpl.vert, tmpl.defines, defines); vert = customDef + _unrollLoops(vert); this._highpSupported || (vert = _replaceHighp(vert)); var frag = _replaceMacroNums(tmpl.frag, tmpl.defines, defines); frag = customDef + _unrollLoops(frag); this._highpSupported || (frag = _replaceHighp(frag)); program = new _gfx["default"].Program(this._device, { vert: vert, frag: frag }); var errors = program.link(); if (errors) { var vertLines = vert.split("\n"); var fragLines = frag.split("\n"); var defineLength = tmpl.defines.length; errors.forEach((function(err) { var line = err.line - 1; var originLine = err.line - defineLength; var lines = "vs" === err.type ? vertLines : fragLines; var source = lines[line]; var info = err.info || "Failed to compile " + err.type + " " + err.fileID + " (ln " + originLine + "): \n " + err.message + ": \n " + source; cc.error(errPrefix + " : " + info); })); } this._cache[key] = program; return program; }; _proto._checkPrecision = function _checkPrecision() { var gl = this._device._gl; var highpSupported = false; if (gl.getShaderPrecisionFormat) { var vertHighp = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT); var fragHighp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); highpSupported = vertHighp && vertHighp.precision > 0 && fragHighp && fragHighp.precision > 0; } highpSupported || cc.warnID(9102); this._highpSupported = highpSupported; }; return ProgramLib; })(); exports["default"] = ProgramLib; module.exports = exports["default"]; }), { "../gfx": 259 } ], 252: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var Technique = (function() { function Technique(name, passes) { this._name = name; this._passes = passes; } var _proto = Technique.prototype; _proto.clone = function clone() { var passes = []; for (var i = 0; i < this._passes.length; i++) passes.push(this._passes[i].clone()); return new Technique(this._name, passes); }; _createClass(Technique, [ { key: "name", get: function get() { return this._name; } }, { key: "passes", get: function get() { return this._passes; } } ]); return Technique; })(); exports["default"] = Technique; module.exports = exports["default"]; }), {} ], 253: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueTypes = require("../../core/value-types"); var _enums = _interopRequireDefault(require("../enums")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _m4_tmp = new _valueTypes.Mat4(); var _genID = 0; var View = (function() { function View() { this._id = _genID++; this._priority = 0; this._rect = { x: 0, y: 0, w: 1, h: 1 }; this._color = new _valueTypes.Vec4(.3, .3, .3, 1); this._depth = 1; this._stencil = 0; this._clearFlags = _enums["default"].CLEAR_COLOR | _enums["default"].CLEAR_DEPTH; this._clearModel = null; this._matView = cc.mat4(); this._matViewInv = cc.mat4(); this._matProj = cc.mat4(); this._matViewProj = cc.mat4(); this._matInvViewProj = cc.mat4(); this._stages = []; this._cullingByID = false; this._framebuffer = null; this._shadowLight = null; this._cullingMask = 4294967295; } var _proto = View.prototype; _proto.getForward = function getForward(out) { var m = this._matView.m; return _valueTypes.Vec3.set(out, -m[2], -m[6], -m[10]); }; _proto.getPosition = function getPosition(out) { _valueTypes.Mat4.invert(_m4_tmp, this._matView); return _valueTypes.Mat4.getTranslation(out, _m4_tmp); }; return View; })(); exports["default"] = View; module.exports = exports["default"]; }), { "../../core/value-types": 232, "../enums": 254 } ], 254: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _mappings = require("./build/mappings"); var _default = { PROJ_PERSPECTIVE: 0, PROJ_ORTHO: 1, LIGHT_DIRECTIONAL: 0, LIGHT_POINT: 1, LIGHT_SPOT: 2, LIGHT_AMBIENT: 3, SHADOW_NONE: 0, SHADOW_HARD: 1, SHADOW_SOFT: 2, PARAM_INT: _mappings.typeMap["int"], PARAM_INT2: _mappings.typeMap.ivec2, PARAM_INT3: _mappings.typeMap.ivec3, PARAM_INT4: _mappings.typeMap.ivec4, PARAM_FLOAT: _mappings.typeMap["float"], PARAM_FLOAT2: _mappings.typeMap.vec2, PARAM_FLOAT3: _mappings.typeMap.vec3, PARAM_FLOAT4: _mappings.typeMap.vec4, PARAM_MAT2: _mappings.typeMap.mat2, PARAM_MAT3: _mappings.typeMap.mat3, PARAM_MAT4: _mappings.typeMap.mat4, PARAM_TEXTURE_2D: _mappings.typeMap.sampler2D, PARAM_TEXTURE_CUBE: _mappings.typeMap.samplerCube, CLEAR_COLOR: 1, CLEAR_DEPTH: 2, CLEAR_STENCIL: 4, CLEAR_SKYBOX: 8, BUFFER_VIEW_INT8: 0, BUFFER_VIEW_UINT8: 1, BUFFER_VIEW_INT16: 2, BUFFER_VIEW_UINT16: 3, BUFFER_VIEW_INT32: 4, BUFFER_VIEW_UINT32: 5, BUFFER_VIEW_FLOAT32: 6 }; exports["default"] = _default; module.exports = exports["default"]; }), { "./build/mappings": 247 } ], 255: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _state = _interopRequireDefault(require("./state")); var _enums = require("./enums"); var _texture2d = _interopRequireDefault(require("./texture-2d")); var _textureCube = _interopRequireDefault(require("./texture-cube")); var _type2uniformCommit2, _type2uniformArrayCom; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var GL_INT = 5124; var GL_FLOAT = 5126; var GL_FLOAT_VEC2 = 35664; var GL_FLOAT_VEC3 = 35665; var GL_FLOAT_VEC4 = 35666; var GL_INT_VEC2 = 35667; var GL_INT_VEC3 = 35668; var GL_INT_VEC4 = 35669; var GL_BOOL = 35670; var GL_BOOL_VEC2 = 35671; var GL_BOOL_VEC3 = 35672; var GL_BOOL_VEC4 = 35673; var GL_FLOAT_MAT2 = 35674; var GL_FLOAT_MAT3 = 35675; var GL_FLOAT_MAT4 = 35676; var GL_SAMPLER_2D = 35678; var GL_SAMPLER_CUBE = 35680; var _type2uniformCommit = (_type2uniformCommit2 = {}, _type2uniformCommit2[GL_INT] = function(gl, id, value) { gl.uniform1i(id, value); }, _type2uniformCommit2[GL_FLOAT] = function(gl, id, value) { gl.uniform1f(id, value); }, _type2uniformCommit2[GL_FLOAT_VEC2] = function(gl, id, value) { gl.uniform2fv(id, value); }, _type2uniformCommit2[GL_FLOAT_VEC3] = function(gl, id, value) { gl.uniform3fv(id, value); }, _type2uniformCommit2[GL_FLOAT_VEC4] = function(gl, id, value) { gl.uniform4fv(id, value); }, _type2uniformCommit2[GL_INT_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }, _type2uniformCommit2[GL_INT_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }, _type2uniformCommit2[GL_INT_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }, _type2uniformCommit2[GL_BOOL] = function(gl, id, value) { gl.uniform1i(id, value); }, _type2uniformCommit2[GL_BOOL_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }, _type2uniformCommit2[GL_BOOL_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }, _type2uniformCommit2[GL_BOOL_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }, _type2uniformCommit2[GL_FLOAT_MAT2] = function(gl, id, value) { gl.uniformMatrix2fv(id, false, value); }, _type2uniformCommit2[GL_FLOAT_MAT3] = function(gl, id, value) { gl.uniformMatrix3fv(id, false, value); }, _type2uniformCommit2[GL_FLOAT_MAT4] = function(gl, id, value) { gl.uniformMatrix4fv(id, false, value); }, _type2uniformCommit2[GL_SAMPLER_2D] = function(gl, id, value) { gl.uniform1i(id, value); }, _type2uniformCommit2[GL_SAMPLER_CUBE] = function(gl, id, value) { gl.uniform1i(id, value); }, _type2uniformCommit2); var _type2uniformArrayCommit = (_type2uniformArrayCom = {}, _type2uniformArrayCom[GL_INT] = function(gl, id, value) { gl.uniform1iv(id, value); }, _type2uniformArrayCom[GL_FLOAT] = function(gl, id, value) { gl.uniform1fv(id, value); }, _type2uniformArrayCom[GL_FLOAT_VEC2] = function(gl, id, value) { gl.uniform2fv(id, value); }, _type2uniformArrayCom[GL_FLOAT_VEC3] = function(gl, id, value) { gl.uniform3fv(id, value); }, _type2uniformArrayCom[GL_FLOAT_VEC4] = function(gl, id, value) { gl.uniform4fv(id, value); }, _type2uniformArrayCom[GL_INT_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }, _type2uniformArrayCom[GL_INT_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }, _type2uniformArrayCom[GL_INT_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }, _type2uniformArrayCom[GL_BOOL] = function(gl, id, value) { gl.uniform1iv(id, value); }, _type2uniformArrayCom[GL_BOOL_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }, _type2uniformArrayCom[GL_BOOL_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }, _type2uniformArrayCom[GL_BOOL_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }, _type2uniformArrayCom[GL_FLOAT_MAT2] = function(gl, id, value) { gl.uniformMatrix2fv(id, false, value); }, _type2uniformArrayCom[GL_FLOAT_MAT3] = function(gl, id, value) { gl.uniformMatrix3fv(id, false, value); }, _type2uniformArrayCom[GL_FLOAT_MAT4] = function(gl, id, value) { gl.uniformMatrix4fv(id, false, value); }, _type2uniformArrayCom[GL_SAMPLER_2D] = function(gl, id, value) { gl.uniform1iv(id, value); }, _type2uniformArrayCom[GL_SAMPLER_CUBE] = function(gl, id, value) { gl.uniform1iv(id, value); }, _type2uniformArrayCom); function _commitBlendStates(gl, cur, next) { if (cur.blend !== next.blend) { if (!next.blend) { gl.disable(gl.BLEND); return; } gl.enable(gl.BLEND); next.blendSrc !== _enums.enums.BLEND_CONSTANT_COLOR && next.blendSrc !== _enums.enums.BLEND_ONE_MINUS_CONSTANT_COLOR && next.blendDst !== _enums.enums.BLEND_CONSTANT_COLOR && next.blendDst !== _enums.enums.BLEND_ONE_MINUS_CONSTANT_COLOR || gl.blendColor((next.blendColor >> 24) / 255, (next.blendColor >> 16 & 255) / 255, (next.blendColor >> 8 & 255) / 255, (255 & next.blendColor) / 255); if (next.blendSep) { gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); } else { gl.blendFunc(next.blendSrc, next.blendDst); gl.blendEquation(next.blendEq); } return; } if (false === next.blend) return; cur.blendColor !== next.blendColor && gl.blendColor((next.blendColor >> 24) / 255, (next.blendColor >> 16 & 255) / 255, (next.blendColor >> 8 & 255) / 255, (255 & next.blendColor) / 255); if (cur.blendSep !== next.blendSep) { if (next.blendSep) { gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); } else { gl.blendFunc(next.blendSrc, next.blendDst); gl.blendEquation(next.blendEq); } return; } if (next.blendSep) { cur.blendSrc === next.blendSrc && cur.blendDst === next.blendDst && cur.blendSrcAlpha === next.blendSrcAlpha && cur.blendDstAlpha === next.blendDstAlpha || gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); cur.blendEq === next.blendEq && cur.blendAlphaEq === next.blendAlphaEq || gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); } else { cur.blendSrc === next.blendSrc && cur.blendDst === next.blendDst || gl.blendFunc(next.blendSrc, next.blendDst); cur.blendEq !== next.blendEq && gl.blendEquation(next.blendEq); } } function _commitDepthStates(gl, cur, next) { if (cur.depthTest !== next.depthTest) { if (!next.depthTest) { gl.disable(gl.DEPTH_TEST); return; } gl.enable(gl.DEPTH_TEST); gl.depthFunc(next.depthFunc); gl.depthMask(next.depthWrite); return; } cur.depthWrite !== next.depthWrite && gl.depthMask(next.depthWrite); if (false === next.depthTest) { if (next.depthWrite) { next.depthTest = true; next.depthFunc = _enums.enums.DS_FUNC_ALWAYS; gl.enable(gl.DEPTH_TEST); gl.depthFunc(next.depthFunc); } return; } cur.depthFunc !== next.depthFunc && gl.depthFunc(next.depthFunc); } function _commitStencilStates(gl, cur, next) { if (next.stencilTest === _enums.enums.STENCIL_INHERIT) return; if (next.stencilTest !== cur.stencilTest) { if (next.stencilTest === _enums.enums.STENCIL_DISABLE) { gl.disable(gl.STENCIL_TEST); return; } gl.enable(gl.STENCIL_TEST); if (next.stencilSep) { gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); } else { gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMask(next.stencilWriteMaskFront); gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); } return; } if (next.stencilTest === _enums.enums.STENCIL_DISABLE) return; if (cur.stencilSep !== next.stencilSep) { if (next.stencilSep) { gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); } else { gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMask(next.stencilWriteMaskFront); gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); } return; } if (next.stencilSep) { cur.stencilFuncFront === next.stencilFuncFront && cur.stencilRefFront === next.stencilRefFront && cur.stencilMaskFront === next.stencilMaskFront || gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); cur.stencilWriteMaskFront !== next.stencilWriteMaskFront && gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); cur.stencilFailOpFront === next.stencilFailOpFront && cur.stencilZFailOpFront === next.stencilZFailOpFront && cur.stencilZPassOpFront === next.stencilZPassOpFront || gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); cur.stencilFuncBack === next.stencilFuncBack && cur.stencilRefBack === next.stencilRefBack && cur.stencilMaskBack === next.stencilMaskBack || gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); cur.stencilWriteMaskBack !== next.stencilWriteMaskBack && gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); cur.stencilFailOpBack === next.stencilFailOpBack && cur.stencilZFailOpBack === next.stencilZFailOpBack && cur.stencilZPassOpBack === next.stencilZPassOpBack || gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); } else { cur.stencilFuncFront === next.stencilFuncFront && cur.stencilRefFront === next.stencilRefFront && cur.stencilMaskFront === next.stencilMaskFront || gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); cur.stencilWriteMaskFront !== next.stencilWriteMaskFront && gl.stencilMask(next.stencilWriteMaskFront); cur.stencilFailOpFront === next.stencilFailOpFront && cur.stencilZFailOpFront === next.stencilZFailOpFront && cur.stencilZPassOpFront === next.stencilZPassOpFront || gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); } } function _commitCullMode(gl, cur, next) { if (cur.cullMode === next.cullMode) return; if (next.cullMode === _enums.enums.CULL_NONE) { gl.disable(gl.CULL_FACE); return; } gl.enable(gl.CULL_FACE); gl.cullFace(next.cullMode); } function _commitVertexBuffers(device, gl, cur, next) { var attrsDirty = false; if (-1 === next.maxStream) return; if (cur.maxStream !== next.maxStream) attrsDirty = true; else if (cur.program !== next.program) attrsDirty = true; else for (var i = 0; i < next.maxStream + 1; ++i) if (cur.vertexBuffers[i] !== next.vertexBuffers[i] || cur.vertexBufferOffsets[i] !== next.vertexBufferOffsets[i]) { attrsDirty = true; break; } if (attrsDirty) { for (var _i = 0; _i < device._caps.maxVertexAttribs; ++_i) device._newAttributes[_i] = 0; for (var _i2 = 0; _i2 < next.maxStream + 1; ++_i2) { var vb = next.vertexBuffers[_i2]; var vbOffset = next.vertexBufferOffsets[_i2]; if (!vb || -1 === vb._glID) continue; gl.bindBuffer(gl.ARRAY_BUFFER, vb._glID); for (var j = 0; j < next.program._attributes.length; ++j) { var attr = next.program._attributes[j]; var el = vb._format.element(attr.name); if (!el) { console.warn("Can not find vertex attribute: " + attr.name); continue; } if (0 === device._enabledAttributes[attr.location]) { gl.enableVertexAttribArray(attr.location); device._enabledAttributes[attr.location] = 1; } device._newAttributes[attr.location] = 1; gl.vertexAttribPointer(attr.location, el.num, el.type, el.normalize, el.stride, el.offset + vbOffset * el.stride); } } for (var _i3 = 0; _i3 < device._caps.maxVertexAttribs; ++_i3) if (device._enabledAttributes[_i3] !== device._newAttributes[_i3]) { gl.disableVertexAttribArray(_i3); device._enabledAttributes[_i3] = 0; } } } function _commitTextures(gl, cur, next) { for (var i = 0; i < next.maxTextureSlot + 1; ++i) if (cur.textureUnits[i] !== next.textureUnits[i]) { var texture = next.textureUnits[i]; if (texture && -1 !== texture._glID) { gl.activeTexture(gl.TEXTURE0 + i); gl.bindTexture(texture._target, texture._glID); } } } function _attach(gl, location, attachment, face) { void 0 === face && (face = 0); attachment instanceof _texture2d["default"] ? gl.framebufferTexture2D(gl.FRAMEBUFFER, location, gl.TEXTURE_2D, attachment._glID, 0) : attachment instanceof _textureCube["default"] ? gl.framebufferTexture2D(gl.FRAMEBUFFER, location, gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, attachment._glID, 0) : gl.framebufferRenderbuffer(gl.FRAMEBUFFER, location, gl.RENDERBUFFER, attachment._glID); } var Device = (function() { function Device(canvasEL, opts) { var gl; opts = opts || {}; void 0 === opts.alpha && (opts.alpha = false); void 0 === opts.stencil && (opts.stencil = true); void 0 === opts.depth && (opts.depth = true); void 0 === opts.antialias && (opts.antialias = false); void 0 === opts.preserveDrawingBuffer && (opts.preserveDrawingBuffer = false); try { gl = canvasEL.getContext("webgl", opts) || canvasEL.getContext("experimental-webgl", opts) || canvasEL.getContext("webkit-3d", opts) || canvasEL.getContext("moz-webgl", opts); } catch (err) { console.error(err); return; } gl || console.error("This device does not support webgl"); this._gl = gl; this._extensions = {}; this._caps = {}; this._stats = { texture: 0, vb: 0, ib: 0, drawcalls: 0 }; this._initExtensions([ "EXT_texture_filter_anisotropic", "EXT_shader_texture_lod", "OES_standard_derivatives", "OES_texture_float", "OES_texture_float_linear", "OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object", "WEBGL_compressed_texture_atc", "WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1", "WEBGL_compressed_texture_pvrtc", "WEBGL_compressed_texture_s3tc", "WEBGL_depth_texture", "WEBGL_draw_buffers" ]); this._initCaps(); this._initStates(); _state["default"].initDefault(this); this._current = new _state["default"](this); this._next = new _state["default"](this); this._uniforms = {}; this._vx = this._vy = this._vw = this._vh = 0; this._sx = this._sy = this._sw = this._sh = 0; this._framebuffer = null; this._enabledAttributes = new Array(this._caps.maxVertexAttribs); this._newAttributes = new Array(this._caps.maxVertexAttribs); for (var i = 0; i < this._caps.maxVertexAttribs; ++i) { this._enabledAttributes[i] = 0; this._newAttributes[i] = 0; } } var _proto = Device.prototype; _proto._initExtensions = function _initExtensions(extensions) { var gl = this._gl; for (var i = 0; i < extensions.length; ++i) { var name = extensions[i]; var vendorPrefixes = [ "", "WEBKIT_", "MOZ_" ]; for (var j = 0; j < vendorPrefixes.length; j++) try { var ext = gl.getExtension(vendorPrefixes[j] + name); if (ext) { this._extensions[name] = ext; break; } } catch (e) { console.error(e); } } }; _proto._initCaps = function _initCaps() { var gl = this._gl; var extDrawBuffers = this.ext("WEBGL_draw_buffers"); this._caps.maxVertexStreams = 4; this._caps.maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); this._caps.maxFragUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); this._caps.maxVertexAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); this._caps.maxDrawBuffers = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_DRAW_BUFFERS_WEBGL) : 1; this._caps.maxColorAttachments = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_COLOR_ATTACHMENTS_WEBGL) : 1; }; _proto._initStates = function _initStates() { var gl = this._gl; gl.disable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ZERO); gl.blendEquation(gl.FUNC_ADD); gl.blendColor(1, 1, 1, 1); gl.colorMask(true, true, true, true); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); gl.disable(gl.DEPTH_TEST); gl.depthFunc(gl.LESS); gl.depthMask(false); gl.disable(gl.POLYGON_OFFSET_FILL); gl.depthRange(0, 1); gl.disable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 0, 255); gl.stencilMask(255); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); gl.clearDepth(1); gl.clearColor(0, 0, 0, 0); gl.clearStencil(0); gl.disable(gl.SCISSOR_TEST); }; _proto._restoreTexture = function _restoreTexture(unit) { var gl = this._gl; var texture = this._current.textureUnits[unit]; texture && -1 !== texture._glID ? gl.bindTexture(texture._target, texture._glID) : gl.bindTexture(gl.TEXTURE_2D, null); }; _proto._restoreIndexBuffer = function _restoreIndexBuffer() { var gl = this._gl; var ib = this._current.indexBuffer; ib && -1 !== ib._glID ? gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib._glID) : gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); }; _proto.ext = function ext(name) { return this._extensions[name]; }; _proto.allowFloatTexture = function allowFloatTexture() { return null != this.ext("OES_texture_float"); }; _proto.setFrameBuffer = function setFrameBuffer(fb) { if (this._framebuffer === fb) return; this._framebuffer = fb; var gl = this._gl; if (!fb) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, fb._glID); var numColors = fb._colors.length; for (var i = 0; i < numColors; ++i) { var colorBuffer = fb._colors[i]; _attach(gl, gl.COLOR_ATTACHMENT0 + i, colorBuffer); } for (var _i4 = numColors; _i4 < this._caps.maxColorAttachments; ++_i4) gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i4, gl.TEXTURE_2D, null, 0); fb._depth && _attach(gl, gl.DEPTH_ATTACHMENT, fb._depth); fb._stencil && _attach(gl, gl.STENCIL_ATTACHMENT, fb._stencil); fb._depthStencil && _attach(gl, gl.DEPTH_STENCIL_ATTACHMENT, fb._depthStencil); }; _proto.setViewport = function setViewport(x, y, w, h) { if (this._vx !== x || this._vy !== y || this._vw !== w || this._vh !== h) { this._gl.viewport(x, y, w, h); this._vx = x; this._vy = y; this._vw = w; this._vh = h; } }; _proto.setScissor = function setScissor(x, y, w, h) { if (this._sx !== x || this._sy !== y || this._sw !== w || this._sh !== h) { this._gl.scissor(x, y, w, h); this._sx = x; this._sy = y; this._sw = w; this._sh = h; } }; _proto.clear = function clear(opts) { if (void 0 === opts.color && void 0 === opts.depth && void 0 === opts.stencil) return; var gl = this._gl; var flags = 0; if (void 0 !== opts.color) { flags |= gl.COLOR_BUFFER_BIT; gl.clearColor(opts.color[0], opts.color[1], opts.color[2], opts.color[3]); } if (void 0 !== opts.depth) { flags |= gl.DEPTH_BUFFER_BIT; gl.clearDepth(opts.depth); gl.enable(gl.DEPTH_TEST); gl.depthMask(true); gl.depthFunc(gl.ALWAYS); } if (void 0 !== opts.stencil) { flags |= gl.STENCIL_BUFFER_BIT; gl.clearStencil(opts.stencil); } gl.clear(flags); if (void 0 !== opts.depth) if (false === this._current.depthTest) gl.disable(gl.DEPTH_TEST); else { false === this._current.depthWrite && gl.depthMask(false); this._current.depthFunc !== _enums.enums.DS_FUNC_ALWAYS && gl.depthFunc(this._current.depthFunc); } }; _proto.enableBlend = function enableBlend() { this._next.blend = true; }; _proto.enableDepthTest = function enableDepthTest() { this._next.depthTest = true; }; _proto.enableDepthWrite = function enableDepthWrite() { this._next.depthWrite = true; }; _proto.setStencilTest = function setStencilTest(stencilTest) { this._next.stencilTest = stencilTest; }; _proto.setStencilFunc = function setStencilFunc(func, ref, mask) { this._next.stencilSep = false; this._next.stencilFuncFront = this._next.stencilFuncBack = func; this._next.stencilRefFront = this._next.stencilRefBack = ref; this._next.stencilMaskFront = this._next.stencilMaskBack = mask; }; _proto.setStencilFuncFront = function setStencilFuncFront(func, ref, mask) { this._next.stencilSep = true; this._next.stencilFuncFront = func; this._next.stencilRefFront = ref; this._next.stencilMaskFront = mask; }; _proto.setStencilFuncBack = function setStencilFuncBack(func, ref, mask) { this._next.stencilSep = true; this._next.stencilFuncBack = func; this._next.stencilRefBack = ref; this._next.stencilMaskBack = mask; }; _proto.setStencilOp = function setStencilOp(failOp, zFailOp, zPassOp, writeMask) { this._next.stencilFailOpFront = this._next.stencilFailOpBack = failOp; this._next.stencilZFailOpFront = this._next.stencilZFailOpBack = zFailOp; this._next.stencilZPassOpFront = this._next.stencilZPassOpBack = zPassOp; this._next.stencilWriteMaskFront = this._next.stencilWriteMaskBack = writeMask; }; _proto.setStencilOpFront = function setStencilOpFront(failOp, zFailOp, zPassOp, writeMask) { this._next.stencilSep = true; this._next.stencilFailOpFront = failOp; this._next.stencilZFailOpFront = zFailOp; this._next.stencilZPassOpFront = zPassOp; this._next.stencilWriteMaskFront = writeMask; }; _proto.setStencilOpBack = function setStencilOpBack(failOp, zFailOp, zPassOp, writeMask) { this._next.stencilSep = true; this._next.stencilFailOpBack = failOp; this._next.stencilZFailOpBack = zFailOp; this._next.stencilZPassOpBack = zPassOp; this._next.stencilWriteMaskBack = writeMask; }; _proto.setDepthFunc = function setDepthFunc(depthFunc) { this._next.depthFunc = depthFunc; }; _proto.setBlendColor32 = function setBlendColor32(rgba) { this._next.blendColor = rgba; }; _proto.setBlendColor = function setBlendColor(r, g, b, a) { this._next.blendColor = (255 * r << 24 | 255 * g << 16 | 255 * b << 8 | 255 * a) >>> 0; }; _proto.setBlendFunc = function setBlendFunc(src, dst) { this._next.blendSep = false; this._next.blendSrc = src; this._next.blendDst = dst; }; _proto.setBlendFuncSep = function setBlendFuncSep(src, dst, srcAlpha, dstAlpha) { this._next.blendSep = true; this._next.blendSrc = src; this._next.blendDst = dst; this._next.blendSrcAlpha = srcAlpha; this._next.blendDstAlpha = dstAlpha; }; _proto.setBlendEq = function setBlendEq(eq) { this._next.blendSep = false; this._next.blendEq = eq; }; _proto.setBlendEqSep = function setBlendEqSep(eq, alphaEq) { this._next.blendSep = true; this._next.blendEq = eq; this._next.blendAlphaEq = alphaEq; }; _proto.setCullMode = function setCullMode(mode) { this._next.cullMode = mode; }; _proto.setVertexBuffer = function setVertexBuffer(stream, buffer, start) { void 0 === start && (start = 0); this._next.vertexBuffers[stream] = buffer; this._next.vertexBufferOffsets[stream] = start; this._next.maxStream < stream && (this._next.maxStream = stream); }; _proto.setIndexBuffer = function setIndexBuffer(buffer) { this._next.indexBuffer = buffer; }; _proto.setProgram = function setProgram(program) { this._next.program = program; }; _proto.setTexture = function setTexture(name, texture, slot) { if (slot >= this._caps.maxTextureUnits) { console.warn("Can not set texture " + name + " at stage " + slot + ", max texture exceed: " + this._caps.maxTextureUnits); return; } this._next.textureUnits[slot] = texture; this.setUniform(name, slot); this._next.maxTextureSlot < slot && (this._next.maxTextureSlot = slot); }; _proto.setTextureArray = function setTextureArray(name, textures, slots) { var len = textures.length; if (len >= this._caps.maxTextureUnits) { console.warn("Can not set " + len + " textures for " + name + ", max texture exceed: " + this._caps.maxTextureUnits); return; } for (var i = 0; i < len; ++i) { var slot = slots[i]; this._next.textureUnits[slot] = textures[i]; this._next.maxTextureSlot < slot && (this._next.maxTextureSlot = slot); } this.setUniform(name, slots); }; _proto.setUniform = function setUniform(name, value) { var uniform = this._uniforms[name]; var sameType = false; var isArray = false, isFloat32Array = false, isInt32Array = false; do { if (!uniform) break; isFloat32Array = Array.isArray(value) || value instanceof Float32Array; isInt32Array = value instanceof Int32Array; isArray = isFloat32Array || isInt32Array; if (uniform.isArray !== isArray) break; if (uniform.isArray && uniform.value.length !== value.length) break; sameType = true; } while (false); if (sameType) { var oldValue = uniform.value; var dirty = false; if (uniform.isArray) { for (var i = 0, l = oldValue.length; i < l; i++) if (oldValue[i] !== value[i]) { dirty = true; oldValue[i] = value[i]; } } else if (oldValue !== value) { dirty = true; uniform.value = value; } dirty && (uniform.dirty = true); } else { var newValue = value; isFloat32Array ? newValue = new Float32Array(value) : isInt32Array && (newValue = new Int32Array(value)); uniform = { dirty: true, value: newValue, isArray: isArray }; } this._uniforms[name] = uniform; }; _proto.setUniformDirectly = function setUniformDirectly(name, value) { var uniform = this._uniforms[name]; uniform || (this._uniforms[name] = uniform = {}); uniform.dirty = true; uniform.value = value; }; _proto.setPrimitiveType = function setPrimitiveType(type) { this._next.primitiveType = type; }; _proto.resetDrawCalls = function resetDrawCalls() { this._stats.drawcalls = 0; }; _proto.getDrawCalls = function getDrawCalls() { return this._stats.drawcalls; }; _proto.draw = function draw(base, count) { var gl = this._gl; var cur = this._current; var next = this._next; _commitBlendStates(gl, cur, next); _commitDepthStates(gl, cur, next); _commitStencilStates(gl, cur, next); _commitCullMode(gl, cur, next); _commitVertexBuffers(this, gl, cur, next); cur.indexBuffer !== next.indexBuffer && gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, next.indexBuffer && -1 !== next.indexBuffer._glID ? next.indexBuffer._glID : null); var programDirty = false; if (cur.program !== next.program) { next.program._linked ? gl.useProgram(next.program._glID) : console.warn("Failed to use program: has not linked yet."); programDirty = true; } _commitTextures(gl, cur, next); for (var i = 0; i < next.program._uniforms.length; ++i) { var uniformInfo = next.program._uniforms[i]; var uniform = this._uniforms[uniformInfo.name]; if (!uniform) continue; if (!programDirty && !uniform.dirty) continue; uniform.dirty = false; var commitFunc = void 0 === uniformInfo.size ? _type2uniformCommit[uniformInfo.type] : _type2uniformArrayCommit[uniformInfo.type]; if (!commitFunc) { console.warn("Can not find commit function for uniform " + uniformInfo.name); continue; } commitFunc(gl, uniformInfo.location, uniform.value); } if (count) { next.indexBuffer ? gl.drawElements(this._next.primitiveType, count, next.indexBuffer._format, base * next.indexBuffer._bytesPerIndex) : gl.drawArrays(this._next.primitiveType, base, count); this._stats.drawcalls++; } cur.set(next); next.reset(); }; _createClass(Device, [ { key: "caps", get: function get() { return this._caps; } } ]); return Device; })(); exports["default"] = Device; module.exports = exports["default"]; }), { "./enums": 256, "./state": 263, "./texture-2d": 264, "./texture-cube": 265 } ], 256: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.attrTypeBytes = attrTypeBytes; exports.enums = void 0; exports.glFilter = glFilter; exports.glTextureFmt = glTextureFmt; var GL_NEAREST = 9728; var GL_LINEAR = 9729; var GL_NEAREST_MIPMAP_NEAREST = 9984; var GL_LINEAR_MIPMAP_NEAREST = 9985; var GL_NEAREST_MIPMAP_LINEAR = 9986; var GL_LINEAR_MIPMAP_LINEAR = 9987; var GL_UNSIGNED_BYTE = 5121; var GL_UNSIGNED_SHORT = 5123; var GL_UNSIGNED_INT = 5125; var GL_FLOAT = 5126; var GL_UNSIGNED_SHORT_5_6_5 = 33635; var GL_UNSIGNED_SHORT_4_4_4_4 = 32819; var GL_UNSIGNED_SHORT_5_5_5_1 = 32820; var GL_HALF_FLOAT_OES = 36193; var GL_DEPTH_COMPONENT = 6402; var GL_ALPHA = 6406; var GL_RGB = 6407; var GL_RGBA = 6408; var GL_LUMINANCE = 6409; var GL_LUMINANCE_ALPHA = 6410; var GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 33776; var GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 33777; var GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 33778; var GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 33779; var GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 35840; var GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 35841; var GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 35842; var GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 35843; var GL_COMPRESSED_RGB_ETC1_WEBGL = 36196; var GL_COMPRESSED_RGB8_ETC2 = 37492; var GL_COMPRESSED_RGBA8_ETC2_EAC = 37496; var _filterGL = [ [ GL_NEAREST, GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR ], [ GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_LINEAR ] ]; var _textureFmtGL = [ { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_S3TC_DXT1_EXT, pixelType: null }, { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixelType: null }, { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, pixelType: null }, { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, pixelType: null }, { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_ETC1_WEBGL, pixelType: null }, { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, pixelType: null }, { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, pixelType: null }, { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, pixelType: null }, { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, pixelType: null }, { format: GL_ALPHA, internalFormat: GL_ALPHA, pixelType: GL_UNSIGNED_BYTE }, { format: GL_LUMINANCE, internalFormat: GL_LUMINANCE, pixelType: GL_UNSIGNED_BYTE }, { format: GL_LUMINANCE_ALPHA, internalFormat: GL_LUMINANCE_ALPHA, pixelType: GL_UNSIGNED_BYTE }, { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_UNSIGNED_SHORT_5_6_5 }, { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_SHORT_5_5_5_1 }, { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_SHORT_4_4_4_4 }, { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_UNSIGNED_BYTE }, { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_BYTE }, { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_HALF_FLOAT_OES }, { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_HALF_FLOAT_OES }, { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_FLOAT }, { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_FLOAT }, { format: null, internalFormat: null, pixelType: null }, { format: null, internalFormat: null, pixelType: null }, { format: null, internalFormat: null, pixelType: null }, { format: null, internalFormat: null, pixelType: null }, { format: GL_DEPTH_COMPONENT, internalFormat: GL_DEPTH_COMPONENT, pixelType: GL_UNSIGNED_SHORT }, { format: GL_DEPTH_COMPONENT, internalFormat: GL_DEPTH_COMPONENT, pixelType: GL_UNSIGNED_INT }, { format: GL_DEPTH_COMPONENT, internalFormat: GL_DEPTH_COMPONENT, pixelType: GL_UNSIGNED_INT }, { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB8_ETC2, pixelType: null }, { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA8_ETC2_EAC, pixelType: null } ]; var enums = { USAGE_STATIC: 35044, USAGE_DYNAMIC: 35048, USAGE_STREAM: 35040, INDEX_FMT_UINT8: 5121, INDEX_FMT_UINT16: 5123, INDEX_FMT_UINT32: 5125, ATTR_POSITION: "a_position", ATTR_NORMAL: "a_normal", ATTR_TANGENT: "a_tangent", ATTR_BITANGENT: "a_bitangent", ATTR_WEIGHTS: "a_weights", ATTR_JOINTS: "a_joints", ATTR_COLOR: "a_color", ATTR_COLOR0: "a_color0", ATTR_COLOR1: "a_color1", ATTR_UV: "a_uv", ATTR_UV0: "a_uv0", ATTR_UV1: "a_uv1", ATTR_UV2: "a_uv2", ATTR_UV3: "a_uv3", ATTR_UV4: "a_uv4", ATTR_UV5: "a_uv5", ATTR_UV6: "a_uv6", ATTR_UV7: "a_uv7", ATTR_TEX_COORD: "a_texCoord", ATTR_TEX_COORD1: "a_texCoord1", ATTR_TEX_COORD2: "a_texCoord2", ATTR_TEX_COORD3: "a_texCoord3", ATTR_TEX_COORD4: "a_texCoord4", ATTR_TEX_COORD5: "a_texCoord5", ATTR_TEX_COORD6: "a_texCoord6", ATTR_TEX_COORD7: "a_texCoord7", ATTR_TEX_COORD8: "a_texCoord8", ATTR_TEX_ID: "a_texId", ATTR_TYPE_INT8: 5120, ATTR_TYPE_UINT8: 5121, ATTR_TYPE_INT16: 5122, ATTR_TYPE_UINT16: 5123, ATTR_TYPE_INT32: 5124, ATTR_TYPE_UINT32: 5125, ATTR_TYPE_FLOAT32: 5126, FILTER_NEAREST: 0, FILTER_LINEAR: 1, WRAP_REPEAT: 10497, WRAP_CLAMP: 33071, WRAP_MIRROR: 33648, TEXTURE_FMT_RGB_DXT1: 0, TEXTURE_FMT_RGBA_DXT1: 1, TEXTURE_FMT_RGBA_DXT3: 2, TEXTURE_FMT_RGBA_DXT5: 3, TEXTURE_FMT_RGB_ETC1: 4, TEXTURE_FMT_RGB_PVRTC_2BPPV1: 5, TEXTURE_FMT_RGBA_PVRTC_2BPPV1: 6, TEXTURE_FMT_RGB_PVRTC_4BPPV1: 7, TEXTURE_FMT_RGBA_PVRTC_4BPPV1: 8, TEXTURE_FMT_A8: 9, TEXTURE_FMT_L8: 10, TEXTURE_FMT_L8_A8: 11, TEXTURE_FMT_R5_G6_B5: 12, TEXTURE_FMT_R5_G5_B5_A1: 13, TEXTURE_FMT_R4_G4_B4_A4: 14, TEXTURE_FMT_RGB8: 15, TEXTURE_FMT_RGBA8: 16, TEXTURE_FMT_RGB16F: 17, TEXTURE_FMT_RGBA16F: 18, TEXTURE_FMT_RGB32F: 19, TEXTURE_FMT_RGBA32F: 20, TEXTURE_FMT_R32F: 21, TEXTURE_FMT_111110F: 22, TEXTURE_FMT_SRGB: 23, TEXTURE_FMT_SRGBA: 24, TEXTURE_FMT_D16: 25, TEXTURE_FMT_D32: 26, TEXTURE_FMT_D24S8: 27, TEXTURE_FMT_RGB_ETC2: 28, TEXTURE_FMT_RGBA_ETC2: 29, DS_FUNC_NEVER: 512, DS_FUNC_LESS: 513, DS_FUNC_EQUAL: 514, DS_FUNC_LEQUAL: 515, DS_FUNC_GREATER: 516, DS_FUNC_NOTEQUAL: 517, DS_FUNC_GEQUAL: 518, DS_FUNC_ALWAYS: 519, RB_FMT_RGBA4: 32854, RB_FMT_RGB5_A1: 32855, RB_FMT_RGB565: 36194, RB_FMT_D16: 33189, RB_FMT_S8: 36168, RB_FMT_D24S8: 34041, BLEND_FUNC_ADD: 32774, BLEND_FUNC_SUBTRACT: 32778, BLEND_FUNC_REVERSE_SUBTRACT: 32779, BLEND_ZERO: 0, BLEND_ONE: 1, BLEND_SRC_COLOR: 768, BLEND_ONE_MINUS_SRC_COLOR: 769, BLEND_DST_COLOR: 774, BLEND_ONE_MINUS_DST_COLOR: 775, BLEND_SRC_ALPHA: 770, BLEND_ONE_MINUS_SRC_ALPHA: 771, BLEND_DST_ALPHA: 772, BLEND_ONE_MINUS_DST_ALPHA: 773, BLEND_CONSTANT_COLOR: 32769, BLEND_ONE_MINUS_CONSTANT_COLOR: 32770, BLEND_CONSTANT_ALPHA: 32771, BLEND_ONE_MINUS_CONSTANT_ALPHA: 32772, BLEND_SRC_ALPHA_SATURATE: 776, STENCIL_DISABLE: 0, STENCIL_ENABLE: 1, STENCIL_INHERIT: 2, STENCIL_OP_KEEP: 7680, STENCIL_OP_ZERO: 0, STENCIL_OP_REPLACE: 7681, STENCIL_OP_INCR: 7682, STENCIL_OP_INCR_WRAP: 34055, STENCIL_OP_DECR: 7683, STENCIL_OP_DECR_WRAP: 34056, STENCIL_OP_INVERT: 5386, CULL_NONE: 0, CULL_FRONT: 1028, CULL_BACK: 1029, CULL_FRONT_AND_BACK: 1032, PT_POINTS: 0, PT_LINES: 1, PT_LINE_LOOP: 2, PT_LINE_STRIP: 3, PT_TRIANGLES: 4, PT_TRIANGLE_STRIP: 5, PT_TRIANGLE_FAN: 6 }; exports.enums = enums; function attrTypeBytes(attrType) { if (attrType === enums.ATTR_TYPE_INT8) return 1; if (attrType === enums.ATTR_TYPE_UINT8) return 1; if (attrType === enums.ATTR_TYPE_INT16) return 2; if (attrType === enums.ATTR_TYPE_UINT16) return 2; if (attrType === enums.ATTR_TYPE_INT32) return 4; if (attrType === enums.ATTR_TYPE_UINT32) return 4; if (attrType === enums.ATTR_TYPE_FLOAT32) return 4; console.warn("Unknown ATTR_TYPE: " + attrType); return 0; } function glFilter(gl, filter, mipFilter) { void 0 === mipFilter && (mipFilter = -1); var result = _filterGL[filter][mipFilter + 1]; if (void 0 === result) { console.warn("Unknown FILTER: " + filter); return -1 === mipFilter ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR; } return result; } function glTextureFmt(fmt) { var result = _textureFmtGL[fmt]; if (void 0 === result) { console.warn("Unknown TEXTURE_FMT: " + fmt); return _textureFmtGL[enums.TEXTURE_FMT_RGBA8]; } return result; } }), {} ], 257: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var FrameBuffer = (function() { function FrameBuffer(device, width, height, options) { this._device = device; this._width = width; this._height = height; this._colors = options.colors || []; this._depth = options.depth || null; this._stencil = options.stencil || null; this._depthStencil = options.depthStencil || null; this._glID = device._gl.createFramebuffer(); } var _proto = FrameBuffer.prototype; _proto.destroy = function destroy() { if (null === this._glID) { console.error("The frame-buffer already destroyed"); return; } var gl = this._device._gl; gl.deleteFramebuffer(this._glID); this._glID = null; }; _proto.getHandle = function getHandle() { return this._glID; }; return FrameBuffer; })(); exports["default"] = FrameBuffer; module.exports = exports["default"]; }), {} ], 258: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _enums = require("./enums"); var _BYTES_PER_INDEX; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var BYTES_PER_INDEX = (_BYTES_PER_INDEX = {}, _BYTES_PER_INDEX[_enums.enums.INDEX_FMT_UINT8] = 1, _BYTES_PER_INDEX[_enums.enums.INDEX_FMT_UINT16] = 2, _BYTES_PER_INDEX[_enums.enums.INDEX_FMT_UINT32] = 4, _BYTES_PER_INDEX); var IndexBuffer = (function() { function IndexBuffer(device, format, usage, data) { this._device = device; this._format = format; this._usage = usage; this._bytesPerIndex = BYTES_PER_INDEX[format]; this._bytes = data.byteLength; this._numIndices = this._bytes / this._bytesPerIndex; this._needExpandDataStore = true; this._glID = device._gl.createBuffer(); this.update(0, data); device._stats.ib += this._bytes; } var _proto = IndexBuffer.prototype; _proto.destroy = function destroy() { if (-1 === this._glID) { console.error("The buffer already destroyed"); return; } var gl = this._device._gl; gl.deleteBuffer(this._glID); this._device._stats.ib -= this.bytes; this._glID = -1; }; _proto.update = function update(byteOffset, data) { if (-1 === this._glID) { console.error("The buffer is destroyed"); return; } if (0 === data.byteLength) return; if (byteOffset + data.byteLength > this._bytes) { if (byteOffset) { console.error("Failed to update data, bytes exceed."); return; } this._needExpandDataStore = true; this._bytes = byteOffset + data.byteLength; this._numIndices = this._bytes / this._bytesPerIndex; } var gl = this._device._gl; var glUsage = this._usage; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glID); if (this._needExpandDataStore) { gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, glUsage); this._needExpandDataStore = false; } else gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, byteOffset, data); this._device._restoreIndexBuffer(); }; _proto.setUsage = function setUsage(usage) { this._usage = usage; }; _createClass(IndexBuffer, [ { key: "count", get: function get() { return this._numIndices; } } ]); return IndexBuffer; })(); IndexBuffer.BYTES_PER_INDEX = BYTES_PER_INDEX; var _default = IndexBuffer; exports["default"] = _default; module.exports = exports["default"]; }), { "./enums": 256 } ], 259: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _enums = require("./enums"); var gfx = null; false; var VertexFormat = require("./vertex-format"); var IndexBuffer = require("./index-buffer"); var VertexBuffer = require("./vertex-buffer"); var Program = require("./program"); var Texture = require("./texture"); var Texture2D = require("./texture-2d"); var TextureCube = require("./texture-cube"); var RenderBuffer = require("./render-buffer"); var FrameBuffer = require("./frame-buffer"); var Device = require("./device"); gfx = { VertexFormat: VertexFormat, IndexBuffer: IndexBuffer, VertexBuffer: VertexBuffer, Program: Program, Texture: Texture, Texture2D: Texture2D, TextureCube: TextureCube, RenderBuffer: RenderBuffer, FrameBuffer: FrameBuffer, Device: Device, attrTypeBytes: _enums.attrTypeBytes, glFilter: _enums.glFilter, glTextureFmt: _enums.glTextureFmt }; Object.assign(gfx, _enums.enums); var _default = gfx; exports["default"] = _default; cc.gfx = gfx; module.exports = exports["default"]; }), { "./device": 255, "./enums": 256, "./frame-buffer": 257, "./index-buffer": 258, "./program": 261, "./render-buffer": 262, "./texture": 266, "./texture-2d": 264, "./texture-cube": 265, "./vertex-buffer": 267, "./vertex-format": 268 } ], 260: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.isPow2 = isPow2; function isPow2(v) { return !(v & v - 1) && !!v; } }), {} ], 261: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var _genID = 0; function _parseError(out, type, errorLog) { if (!errorLog) return; errorLog.split("\n").forEach((function(msg) { if (msg.length < 5) return; var parts = /^ERROR:\s+(\d+):(\d+):\s*(.*)$/.exec(msg); parts ? out.push({ type: type, fileID: 0 | parts[1], line: 0 | parts[2], message: parts[3].trim() }) : msg.length > 0 && out.push({ type: type, fileID: -1, line: 0, message: msg }); })); } var Program = (function() { function Program(device, options) { this._device = device; this._attributes = []; this._uniforms = []; this._samplers = []; this._errors = []; this._linked = false; this._vertSource = options.vert; this._fragSource = options.frag; this._glID = null; this._id = _genID++; } var _proto = Program.prototype; _proto.link = function link() { if (this._linked) return; var gl = this._device._gl; var vertShader = _createShader(gl, gl.VERTEX_SHADER, this._vertSource); var fragShader = _createShader(gl, gl.FRAGMENT_SHADER, this._fragSource); var program = gl.createProgram(); gl.attachShader(program, vertShader); gl.attachShader(program, fragShader); gl.linkProgram(program); var failed = false; var errors = this._errors; if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { _parseError(errors, "vs", gl.getShaderInfoLog(vertShader)); failed = true; } if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { _parseError(errors, "fs", gl.getShaderInfoLog(fragShader)); failed = true; } gl.deleteShader(vertShader); gl.deleteShader(fragShader); if (failed) return errors; if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { errors.push({ info: "Failed to link shader program: " + gl.getProgramInfoLog(program) }); return errors; } this._glID = program; var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); for (var i = 0; i < numAttributes; ++i) { var info = gl.getActiveAttrib(program, i); var location = gl.getAttribLocation(program, info.name); this._attributes.push({ name: info.name, location: location, type: info.type }); } var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (var _i = 0; _i < numUniforms; ++_i) { var _info = gl.getActiveUniform(program, _i); var name = _info.name; var _location = gl.getUniformLocation(program, name); var isArray = "[0]" === name.substr(name.length - 3); isArray && (name = name.substr(0, name.length - 3)); var uniform = { name: name, location: _location, type: _info.type, size: isArray ? _info.size : void 0 }; this._uniforms.push(uniform); } this._linked = true; }; _proto.destroy = function destroy() { var gl = this._device._gl; gl.deleteProgram(this._glID); this._linked = false; this._glID = null; this._attributes = []; this._uniforms = []; this._samplers = []; }; _createClass(Program, [ { key: "id", get: function get() { return this._id; } } ]); return Program; })(); exports["default"] = Program; function _createShader(gl, type, src) { var shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); return shader; } module.exports = exports["default"]; }), {} ], 262: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var RenderBuffer = (function() { function RenderBuffer(device, format, width, height) { this._device = device; this._format = format; this._glID = device._gl.createRenderbuffer(); this.update(width, height); } var _proto = RenderBuffer.prototype; _proto.update = function update(width, height) { this._width = width; this._height = height; var gl = this._device._gl; gl.bindRenderbuffer(gl.RENDERBUFFER, this._glID); gl.renderbufferStorage(gl.RENDERBUFFER, this._format, width, height); gl.bindRenderbuffer(gl.RENDERBUFFER, null); }; _proto.destroy = function destroy() { if (null === this._glID) { console.error("The render-buffer already destroyed"); return; } var gl = this._device._gl; gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.deleteRenderbuffer(this._glID); this._glID = null; }; return RenderBuffer; })(); exports["default"] = RenderBuffer; module.exports = exports["default"]; }), {} ], 263: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _enums = require("./enums"); var _default = { blend: false, blendSep: false, blendColor: 4294967295, blendEq: _enums.enums.BLEND_FUNC_ADD, blendAlphaEq: _enums.enums.BLEND_FUNC_ADD, blendSrc: _enums.enums.BLEND_ONE, blendDst: _enums.enums.BLEND_ZERO, blendSrcAlpha: _enums.enums.BLEND_ONE, blendDstAlpha: _enums.enums.BLEND_ZERO, depthTest: false, depthWrite: false, depthFunc: _enums.enums.DS_FUNC_LESS, stencilTest: false, stencilSep: false, stencilFuncFront: _enums.enums.DS_FUNC_ALWAYS, stencilRefFront: 0, stencilMaskFront: 255, stencilFailOpFront: _enums.enums.STENCIL_OP_KEEP, stencilZFailOpFront: _enums.enums.STENCIL_OP_KEEP, stencilZPassOpFront: _enums.enums.STENCIL_OP_KEEP, stencilWriteMaskFront: 255, stencilFuncBack: _enums.enums.DS_FUNC_ALWAYS, stencilRefBack: 0, stencilMaskBack: 255, stencilFailOpBack: _enums.enums.STENCIL_OP_KEEP, stencilZFailOpBack: _enums.enums.STENCIL_OP_KEEP, stencilZPassOpBack: _enums.enums.STENCIL_OP_KEEP, stencilWriteMaskBack: 255, cullMode: _enums.enums.CULL_BACK, primitiveType: _enums.enums.PT_TRIANGLES, maxStream: -1, vertexBuffers: [], vertexBufferOffsets: [], indexBuffer: null, maxTextureSlot: -1, textureUnits: [], program: null }; var State = (function() { function State(device) { this.vertexBuffers = new Array(device._caps.maxVertexStreams); this.vertexBufferOffsets = new Array(device._caps.maxVertexStreams); this.textureUnits = new Array(device._caps.maxTextureUnits); this.set(_default); } State.initDefault = function initDefault(device) { _default.vertexBuffers = new Array(device._caps.maxVertexStreams); _default.vertexBufferOffsets = new Array(device._caps.maxVertexStreams); _default.textureUnits = new Array(device._caps.maxTextureUnits); }; var _proto = State.prototype; _proto.reset = function reset() { this.set(_default); }; _proto.set = function set(cpy) { this.blend = cpy.blend; this.blendSep = cpy.blendSep; this.blendColor = cpy.blendColor; this.blendEq = cpy.blendEq; this.blendAlphaEq = cpy.blendAlphaEq; this.blendSrc = cpy.blendSrc; this.blendDst = cpy.blendDst; this.blendSrcAlpha = cpy.blendSrcAlpha; this.blendDstAlpha = cpy.blendDstAlpha; this.depthTest = cpy.depthTest; this.depthWrite = cpy.depthWrite; this.depthFunc = cpy.depthFunc; this.stencilTest = cpy.stencilTest; this.stencilSep = cpy.stencilSep; this.stencilFuncFront = cpy.stencilFuncFront; this.stencilRefFront = cpy.stencilRefFront; this.stencilMaskFront = cpy.stencilMaskFront; this.stencilFailOpFront = cpy.stencilFailOpFront; this.stencilZFailOpFront = cpy.stencilZFailOpFront; this.stencilZPassOpFront = cpy.stencilZPassOpFront; this.stencilWriteMaskFront = cpy.stencilWriteMaskFront; this.stencilFuncBack = cpy.stencilFuncBack; this.stencilRefBack = cpy.stencilRefBack; this.stencilMaskBack = cpy.stencilMaskBack; this.stencilFailOpBack = cpy.stencilFailOpBack; this.stencilZFailOpBack = cpy.stencilZFailOpBack; this.stencilZPassOpBack = cpy.stencilZPassOpBack; this.stencilWriteMaskBack = cpy.stencilWriteMaskBack; this.cullMode = cpy.cullMode; this.primitiveType = cpy.primitiveType; this.maxStream = cpy.maxStream; for (var i = 0; i < cpy.vertexBuffers.length; ++i) this.vertexBuffers[i] = cpy.vertexBuffers[i]; for (var _i = 0; _i < cpy.vertexBufferOffsets.length; ++_i) this.vertexBufferOffsets[_i] = cpy.vertexBufferOffsets[_i]; this.indexBuffer = cpy.indexBuffer; this.maxTextureSlot = cpy.maxTextureSlot; for (var _i2 = 0; _i2 < cpy.textureUnits.length; ++_i2) this.textureUnits[_i2] = cpy.textureUnits[_i2]; this.program = cpy.program; }; return State; })(); exports["default"] = State; module.exports = exports["default"]; }), { "./enums": 256 } ], 264: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _texture = _interopRequireDefault(require("./texture")); var _enums = require("./enums"); var _misc = require("./misc"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Texture2D = (function(_Texture) { _inheritsLoose(Texture2D, _Texture); function Texture2D(device, options) { var _this; _this = _Texture.call(this, device) || this; var gl = _this._device._gl; _this._target = gl.TEXTURE_2D; _this._glID = gl.createTexture(); options.images = options.images || [ null ]; _this.update(options); return _this; } var _proto = Texture2D.prototype; _proto.update = function update(options) { var gl = this._device._gl; var genMipmaps = this._genMipmap; if (options) { void 0 !== options.width && (this._width = options.width); void 0 !== options.height && (this._height = options.height); void 0 !== options.anisotropy && (this._anisotropy = options.anisotropy); void 0 !== options.minFilter && (this._minFilter = options.minFilter); void 0 !== options.magFilter && (this._magFilter = options.magFilter); void 0 !== options.mipFilter && (this._mipFilter = options.mipFilter); void 0 !== options.wrapS && (this._wrapS = options.wrapS); void 0 !== options.wrapT && (this._wrapT = options.wrapT); if (void 0 !== options.format) { this._format = options.format; this._compressed = this._format >= _enums.enums.TEXTURE_FMT_RGB_DXT1 && this._format <= _enums.enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1 || this._format >= _enums.enums.TEXTURE_FMT_RGB_ETC2 && this._format <= _enums.enums.TEXTURE_FMT_RGBA_ETC2; } if (void 0 !== options.genMipmaps) { this._genMipmap = options.genMipmaps; genMipmaps = options.genMipmaps; } var maxSize = this._device.caps.maxTextureSize || Number.MAX_VALUE; var textureMaxSize = Math.max(options.width || 0, options.height || 0); maxSize < textureMaxSize && console.warn("The current texture size " + textureMaxSize + " exceeds the maximum size [" + maxSize + "] supported on the device."); if (void 0 !== options.images && options.images.length > 1) { genMipmaps = false; var maxLength = options.width > options.height ? options.width : options.height; maxLength >> options.images.length - 1 !== 1 && console.error("texture-2d mipmap is invalid, should have a 1x1 mipmap."); } } var pot = (0, _misc.isPow2)(this._width) && (0, _misc.isPow2)(this._height); pot || (genMipmaps = false); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this._glID); if (void 0 !== options.images && options.images.length > 0) { this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); options.images.length > 1 && (this._genMipmap = true); } if (genMipmaps) { gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); gl.generateMipmap(gl.TEXTURE_2D); this._genMipmap = true; } this._setTexInfo(); this._device._restoreTexture(0); }; _proto.updateSubImage = function updateSubImage(options) { var gl = this._device._gl; var glFmt = (0, _enums.glTextureFmt)(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this._glID); this._setSubImage(glFmt, options); this._device._restoreTexture(0); }; _proto.updateImage = function updateImage(options) { var gl = this._device._gl; var glFmt = (0, _enums.glTextureFmt)(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this._glID); this._setImage(glFmt, options); this._device._restoreTexture(0); }; _proto._setSubImage = function _setSubImage(glFmt, options) { var gl = this._device._gl; var flipY = options.flipY; var premultiplyAlpha = options.premultiplyAlpha; var img = options.image; if (!img || ArrayBuffer.isView(img) || img instanceof ArrayBuffer) { void 0 === flipY ? gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false) : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); void 0 === premultiplyAlpha ? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) : gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); this._compressed ? gl.compressedTexSubImage2D(gl.TEXTURE_2D, options.level, options.x, options.y, options.width, options.height, glFmt.format, img) : gl.texSubImage2D(gl.TEXTURE_2D, options.level, options.x, options.y, options.width, options.height, glFmt.format, glFmt.pixelType, img); } else { void 0 === flipY ? gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true) : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); void 0 === premultiplyAlpha ? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) : gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); gl.texSubImage2D(gl.TEXTURE_2D, options.level, options.x, options.y, glFmt.format, glFmt.pixelType, img); } }; _proto._setImage = function _setImage(glFmt, options) { var gl = this._device._gl; var flipY = options.flipY; var premultiplyAlpha = options.premultiplyAlpha; var img = options.image; if (!img || ArrayBuffer.isView(img) || img instanceof ArrayBuffer) { void 0 === flipY ? gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false) : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); void 0 === premultiplyAlpha ? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) : gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); this._compressed ? gl.compressedTexImage2D(gl.TEXTURE_2D, options.level, glFmt.internalFormat, options.width, options.height, 0, img) : gl.texImage2D(gl.TEXTURE_2D, options.level, glFmt.internalFormat, options.width, options.height, 0, glFmt.format, glFmt.pixelType, img); } else { void 0 === flipY ? gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true) : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); void 0 === premultiplyAlpha ? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) : gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); gl.texImage2D(gl.TEXTURE_2D, options.level, glFmt.internalFormat, glFmt.format, glFmt.pixelType, img); } }; _proto._setMipmap = function _setMipmap(images, flipY, premultiplyAlpha) { var glFmt = (0, _enums.glTextureFmt)(this._format); var options = { width: this._width, height: this._height, flipY: flipY, premultiplyAlpha: premultiplyAlpha, level: 0, image: null }; for (var i = 0; i < images.length; ++i) { options.level = i; options.width = this._width >> i; options.height = this._height >> i; options.image = images[i]; this._setImage(glFmt, options); } }; _proto._setTexInfo = function _setTexInfo() { var gl = this._device._gl; var pot = (0, _misc.isPow2)(this._width) && (0, _misc.isPow2)(this._height); if (!pot && (this._wrapS !== _enums.enums.WRAP_CLAMP || this._wrapT !== _enums.enums.WRAP_CLAMP)) { console.warn("WebGL1 doesn't support all wrap modes with NPOT textures"); this._wrapS = _enums.enums.WRAP_CLAMP; this._wrapT = _enums.enums.WRAP_CLAMP; } var mipFilter = this._genMipmap ? this._mipFilter : -1; if (!pot && -1 !== mipFilter) { console.warn("NPOT textures do not support mipmap filter"); mipFilter = -1; } gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (0, _enums.glFilter)(gl, this._minFilter, mipFilter)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (0, _enums.glFilter)(gl, this._magFilter, -1)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT); var ext = this._device.ext("EXT_texture_filter_anisotropic"); ext && gl.texParameteri(gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); }; return Texture2D; })(_texture["default"]); exports["default"] = Texture2D; module.exports = exports["default"]; }), { "./enums": 256, "./misc": 260, "./texture": 266 } ], 265: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _texture = _interopRequireDefault(require("./texture")); var _enums = require("./enums"); var _misc = require("./misc"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var TextureCube = (function(_Texture) { _inheritsLoose(TextureCube, _Texture); function TextureCube(device, options) { var _this; _this = _Texture.call(this, device) || this; var gl = _this._device._gl; _this._target = gl.TEXTURE_CUBE_MAP; _this._glID = gl.createTexture(); _this.update(options); return _this; } var _proto = TextureCube.prototype; _proto.update = function update(options) { var gl = this._device._gl; var genMipmaps = this._genMipmaps; if (options) { void 0 !== options.width && (this._width = options.width); void 0 !== options.height && (this._height = options.height); void 0 !== options.anisotropy && (this._anisotropy = options.anisotropy); void 0 !== options.minFilter && (this._minFilter = options.minFilter); void 0 !== options.magFilter && (this._magFilter = options.magFilter); void 0 !== options.mipFilter && (this._mipFilter = options.mipFilter); void 0 !== options.wrapS && (this._wrapS = options.wrapS); void 0 !== options.wrapT && (this._wrapT = options.wrapT); if (void 0 !== options.format) { this._format = options.format; this._compressed = this._format >= _enums.enums.TEXTURE_FMT_RGB_DXT1 && this._format <= _enums.enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1 || this._format >= _enums.enums.TEXTURE_FMT_RGB_ETC2 && this._format <= _enums.enums.TEXTURE_FMT_RGBA_ETC2; } if (void 0 !== options.genMipmaps) { this._genMipmaps = options.genMipmaps; genMipmaps = options.genMipmaps; } if (void 0 !== options.images && options.images.length > 1) { genMipmaps = false; options.width !== options.height && console.warn("texture-cube width and height should be identical."); options.width >> options.images.length - 1 !== 1 && console.error("texture-cube mipmap is invalid. please set mipmap as 1x1, 2x2, 4x4 ... nxn"); } } var pot = (0, _misc.isPow2)(this._width) && (0, _misc.isPow2)(this._height); pot || (genMipmaps = false); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); if (void 0 !== options.images && options.images.length > 0) { this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); options.images.length > 1 && (this._genMipmaps = true); } if (genMipmaps) { gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); gl.generateMipmap(gl.TEXTURE_CUBE_MAP); this._genMipmaps = true; } this._setTexInfo(); this._device._restoreTexture(0); }; _proto.updateSubImage = function updateSubImage(options) { var gl = this._device._gl; var glFmt = (0, _enums.glTextureFmt)(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); this._setSubImage(glFmt, options); this._device._restoreTexture(0); }; _proto.updateImage = function updateImage(options) { var gl = this._device._gl; var glFmt = (0, _enums.glTextureFmt)(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); this._setImage(glFmt, options); this._device._restoreTexture(0); }; _proto._setSubImage = function _setSubImage(glFmt, options) { var gl = this._device._gl; var flipY = options.flipY; var premultiplyAlpha = options.premultiplyAlpha; var faceIndex = options.faceIndex; var img = options.image; void 0 === flipY ? gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false) : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); void 0 === premultiplyAlpha ? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) : gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); !img || ArrayBuffer.isView(img) || img instanceof ArrayBuffer ? this._compressed ? gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, options.x, options.y, options.width, options.height, glFmt.format, img) : gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, options.x, options.y, options.width, options.height, glFmt.format, glFmt.pixelType, img) : gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, options.x, options.y, glFmt.format, glFmt.pixelType, img); }; _proto._setImage = function _setImage(glFmt, options) { var gl = this._device._gl; var flipY = options.flipY; var premultiplyAlpha = options.premultiplyAlpha; var faceIndex = options.faceIndex; var img = options.image; void 0 === flipY ? gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false) : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); void 0 === premultiplyAlpha ? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) : gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); !img || ArrayBuffer.isView(img) || img instanceof ArrayBuffer ? this._compressed ? gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, glFmt.internalFormat, options.width, options.height, 0, img) : gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, glFmt.internalFormat, options.width, options.height, 0, glFmt.format, glFmt.pixelType, img) : gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, glFmt.internalFormat, glFmt.format, glFmt.pixelType, img); }; _proto._setMipmap = function _setMipmap(images, flipY, premultiplyAlpha) { var glFmt = (0, _enums.glTextureFmt)(this._format); var options = { width: this._width, height: this._height, faceIndex: 0, flipY: flipY, premultiplyAlpha: premultiplyAlpha, level: 0, image: null }; for (var i = 0; i < images.length; ++i) { var levelImages = images[i]; options.level = i; options.width = this._width >> i; options.height = this._height >> i; for (var face = 0; face < 6; ++face) { options.faceIndex = face; options.image = levelImages[face]; this._setImage(glFmt, options); } } }; _proto._setTexInfo = function _setTexInfo() { var gl = this._device._gl; var pot = (0, _misc.isPow2)(this._width) && (0, _misc.isPow2)(this._height); if (!pot && (this._wrapS !== _enums.enums.WRAP_CLAMP || this._wrapT !== _enums.enums.WRAP_CLAMP)) { console.warn("WebGL1 doesn't support all wrap modes with NPOT textures"); this._wrapS = _enums.enums.WRAP_CLAMP; this._wrapT = _enums.enums.WRAP_CLAMP; } var mipFilter = this._genMipmaps ? this._mipFilter : -1; if (!pot && -1 !== mipFilter) { console.warn("NPOT textures do not support mipmap filter"); mipFilter = -1; } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, (0, _enums.glFilter)(gl, this._minFilter, mipFilter)); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, (0, _enums.glFilter)(gl, this._magFilter, -1)); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, this._wrapS); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, this._wrapT); var ext = this._device.ext("EXT_texture_filter_anisotropic"); ext && gl.texParameteri(gl.TEXTURE_CUBE_MAP, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); }; return TextureCube; })(_texture["default"]); exports["default"] = TextureCube; module.exports = exports["default"]; }), { "./enums": 256, "./misc": 260, "./texture": 266 } ], 266: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _enums = require("./enums"); var _nullWebGLTexture = null; var _textureID = 0; var Texture = (function() { function Texture(device) { this._device = device; this._width = 4; this._height = 4; this._genMipmaps = false; this._compressed = false; this._anisotropy = 1; this._minFilter = _enums.enums.FILTER_LINEAR; this._magFilter = _enums.enums.FILTER_LINEAR; this._mipFilter = _enums.enums.FILTER_LINEAR; this._wrapS = _enums.enums.WRAP_REPEAT; this._wrapT = _enums.enums.WRAP_REPEAT; this._format = _enums.enums.TEXTURE_FMT_RGBA8; this._target = -1; this._id = _textureID++; } var _proto = Texture.prototype; _proto.destroy = function destroy() { if (this._glID === _nullWebGLTexture) { console.error("The texture already destroyed"); return; } var gl = this._device._gl; gl.deleteTexture(this._glID); this._device._stats.tex -= this.bytes; this._glID = _nullWebGLTexture; }; return Texture; })(); exports["default"] = Texture; module.exports = exports["default"]; }), { "./enums": 256 } ], 267: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _enums = require("./enums"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var VertexBuffer = (function() { function VertexBuffer(device, format, usage, data) { this._device = device; this._format = format; this._usage = usage; this._bytesPerVertex = this._format._bytes; this._bytes = data.byteLength; this._numVertices = this._bytes / this._bytesPerVertex; this._needExpandDataStore = true; this._glID = device._gl.createBuffer(); this.update(0, data); device._stats.vb += this._bytes; } var _proto = VertexBuffer.prototype; _proto.destroy = function destroy() { if (-1 === this._glID) { console.error("The buffer already destroyed"); return; } var gl = this._device._gl; gl.deleteBuffer(this._glID); this._device._stats.vb -= this.bytes; this._glID = -1; }; _proto.update = function update(byteOffset, data) { if (-1 === this._glID) { console.error("The buffer is destroyed"); return; } if (0 === data.byteLength) return; if (byteOffset + data.byteLength > this._bytes) { if (byteOffset) { console.error("Failed to update data, bytes exceed."); return; } this._needExpandDataStore = true; this._bytes = byteOffset + data.byteLength; this._numVertices = this._bytes / this._bytesPerVertex; } var gl = this._device._gl; var glUsage = this._usage; gl.bindBuffer(gl.ARRAY_BUFFER, this._glID); if (this._needExpandDataStore) { gl.bufferData(gl.ARRAY_BUFFER, data, glUsage); this._needExpandDataStore = false; } else gl.bufferSubData(gl.ARRAY_BUFFER, byteOffset, data); gl.bindBuffer(gl.ARRAY_BUFFER, null); }; _proto.getFormat = function getFormat(name) { return this._format.element(name); }; _proto.setUsage = function setUsage(usage) { this._usage = usage; }; _createClass(VertexBuffer, [ { key: "count", get: function get() { return this._numVertices; } } ]); return VertexBuffer; })(); var _default = VertexBuffer; exports["default"] = _default; module.exports = exports["default"]; }), { "./enums": 256 } ], 268: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _enums = require("./enums"); var _murmurhash2_gc = _interopRequireDefault(require("../murmurhash2_gc")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var VertexFormat = (function() { function VertexFormat(infos) { this._attr2el = {}; this._elements = []; this._bytes = 0; var hash = ""; for (var i = 0, len = infos.length; i < len; ++i) { var info = infos[i]; var el = { name: info.name, offset: this._bytes, stride: 0, stream: -1, type: info.type, num: info.num, normalize: void 0 !== info.normalize && info.normalize, bytes: info.num * (0, _enums.attrTypeBytes)(info.type) }; this._attr2el[el.name] = el; this._elements.push(el); this._bytes += el.bytes; hash += el.name + ":" + el.num + ":" + el.type + ":" + el.normalize; } for (var _i = 0, _len = this._elements.length; _i < _len; ++_i) { var _el = this._elements[_i]; _el.stride = this._bytes; } this._hash = (0, _murmurhash2_gc["default"])(hash, 666); } var _proto = VertexFormat.prototype; _proto.element = function element(attrName) { return this._attr2el[attrName]; }; _proto.getHash = function getHash() { return this._hash; }; return VertexFormat; })(); exports["default"] = VertexFormat; module.exports = exports["default"]; }), { "../murmurhash2_gc": 277, "./enums": 256 } ], 269: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var CircularPool = (function() { function CircularPool(fn, size) { this._cursor = 0; this._data = new Array(size); for (var i = 0; i < size; ++i) this._data[i] = fn(); } var _proto = CircularPool.prototype; _proto.request = function request() { var item = this._data[this._cursor]; this._cursor = (this._cursor + 1) % this._data.length; return item; }; return CircularPool; })(); exports["default"] = CircularPool; module.exports = exports["default"]; }), {} ], 270: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _timsort = _interopRequireDefault(require("./timsort")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var FixedArray = (function() { function FixedArray(size) { this._count = 0; this._data = new Array(size); } var _proto = FixedArray.prototype; _proto._resize = function _resize(size) { if (size > this._data.length) for (var i = this._data.length; i < size; ++i) this._data[i] = void 0; }; _proto.reset = function reset() { for (var i = 0; i < this._count; ++i) this._data[i] = void 0; this._count = 0; }; _proto.push = function push(val) { this._count >= this._data.length && this._resize(2 * this._data.length); this._data[this._count] = val; ++this._count; }; _proto.pop = function pop() { --this._count; this._count < 0 && (this._count = 0); var ret = this._data[this._count]; this._data[this._count] = void 0; return ret; }; _proto.fastRemove = function fastRemove(idx) { if (idx >= this._count || idx < 0) return; var last = this._count - 1; this._data[idx] = this._data[last]; this._data[last] = void 0; this._count -= 1; }; _proto.indexOf = function indexOf(val) { return this._data.indexOf(val); }; _proto.sort = function sort(cmp) { return (0, _timsort["default"])(this._data, 0, this._count, cmp); }; _createClass(FixedArray, [ { key: "length", get: function get() { return this._count; } }, { key: "data", get: function get() { return this._data; } } ]); return FixedArray; })(); exports["default"] = FixedArray; module.exports = exports["default"]; }), { "./timsort": 275 } ], 271: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.TypedArrayPool = exports.RecyclePool = exports.Pool = exports.LinkedArray = exports.FixedArray = exports.CircularPool = void 0; var _circularPool = _interopRequireDefault(require("./circular-pool")); exports.CircularPool = _circularPool["default"]; var _fixedArray = _interopRequireDefault(require("./fixed-array")); exports.FixedArray = _fixedArray["default"]; var _linkedArray = _interopRequireDefault(require("./linked-array")); exports.LinkedArray = _linkedArray["default"]; var _pool = _interopRequireDefault(require("./pool")); exports.Pool = _pool["default"]; var _recyclePool = _interopRequireDefault(require("./recycle-pool")); exports.RecyclePool = _recyclePool["default"]; var _typedArrayPool = _interopRequireDefault(require("./typed-array-pool")); exports.TypedArrayPool = _typedArrayPool["default"]; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } }), { "./circular-pool": 269, "./fixed-array": 270, "./linked-array": 272, "./pool": 273, "./recycle-pool": 274, "./typed-array-pool": 276 } ], 272: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _pool = _interopRequireDefault(require("./pool")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var LinkedArray = (function() { function LinkedArray(fn, size) { this._fn = fn; this._count = 0; this._head = null; this._tail = null; this._pool = new _pool["default"](fn, size); } var _proto = LinkedArray.prototype; _proto.add = function add() { var node = this._pool.alloc(); if (this._tail) { this._tail._next = node; node._prev = this._tail; } else this._head = node; this._tail = node; this._count += 1; return node; }; _proto.remove = function remove(node) { node._prev ? node._prev._next = node._next : this._head = node._next; node._next ? node._next._prev = node._prev : this._tail = node._prev; node._next = null; node._prev = null; this._pool.free(node); this._count -= 1; }; _proto.forEach = function forEach(fn, binder) { var cursor = this._head; if (!cursor) return; binder && (fn = fn.bind(binder)); var idx = 0; var next = cursor; while (cursor) { next = cursor._next; fn(cursor, idx, this); cursor = next; ++idx; } }; _createClass(LinkedArray, [ { key: "head", get: function get() { return this._head; } }, { key: "tail", get: function get() { return this._tail; } }, { key: "length", get: function get() { return this._count; } } ]); return LinkedArray; })(); exports["default"] = LinkedArray; module.exports = exports["default"]; }), { "./pool": 273 } ], 273: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var Pool = (function() { function Pool(fn, size) { this._fn = fn; this._idx = size - 1; this._frees = new Array(size); for (var i = 0; i < size; ++i) this._frees[i] = fn(); } var _proto = Pool.prototype; _proto._expand = function _expand(size) { var old = this._frees; this._frees = new Array(size); var len = size - old.length; for (var i = 0; i < len; ++i) this._frees[i] = this._fn(); for (var _i = len, j = 0; _i < size; ++_i, ++j) this._frees[_i] = old[j]; this._idx += len; }; _proto.alloc = function alloc() { this._idx < 0 && this._expand(Math.round(1.2 * this._frees.length) + 1); var ret = this._frees[this._idx]; this._frees[this._idx] = null; --this._idx; return ret; }; _proto.free = function free(obj) { ++this._idx; this._frees[this._idx] = obj; }; _proto.clear = function clear(fn) { for (var i = 0; i <= this._idx; i++) fn && fn(this._frees[i]); this._frees.length = 0; this._idx = -1; }; return Pool; })(); exports["default"] = Pool; module.exports = exports["default"]; }), {} ], 274: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _timsort = _interopRequireDefault(require("./timsort")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var RecyclePool = (function() { function RecyclePool(fn, size) { this._fn = fn; this._count = 0; this._data = new Array(size); for (var i = 0; i < size; ++i) this._data[i] = fn(); } var _proto = RecyclePool.prototype; _proto.reset = function reset() { this._count = 0; }; _proto.resize = function resize(size) { if (size > this._data.length) for (var i = this._data.length; i < size; ++i) this._data[i] = this._fn(); }; _proto.add = function add() { this._count >= this._data.length && this.resize(2 * this._data.length); return this._data[this._count++]; }; _proto.remove = function remove(idx) { if (idx >= this._count) return; var last = this._count - 1; var tmp = this._data[idx]; this._data[idx] = this._data[last]; this._data[last] = tmp; this._count -= 1; }; _proto.sort = function sort(cmp) { return (0, _timsort["default"])(this._data, 0, this._count, cmp); }; _createClass(RecyclePool, [ { key: "length", get: function get() { return this._count; } }, { key: "data", get: function get() { return this._data; } } ]); return RecyclePool; })(); exports["default"] = RecyclePool; cc.RecyclePool = RecyclePool; module.exports = exports["default"]; }), { "./timsort": 275 } ], 275: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = _default; var DEFAULT_MIN_MERGE = 32; var DEFAULT_MIN_GALLOPING = 7; var DEFAULT_TMP_STORAGE_LENGTH = 256; var POWERS_OF_TEN = [ 1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9 ]; function log10(x) { if (x < 1e5) { if (x < 100) return x < 10 ? 0 : 1; if (x < 1e4) return x < 1e3 ? 2 : 3; return 4; } if (x < 1e7) return x < 1e6 ? 5 : 6; if (x < 1e9) return x < 1e8 ? 7 : 8; return 9; } function alphabeticalCompare(a, b) { if (a === b) return 0; if (~~a === a && ~~b === b) { if (0 === a || 0 === b) return a < b ? -1 : 1; if (a < 0 || b < 0) { if (b >= 0) return -1; if (a >= 0) return 1; a = -a; b = -b; } var al = log10(a); var bl = log10(b); var t = 0; if (al < bl) { a *= POWERS_OF_TEN[bl - al - 1]; b /= 10; t = -1; } else if (al > bl) { b *= POWERS_OF_TEN[al - bl - 1]; a /= 10; t = 1; } if (a === b) return t; return a < b ? -1 : 1; } var aStr = String(a); var bStr = String(b); if (aStr === bStr) return 0; return aStr < bStr ? -1 : 1; } function minRunLength(n) { var r = 0; while (n >= DEFAULT_MIN_MERGE) { r |= 1 & n; n >>= 1; } return n + r; } function makeAscendingRun(array, lo, hi, compare) { var runHi = lo + 1; if (runHi === hi) return 1; if (compare(array[runHi++], array[lo]) < 0) { while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) runHi++; reverseRun(array, lo, runHi); } else while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) runHi++; return runHi - lo; } function reverseRun(array, lo, hi) { hi--; while (lo < hi) { var t = array[lo]; array[lo++] = array[hi]; array[hi--] = t; } } function binaryInsertionSort(array, lo, hi, start, compare) { start === lo && start++; for (;start < hi; start++) { var pivot = array[start]; var left = lo; var right = start; while (left < right) { var mid = left + right >>> 1; compare(pivot, array[mid]) < 0 ? right = mid : left = mid + 1; } var n = start - left; switch (n) { case 3: array[left + 3] = array[left + 2]; case 2: array[left + 2] = array[left + 1]; case 1: array[left + 1] = array[left]; break; default: while (n > 0) { array[left + n] = array[left + n - 1]; n--; } } array[left] = pivot; } } function gallopLeft(value, array, start, length, hint, compare) { var lastOffset = 0; var maxOffset = 0; var offset = 1; if (compare(value, array[start + hint]) > 0) { maxOffset = length - hint; while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { lastOffset = offset; offset = 1 + (offset << 1); offset <= 0 && (offset = maxOffset); } offset > maxOffset && (offset = maxOffset); lastOffset += hint; offset += hint; } else { maxOffset = hint + 1; while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { lastOffset = offset; offset = 1 + (offset << 1); offset <= 0 && (offset = maxOffset); } offset > maxOffset && (offset = maxOffset); var tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; } lastOffset++; while (lastOffset < offset) { var m = lastOffset + (offset - lastOffset >>> 1); compare(value, array[start + m]) > 0 ? lastOffset = m + 1 : offset = m; } return offset; } function gallopRight(value, array, start, length, hint, compare) { var lastOffset = 0; var maxOffset = 0; var offset = 1; if (compare(value, array[start + hint]) < 0) { maxOffset = hint + 1; while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { lastOffset = offset; offset = 1 + (offset << 1); offset <= 0 && (offset = maxOffset); } offset > maxOffset && (offset = maxOffset); var tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; } else { maxOffset = length - hint; while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { lastOffset = offset; offset = 1 + (offset << 1); offset <= 0 && (offset = maxOffset); } offset > maxOffset && (offset = maxOffset); lastOffset += hint; offset += hint; } lastOffset++; while (lastOffset < offset) { var m = lastOffset + (offset - lastOffset >>> 1); compare(value, array[start + m]) < 0 ? offset = m : lastOffset = m + 1; } return offset; } var TimSort = (function() { function TimSort(array, compare) { this.array = array; this.compare = compare; this.minGallop = DEFAULT_MIN_GALLOPING; this.length = array.length; this.tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH && (this.tmpStorageLength = this.length >>> 1); this.tmp = new Array(this.tmpStorageLength); this.stackLength = this.length < 120 ? 5 : this.length < 1542 ? 10 : this.length < 119151 ? 19 : 40; this.runStart = new Array(this.stackLength); this.runLength = new Array(this.stackLength); this.stackSize = 0; } var _proto = TimSort.prototype; _proto.pushRun = function pushRun(runStart, runLength) { this.runStart[this.stackSize] = runStart; this.runLength[this.stackSize] = runLength; this.stackSize += 1; }; _proto.mergeRuns = function mergeRuns() { while (this.stackSize > 1) { var n = this.stackSize - 2; if (n >= 1 && this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1] || n >= 2 && this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1]) this.runLength[n - 1] < this.runLength[n + 1] && n--; else if (this.runLength[n] > this.runLength[n + 1]) break; this.mergeAt(n); } }; _proto.forceMergeRuns = function forceMergeRuns() { while (this.stackSize > 1) { var n = this.stackSize - 2; n > 0 && this.runLength[n - 1] < this.runLength[n + 1] && n--; this.mergeAt(n); } }; _proto.mergeAt = function mergeAt(i) { var compare = this.compare; var array = this.array; var start1 = this.runStart[i]; var length1 = this.runLength[i]; var start2 = this.runStart[i + 1]; var length2 = this.runLength[i + 1]; this.runLength[i] = length1 + length2; if (i === this.stackSize - 3) { this.runStart[i + 1] = this.runStart[i + 2]; this.runLength[i + 1] = this.runLength[i + 2]; } this.stackSize--; var k = gallopRight(array[start2], array, start1, length1, 0, compare); start1 += k; length1 -= k; if (0 === length1) return; length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); if (0 === length2) return; length1 <= length2 ? this.mergeLow(start1, length1, start2, length2) : this.mergeHigh(start1, length1, start2, length2); }; _proto.mergeLow = function mergeLow(start1, length1, start2, length2) { var compare = this.compare; var array = this.array; var tmp = this.tmp; var i = 0; for (i = 0; i < length1; i++) tmp[i] = array[start1 + i]; var cursor1 = 0; var cursor2 = start2; var dest = start1; array[dest++] = array[cursor2++]; if (0 === --length2) { for (i = 0; i < length1; i++) array[dest + i] = tmp[cursor1 + i]; return; } if (1 === length1) { for (i = 0; i < length2; i++) array[dest + i] = array[cursor2 + i]; array[dest + length2] = tmp[cursor1]; return; } var minGallop = this.minGallop; while (true) { var count1 = 0; var count2 = 0; var exit = false; do { if (compare(array[cursor2], tmp[cursor1]) < 0) { array[dest++] = array[cursor2++]; count2++; count1 = 0; if (0 === --length2) { exit = true; break; } } else { array[dest++] = tmp[cursor1++]; count1++; count2 = 0; if (1 === --length1) { exit = true; break; } } } while ((count1 | count2) < minGallop); if (exit) break; do { count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); if (0 !== count1) { for (i = 0; i < count1; i++) array[dest + i] = tmp[cursor1 + i]; dest += count1; cursor1 += count1; length1 -= count1; if (length1 <= 1) { exit = true; break; } } array[dest++] = array[cursor2++]; if (0 === --length2) { exit = true; break; } count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); if (0 !== count2) { for (i = 0; i < count2; i++) array[dest + i] = array[cursor2 + i]; dest += count2; cursor2 += count2; length2 -= count2; if (0 === length2) { exit = true; break; } } array[dest++] = tmp[cursor1++]; if (1 === --length1) { exit = true; break; } minGallop--; } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); if (exit) break; minGallop < 0 && (minGallop = 0); minGallop += 2; } this.minGallop = minGallop; minGallop < 1 && (this.minGallop = 1); if (1 === length1) { for (i = 0; i < length2; i++) array[dest + i] = array[cursor2 + i]; array[dest + length2] = tmp[cursor1]; } else { if (0 === length1) throw new Error("mergeLow preconditions were not respected"); for (i = 0; i < length1; i++) array[dest + i] = tmp[cursor1 + i]; } }; _proto.mergeHigh = function mergeHigh(start1, length1, start2, length2) { var compare = this.compare; var array = this.array; var tmp = this.tmp; var i = 0; for (i = 0; i < length2; i++) tmp[i] = array[start2 + i]; var cursor1 = start1 + length1 - 1; var cursor2 = length2 - 1; var dest = start2 + length2 - 1; var customCursor = 0; var customDest = 0; array[dest--] = array[cursor1--]; if (0 === --length1) { customCursor = dest - (length2 - 1); for (i = 0; i < length2; i++) array[customCursor + i] = tmp[i]; return; } if (1 === length2) { dest -= length1; cursor1 -= length1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = length1 - 1; i >= 0; i--) array[customDest + i] = array[customCursor + i]; array[dest] = tmp[cursor2]; return; } var minGallop = this.minGallop; while (true) { var count1 = 0; var count2 = 0; var exit = false; do { if (compare(tmp[cursor2], array[cursor1]) < 0) { array[dest--] = array[cursor1--]; count1++; count2 = 0; if (0 === --length1) { exit = true; break; } } else { array[dest--] = tmp[cursor2--]; count2++; count1 = 0; if (1 === --length2) { exit = true; break; } } } while ((count1 | count2) < minGallop); if (exit) break; do { count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); if (0 !== count1) { dest -= count1; cursor1 -= count1; length1 -= count1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = count1 - 1; i >= 0; i--) array[customDest + i] = array[customCursor + i]; if (0 === length1) { exit = true; break; } } array[dest--] = tmp[cursor2--]; if (1 === --length2) { exit = true; break; } count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); if (0 !== count2) { dest -= count2; cursor2 -= count2; length2 -= count2; customDest = dest + 1; customCursor = cursor2 + 1; for (i = 0; i < count2; i++) array[customDest + i] = tmp[customCursor + i]; if (length2 <= 1) { exit = true; break; } } array[dest--] = array[cursor1--]; if (0 === --length1) { exit = true; break; } minGallop--; } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); if (exit) break; minGallop < 0 && (minGallop = 0); minGallop += 2; } this.minGallop = minGallop; minGallop < 1 && (this.minGallop = 1); if (1 === length2) { dest -= length1; cursor1 -= length1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = length1 - 1; i >= 0; i--) array[customDest + i] = array[customCursor + i]; array[dest] = tmp[cursor2]; } else { if (0 === length2) throw new Error("mergeHigh preconditions were not respected"); customCursor = dest - (length2 - 1); for (i = 0; i < length2; i++) array[customCursor + i] = tmp[i]; } }; return TimSort; })(); function _default(array, lo, hi, compare) { if (!Array.isArray(array)) throw new TypeError("Can only sort arrays"); void 0 === lo && (lo = 0); void 0 === hi && (hi = array.length); void 0 === compare && (compare = alphabeticalCompare); var remaining = hi - lo; if (remaining < 2) return; var runLength = 0; if (remaining < DEFAULT_MIN_MERGE) { runLength = makeAscendingRun(array, lo, hi, compare); binaryInsertionSort(array, lo, hi, lo + runLength, compare); return; } var ts = new TimSort(array, compare); var minRun = minRunLength(remaining); do { runLength = makeAscendingRun(array, lo, hi, compare); if (runLength < minRun) { var force = remaining; force > minRun && (force = minRun); binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); runLength = force; } ts.pushRun(lo, runLength); ts.mergeRuns(); remaining -= runLength; lo += runLength; } while (0 !== remaining); ts.forceMergeRuns(); } module.exports = exports["default"]; }), {} ], 276: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _bufferPools = Array(8); for (var i = 0; i < 8; ++i) _bufferPools[i] = []; function _nextPow16(v) { for (var _i = 16; _i <= 1 << 28; _i *= 16) if (v <= _i) return _i; return 0; } function _log2(v) { var r, shift; r = (v > 65535) << 4; v >>>= r; shift = (v > 255) << 3; v >>>= shift; r |= shift; shift = (v > 15) << 2; v >>>= shift; r |= shift; shift = (v > 3) << 1; v >>>= shift; r |= shift; return r | v >> 1; } function _alloc(n) { var sz = _nextPow16(n); var bin = _bufferPools[_log2(sz) >> 2]; if (bin.length > 0) return bin.pop(); return new ArrayBuffer(sz); } function _free(buf) { _bufferPools[_log2(buf.byteLength) >> 2].push(buf); } var _default = { alloc_int8: function alloc_int8(n) { var result = new Int8Array(_alloc(n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_uint8: function alloc_uint8(n) { var result = new Uint8Array(_alloc(n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_int16: function alloc_int16(n) { var result = new Int16Array(_alloc(2 * n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_uint16: function alloc_uint16(n) { var result = new Uint16Array(_alloc(2 * n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_int32: function alloc_int32(n) { var result = new Int32Array(_alloc(4 * n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_uint32: function alloc_uint32(n) { var result = new Uint32Array(_alloc(4 * n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_float32: function alloc_float32(n) { var result = new Float32Array(_alloc(4 * n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_float64: function alloc_float64(n) { var result = new Float64Array(_alloc(8 * n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, alloc_dataview: function alloc_dataview(n) { var result = new DataView(_alloc(n), 0, n); if (result.length !== n) return result.subarray(0, n); return result; }, free: function free(array) { _free(array.buffer); }, reset: function reset() { var _bufferPools = Array(8); for (var _i2 = 0; _i2 < 8; ++_i2) _bufferPools[_i2] = []; } }; exports["default"] = _default; module.exports = exports["default"]; }), {} ], 277: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = murmurhash2_32_gc; function murmurhash2_32_gc(str, seed) { var l = str.length, h = seed ^ l, i = 0, k; while (l >= 4) { k = 255 & str.charCodeAt(i) | (255 & str.charCodeAt(++i)) << 8 | (255 & str.charCodeAt(++i)) << 16 | (255 & str.charCodeAt(++i)) << 24; k = 1540483477 * (65535 & k) + ((1540483477 * (k >>> 16) & 65535) << 16); k ^= k >>> 24; k = 1540483477 * (65535 & k) + ((1540483477 * (k >>> 16) & 65535) << 16); h = 1540483477 * (65535 & h) + ((1540483477 * (h >>> 16) & 65535) << 16) ^ k; l -= 4; ++i; } switch (l) { case 3: h ^= (255 & str.charCodeAt(i + 2)) << 16; case 2: h ^= (255 & str.charCodeAt(i + 1)) << 8; case 1: h ^= 255 & str.charCodeAt(i); h = 1540483477 * (65535 & h) + ((1540483477 * (h >>> 16) & 65535) << 16); } h ^= h >>> 13; h = 1540483477 * (65535 & h) + ((1540483477 * (h >>> 16) & 65535) << 16); h ^= h >>> 15; return h >>> 0; } module.exports = exports["default"]; }), {} ], 278: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueTypes = require("../../core/value-types"); var _baseRenderer = _interopRequireDefault(require("../core/base-renderer")); var _enums = _interopRequireDefault(require("../enums")); var _memop = require("../memop"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _assertThisInitialized(self) { if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _a16_view = new Float32Array(16); var _a16_view_inv = new Float32Array(16); var _a16_proj = new Float32Array(16); var _a16_viewProj = new Float32Array(16); var _a4_camPos = new Float32Array(4); var _a64_shadow_lightViewProj = new Float32Array(64); var _a16_shadow_lightViewProjs = []; var _a4_shadow_info = new Float32Array(4); var _camPos = new _valueTypes.Vec4(0, 0, 0, 0); var _camFwd = new _valueTypes.Vec3(0, 0, 0); var _v3_tmp1 = new _valueTypes.Vec3(0, 0, 0); var CC_MAX_LIGHTS = 4; var CC_MAX_SHADOW_LIGHTS = 2; var _float16_pool = new _memop.RecyclePool(function() { return new Float32Array(16); }, 8); function sortView(a, b) { return a._priority - b._priority; } var ForwardRenderer = (function(_BaseRenderer) { _inheritsLoose(ForwardRenderer, _BaseRenderer); function ForwardRenderer(device, builtin) { var _this; _this = _BaseRenderer.call(this, device, builtin) || this; _this._time = new Float32Array(4); _this._lights = []; _this._shadowLights = []; _this._numLights = 0; _this._defines = {}; _this._registerStage("shadowcast", _this._shadowStage.bind(_assertThisInitialized(_this))); _this._registerStage("opaque", _this._opaqueStage.bind(_assertThisInitialized(_this))); _this._registerStage("transparent", _this._transparentStage.bind(_assertThisInitialized(_this))); return _this; } var _proto = ForwardRenderer.prototype; _proto.reset = function reset() { _float16_pool.reset(); _BaseRenderer.prototype.reset.call(this); }; _proto.render = function render(scene, dt) { this.reset(); true; if (dt) { this._time[0] += dt; this._time[1] = dt; this._time[2]++; } this._device.setUniform("cc_time", this._time); this._updateLights(scene); var canvas = this._device._gl.canvas; for (var i = 0; i < scene._cameras.length; ++i) { var view = this._requestView(); var width = canvas.width; var height = canvas.height; var camera = scene._cameras.data[i]; camera.extractView(view, width, height); } this._viewPools.sort(sortView); for (var _i = 0; _i < this._viewPools.length; ++_i) { var _view = this._viewPools.data[_i]; this._render(_view, scene); } }; _proto.renderCamera = function renderCamera(camera, scene) { this.reset(); this._updateLights(scene); var canvas = this._device._gl.canvas; var width = canvas.width; var height = canvas.height; var view = this._requestView(); camera.extractView(view, width, height); this._viewPools.sort(sortView); for (var i = 0; i < this._viewPools.length; ++i) { var _view2 = this._viewPools.data[i]; this._render(_view2, scene); } }; _proto._updateLights = function _updateLights(scene) { this._lights.length = 0; this._shadowLights.length = 0; var lights = scene._lights; for (var i = 0; i < lights.length; ++i) { var light = lights.data[i]; light.update(this._device); if (light.shadowType !== _enums["default"].SHADOW_NONE) { this._shadowLights.length < CC_MAX_SHADOW_LIGHTS && this._shadowLights.unshift(light); var view = this._requestView(); light.extractView(view, [ "shadowcast" ]); this._lights.splice(0, 0, light); } else this._lights.push(light); } this._updateLightDefines(); this._numLights = lights._count; }; _proto._updateLightDefines = function _updateLightDefines() { var defines = this._defines; for (var i = 0; i < this._lights.length; ++i) { var light = this._lights[i]; var lightKey = "CC_LIGHT_" + i + "_TYPE"; var shadowKey = "CC_SHADOW_" + i + "_TYPE"; if (defines[lightKey] !== light._type) { defines[lightKey] = light._type; this._definesChanged = true; } if (defines[shadowKey] !== light._shadowType) { defines[shadowKey] = light._shadowType; this._definesChanged = true; } } var newCount = Math.min(CC_MAX_LIGHTS, this._lights.length); if (defines.CC_NUM_LIGHTS !== newCount) { defines.CC_NUM_LIGHTS = newCount; this._definesChanged = true; } newCount = Math.min(CC_MAX_LIGHTS, this._shadowLights.length); if (defines.CC_NUM_SHADOW_LIGHTS !== newCount) { defines.CC_NUM_SHADOW_LIGHTS = newCount; this._definesChanged = true; } }; _proto._submitLightsUniforms = function _submitLightsUniforms() { var device = this._device; if (this._lights.length > 0) { var positionAndRanges = _float16_pool.add(); var directions = _float16_pool.add(); var colors = _float16_pool.add(); var lightNum = Math.min(CC_MAX_LIGHTS, this._lights.length); for (var i = 0; i < lightNum; ++i) { var light = this._lights[i]; var index = 4 * i; colors.set(light._colorUniform, index); directions.set(light._directionUniform, index); positionAndRanges.set(light._positionUniform, index); positionAndRanges[index + 3] = light._range; if (light._type === _enums["default"].LIGHT_SPOT) { directions[index + 3] = light._spotUniform[0]; colors[index + 3] = light._spotUniform[1]; } else { directions[index + 3] = 0; colors[index + 3] = 0; } } device.setUniform("cc_lightDirection", directions); device.setUniform("cc_lightColor", colors); device.setUniform("cc_lightPositionAndRange", positionAndRanges); } }; _proto._submitShadowStageUniforms = function _submitShadowStageUniforms(view) { var light = view._shadowLight; var shadowInfo = _a4_shadow_info; shadowInfo[0] = light.shadowMinDepth; shadowInfo[1] = light.shadowMaxDepth; shadowInfo[2] = light.shadowDepthScale; shadowInfo[3] = light.shadowDarkness; this._device.setUniform("cc_shadow_map_lightViewProjMatrix", _valueTypes.Mat4.toArray(_a16_viewProj, view._matViewProj)); this._device.setUniform("cc_shadow_map_info", shadowInfo); this._device.setUniform("cc_shadow_map_bias", light.shadowBias); this._defines.CC_SHADOW_TYPE = light._shadowType; }; _proto._submitOtherStagesUniforms = function _submitOtherStagesUniforms() { var shadowInfo = _float16_pool.add(); for (var i = 0; i < this._shadowLights.length; ++i) { var light = this._shadowLights[i]; var view = _a16_shadow_lightViewProjs[i]; view || (view = _a16_shadow_lightViewProjs[i] = new Float32Array(_a64_shadow_lightViewProj.buffer, 64 * i, 16)); _valueTypes.Mat4.toArray(view, light.viewProjMatrix); var index = 4 * i; shadowInfo[index] = light.shadowMinDepth; shadowInfo[index + 1] = light.shadowMaxDepth; shadowInfo[index + 2] = light._shadowResolution; shadowInfo[index + 3] = light.shadowDarkness; } this._device.setUniform("cc_shadow_lightViewProjMatrix", _a64_shadow_lightViewProj); this._device.setUniform("cc_shadow_info", shadowInfo); }; _proto._sortItems = function _sortItems(items) { items.sort((function(a, b) { if (a.passes.length !== b.passes.length) return a.passes.length - b.passes.length; return a.sortKey - b.sortKey; })); }; _proto._shadowStage = function _shadowStage(view, items) { this._submitShadowStageUniforms(view); for (var i = 0; i < items.length; ++i) { var item = items.data[i]; item.effect.getDefine("CC_CASTING_SHADOW") && this._draw(item); } }; _proto._drawItems = function _drawItems(view, items) { var shadowLights = this._shadowLights; if (0 === shadowLights.length && 0 === this._numLights) for (var i = 0; i < items.length; ++i) { var item = items.data[i]; this._draw(item); } else for (var _i2 = 0; _i2 < items.length; ++_i2) { var _item = items.data[_i2]; for (var shadowIdx = 0; shadowIdx < shadowLights.length; ++shadowIdx) this._device.setTexture("cc_shadow_map_" + shadowIdx, shadowLights[shadowIdx].shadowMap, this._allocTextureUnit()); this._draw(_item); } }; _proto._opaqueStage = function _opaqueStage(view, items) { view.getPosition(_camPos); this._device.setUniform("cc_matView", _valueTypes.Mat4.toArray(_a16_view, view._matView)); this._device.setUniform("cc_matViewInv", _valueTypes.Mat4.toArray(_a16_view_inv, view._matViewInv)); this._device.setUniform("cc_matProj", _valueTypes.Mat4.toArray(_a16_proj, view._matProj)); this._device.setUniform("cc_matViewProj", _valueTypes.Mat4.toArray(_a16_viewProj, view._matViewProj)); this._device.setUniform("cc_cameraPos", _valueTypes.Vec4.toArray(_a4_camPos, _camPos)); this._submitLightsUniforms(); this._submitOtherStagesUniforms(); this._drawItems(view, items); }; _proto._transparentStage = function _transparentStage(view, items) { view.getPosition(_camPos); view.getForward(_camFwd); this._device.setUniform("cc_matView", _valueTypes.Mat4.toArray(_a16_view, view._matView)); this._device.setUniform("cc_matViewInv", _valueTypes.Mat4.toArray(_a16_view_inv, view._matViewInv)); this._device.setUniform("cc_matProj", _valueTypes.Mat4.toArray(_a16_proj, view._matProj)); this._device.setUniform("cc_matViewProj", _valueTypes.Mat4.toArray(_a16_viewProj, view._matViewProj)); this._device.setUniform("cc_cameraPos", _valueTypes.Vec4.toArray(_a4_camPos, _camPos)); this._submitLightsUniforms(); this._submitOtherStagesUniforms(); for (var i = 0; i < items.length; ++i) { var item = items.data[i]; item.node.getWorldPosition(_v3_tmp1); _valueTypes.Vec3.sub(_v3_tmp1, _v3_tmp1, _camPos); item.sortKey = -_valueTypes.Vec3.dot(_v3_tmp1, _camFwd); } this._sortItems(items); this._drawItems(view, items); }; return ForwardRenderer; })(_baseRenderer["default"]); exports["default"] = ForwardRenderer; module.exports = exports["default"]; }), { "../../core/value-types": 232, "../core/base-renderer": 248, "../enums": 254, "../memop": 271 } ], 279: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _valueTypes = require("../../core/value-types"); var _geomUtils = require("../../core/geom-utils"); var _enums = _interopRequireDefault(require("../enums")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; "value" in descriptor && (descriptor.writable = true); Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { protoProps && _defineProperties(Constructor.prototype, protoProps); staticProps && _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var _tmp_mat4 = new _valueTypes.Mat4(); var _matView = new _valueTypes.Mat4(); var _matViewInv = new _valueTypes.Mat4(); var _matProj = new _valueTypes.Mat4(); var _matViewProj = new _valueTypes.Mat4(); var _matInvViewProj = new _valueTypes.Mat4(); var _tmp_v3 = new _valueTypes.Vec3(); var _tmp2_v3 = new _valueTypes.Vec3(); var Camera = (function() { function Camera() { this._poolID = -1; this._node = null; this._projection = _enums["default"].PROJ_PERSPECTIVE; this._priority = 0; this._color = new _valueTypes.Vec4(.2, .3, .47, 1); this._depth = 1; this._stencil = 0; this._clearFlags = _enums["default"].CLEAR_COLOR | _enums["default"].CLEAR_DEPTH; this._clearModel = null; this._stages = []; this._framebuffer = null; this._near = .01; this._far = 1e3; this._fov = Math.PI / 4; this._rect = { x: 0, y: 0, w: 1, h: 1 }; this._orthoHeight = 10; this._cullingMask = 4294967295; } var _proto = Camera.prototype; _proto.setCullingMask = function setCullingMask(mask) { this._cullingMask = mask; }; _proto.getNode = function getNode() { return this._node; }; _proto.setNode = function setNode(node) { this._node = node; }; _proto.getType = function getType() { return this._projection; }; _proto.setType = function setType(type) { this._projection = type; }; _proto.getPriority = function getPriority() { return this._priority; }; _proto.setPriority = function setPriority(priority) { this._priority = priority; }; _proto.getOrthoHeight = function getOrthoHeight() { return this._orthoHeight; }; _proto.setOrthoHeight = function setOrthoHeight(val) { this._orthoHeight = val; }; _proto.getFov = function getFov() { return this._fov; }; _proto.setFov = function setFov(fov) { this._fov = fov; }; _proto.getNear = function getNear() { return this._near; }; _proto.setNear = function setNear(near) { this._near = near; }; _proto.getFar = function getFar() { return this._far; }; _proto.setFar = function setFar(far) { this._far = far; }; _proto.getColor = function getColor(out) { return _valueTypes.Vec4.copy(out, this._color); }; _proto.setColor = function setColor(r, g, b, a) { _valueTypes.Vec4.set(this._color, r, g, b, a); }; _proto.getDepth = function getDepth() { return this._depth; }; _proto.setDepth = function setDepth(depth) { this._depth = depth; }; _proto.getStencil = function getStencil() { return this._stencil; }; _proto.setStencil = function setStencil(stencil) { this._stencil = stencil; }; _proto.getClearFlags = function getClearFlags() { return this._clearFlags; }; _proto.setClearFlags = function setClearFlags(flags) { this._clearFlags = flags; }; _proto.getRect = function getRect(out) { out.x = this._rect.x; out.y = this._rect.y; out.w = this._rect.w; out.h = this._rect.h; return out; }; _proto.setRect = function setRect(x, y, w, h) { this._rect.x = x; this._rect.y = y; this._rect.w = w; this._rect.h = h; }; _proto.getStages = function getStages() { return this._stages; }; _proto.setStages = function setStages(stages) { this._stages = stages; }; _proto.getFramebuffer = function getFramebuffer() { return this._framebuffer; }; _proto.setFrameBuffer = function setFrameBuffer(framebuffer) { this._framebuffer = framebuffer; }; _proto._calcMatrices = function _calcMatrices(width, height) { this._node.getWorldRT(_matViewInv); _valueTypes.Mat4.invert(_matView, _matViewInv); var aspect = width / height; if (this._projection === _enums["default"].PROJ_PERSPECTIVE) _valueTypes.Mat4.perspective(_matProj, this._fov, aspect, this._near, this._far); else { var x = this._orthoHeight * aspect; var y = this._orthoHeight; _valueTypes.Mat4.ortho(_matProj, -x, x, -y, y, this._near, this._far); } _valueTypes.Mat4.mul(_matViewProj, _matProj, _matView); _valueTypes.Mat4.invert(_matInvViewProj, _matViewProj); }; _proto.extractView = function extractView(out, width, height) { if (this._framebuffer) { width = this._framebuffer._width; height = this._framebuffer._height; } out._priority = this._priority; out._rect.x = this._rect.x * width; out._rect.y = this._rect.y * height; out._rect.w = this._rect.w * width; out._rect.h = this._rect.h * height; this.getColor(out._color); out._depth = this._depth; out._stencil = this._stencil; out._clearFlags = this._clearFlags; out._clearModel = this._clearModel; out._stages = this._stages; out._framebuffer = this._framebuffer; this._calcMatrices(width, height); _valueTypes.Mat4.copy(out._matView, _matView); _valueTypes.Mat4.copy(out._matViewInv, _matViewInv); _valueTypes.Mat4.copy(out._matProj, _matProj); _valueTypes.Mat4.copy(out._matViewProj, _matViewProj); _valueTypes.Mat4.copy(out._matInvViewProj, _matInvViewProj); out._cullingMask = this._cullingMask; }; _proto.screenPointToRay = function screenPointToRay(x, y, width, height, out) { if (!cc.geomUtils) return out; out = out || new _geomUtils.Ray(); this._calcMatrices(width, height); var cx = this._rect.x * width; var cy = this._rect.y * height; var cw = this._rect.w * width; var ch = this._rect.h * height; _valueTypes.Vec3.set(_tmp2_v3, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, 1); _valueTypes.Vec3.transformMat4(_tmp2_v3, _tmp2_v3, _matInvViewProj); if (this._projection === _enums["default"].PROJ_PERSPECTIVE) this._node.getWorldPosition(_tmp_v3); else { _valueTypes.Vec3.set(_tmp_v3, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); _valueTypes.Vec3.transformMat4(_tmp_v3, _tmp_v3, _matInvViewProj); } return _geomUtils.Ray.fromPoints(out, _tmp_v3, _tmp2_v3); }; _proto.screenToWorld = function screenToWorld(out, screenPos, width, height) { this._calcMatrices(width, height); var cx = this._rect.x * width; var cy = this._rect.y * height; var cw = this._rect.w * width; var ch = this._rect.h * height; if (this._projection === _enums["default"].PROJ_PERSPECTIVE) { _valueTypes.Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, .9999); _valueTypes.Vec3.transformMat4(out, out, _matInvViewProj); this._node.getWorldPosition(_tmp_v3); _valueTypes.Vec3.lerp(out, _tmp_v3, out, (0, _valueTypes.lerp)(this._near / this._far, 1, screenPos.z)); } else { _valueTypes.Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, 2 * screenPos.z - 1); _valueTypes.Vec3.transformMat4(out, out, _matInvViewProj); } return out; }; _proto.worldToScreen = function worldToScreen(out, worldPos, width, height) { this._calcMatrices(width, height); var cx = this._rect.x * width; var cy = this._rect.y * height; var cw = this._rect.w * width; var ch = this._rect.h * height; _valueTypes.Vec3.transformMat4(out, worldPos, _matViewProj); out.x = cx + .5 * (out.x + 1) * cw; out.y = cy + .5 * (out.y + 1) * ch; out.z = .5 * out.z + .5; return out; }; _proto.worldMatrixToScreen = function worldMatrixToScreen(out, worldMatrix, width, height) { this._calcMatrices(width, height); _valueTypes.Mat4.mul(out, _matViewProj, worldMatrix); var halfWidth = width / 2; var halfHeight = height / 2; _valueTypes.Mat4.identity(_tmp_mat4); _valueTypes.Mat4.transform(_tmp_mat4, _tmp_mat4, _valueTypes.Vec3.set(_tmp_v3, halfWidth, halfHeight, 0)); _valueTypes.Mat4.scale(_tmp_mat4, _tmp_mat4, _valueTypes.Vec3.set(_tmp_v3, halfWidth, halfHeight, 1)); _valueTypes.Mat4.mul(out, _tmp_mat4, out); return out; }; _createClass(Camera, [ { key: "cullingMask", get: function get() { return this._cullingMask; }, set: function set(mask) { this._cullingMask = mask; } } ]); return Camera; })(); exports["default"] = Camera; module.exports = exports["default"]; }), { "../../core/geom-utils": void 0, "../../core/value-types": 232, "../enums": 254 } ], 280: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var Model = (function() { function Model() { this._type = "default"; this._poolID = -1; this._node = null; this._inputAssembler = null; this._effect = null; this._viewID = -1; this._cameraID = -1; this._userKey = -1; this._castShadow = false; this._boundingShape = null; } var _proto = Model.prototype; _proto.setNode = function setNode(node) { this._node = node; }; _proto.setInputAssembler = function setInputAssembler(ia) { this._inputAssembler = ia; }; _proto.setEffect = function setEffect(effect) { this._effect = effect; }; _proto.setUserKey = function setUserKey(key) { this._userKey = key; }; _proto.extractDrawItem = function extractDrawItem(out) { out.model = this; out.node = this._node; out.ia = this._inputAssembler; out.effect = this._effect; }; return Model; })(); exports["default"] = Model; module.exports = exports["default"]; }), {} ], 281: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _memop = require("../memop"); var Scene = (function() { function Scene(app) { this._lights = new _memop.FixedArray(16); this._models = new _memop.FixedArray(16); this._cameras = new _memop.FixedArray(16); this._debugCamera = null; this._app = app; this._views = []; } var _proto = Scene.prototype; _proto._add = function _add(pool, item) { if (-1 !== item._poolID) return; pool.push(item); item._poolID = pool.length - 1; }; _proto._remove = function _remove(pool, item) { if (-1 === item._poolID) return; pool.data[pool.length - 1]._poolID = item._poolID; pool.fastRemove(item._poolID); item._poolID = -1; }; _proto.reset = function reset() { for (var i = 0; i < this._models.length; ++i) { var model = this._models.data[i]; model._viewID = -1; } }; _proto.setDebugCamera = function setDebugCamera(cam) { this._debugCamera = cam; }; _proto.getCameraCount = function getCameraCount() { return this._cameras.length; }; _proto.getCamera = function getCamera(idx) { return this._cameras.data[idx]; }; _proto.addCamera = function addCamera(camera) { this._add(this._cameras, camera); }; _proto.removeCamera = function removeCamera(camera) { this._remove(this._cameras, camera); }; _proto.getModelCount = function getModelCount() { return this._models.length; }; _proto.getModel = function getModel(idx) { return this._models.data[idx]; }; _proto.addModel = function addModel(model) { this._add(this._models, model); }; _proto.removeModel = function removeModel(model) { this._remove(this._models, model); }; _proto.getLightCount = function getLightCount() { return this._lights.length; }; _proto.getLight = function getLight(idx) { return this._lights.data[idx]; }; _proto.addLight = function addLight(light) { this._add(this._lights, light); }; _proto.removeLight = function removeLight(light) { this._remove(this._lights, light); }; _proto.addView = function addView(view) { -1 === this._views.indexOf(view) && this._views.push(view); }; _proto.removeView = function removeView(view) { var idx = this._views.indexOf(view); -1 !== idx && this._views.splice(idx, 1); }; return Scene; })(); var _default = Scene; exports["default"] = _default; module.exports = exports["default"]; }), { "../memop": 271 } ], 282: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports.getClassName = exports.enums2default = exports.ctor2enums = void 0; exports.getInspectorProps = getInspectorProps; exports.getInstanceType = exports.getInstanceCtor = void 0; var _enums = _interopRequireDefault(require("./enums")); var _valueTypes = require("../core/value-types"); var _CCTexture2D = _interopRequireDefault(require("../core/assets/CCTexture2D")); var _ctor2default, _enums2ctor, _ctor2enums, _enums2default; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var gfxTexture2D = null, gfxTextureCube = null; false; gfxTexture2D = require("./gfx/texture-2d"); var CCObject = cc.Object; var ctor2default = (_ctor2default = {}, _ctor2default[Boolean] = function(v) { return v || false; }, _ctor2default[Number] = function(v) { return v ? ArrayBuffer.isView(v) ? v[0] : v : 0; }, _ctor2default[_valueTypes.Vec2] = function(v) { return v ? cc.v2(v[0], v[1]) : cc.v2(); }, _ctor2default[_valueTypes.Vec3] = function(v) { return v ? cc.v3(v[0], v[1], v[2]) : cc.v3(); }, _ctor2default[_valueTypes.Vec4] = function(v) { return v ? cc.v4(v[0], v[1], v[2], v[3]) : cc.v4(); }, _ctor2default[_valueTypes.Color] = function(v) { return v ? cc.color(255 * v[0], 255 * v[1], 255 * v[2], 255 * (v[3] || 1)) : cc.color(); }, _ctor2default[_valueTypes.Mat4] = function(v) { return v ? cc.mat4(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15]) : cc.mat4(); }, _ctor2default[_CCTexture2D["default"]] = function() { return null; }, _ctor2default[CCObject] = function() { return null; }, _ctor2default); var enums2ctor = (_enums2ctor = {}, _enums2ctor[_enums["default"].PARAM_INT] = Number, _enums2ctor[_enums["default"].PARAM_INT2] = _valueTypes.Vec2, _enums2ctor[_enums["default"].PARAM_INT3] = _valueTypes.Vec3, _enums2ctor[_enums["default"].PARAM_INT4] = _valueTypes.Vec4, _enums2ctor[_enums["default"].PARAM_FLOAT] = Number, _enums2ctor[_enums["default"].PARAM_FLOAT2] = _valueTypes.Vec2, _enums2ctor[_enums["default"].PARAM_FLOAT3] = _valueTypes.Vec3, _enums2ctor[_enums["default"].PARAM_FLOAT4] = _valueTypes.Vec4, _enums2ctor[_enums["default"].PARAM_MAT4] = _valueTypes.Mat4, _enums2ctor[_enums["default"].PARAM_TEXTURE_2D] = _CCTexture2D["default"], _enums2ctor.color = _valueTypes.Color, _enums2ctor.number = Number, _enums2ctor["boolean"] = Boolean, _enums2ctor["default"] = CCObject, _enums2ctor); var ctor2enums = (_ctor2enums = {}, _ctor2enums[Number] = _enums["default"].PARAM_FLOAT, _ctor2enums[_valueTypes.Vec2] = _enums["default"].PARAM_FLOAT2, _ctor2enums[_valueTypes.Vec3] = _enums["default"].PARAM_FLOAT3, _ctor2enums[_valueTypes.Vec4] = _enums["default"].PARAM_FLOAT4, _ctor2enums[_valueTypes.Color] = _enums["default"].PARAM_COLOR3, _ctor2enums[_valueTypes.Color] = _enums["default"].PARAM_COLOR4, _ctor2enums[_valueTypes.Mat4] = _enums["default"].PARAM_MAT4, _ctor2enums[_CCTexture2D["default"]] = _enums["default"].PARAM_TEXTURE_2D, _ctor2enums[gfxTexture2D] = _enums["default"].PARAM_TEXTURE_2D, _ctor2enums); exports.ctor2enums = ctor2enums; var enums2default = (_enums2default = {}, _enums2default[_enums["default"].PARAM_INT] = new Uint32Array([ 0 ]), _enums2default[_enums["default"].PARAM_INT2] = new Uint32Array([ 0, 0 ]), _enums2default[_enums["default"].PARAM_INT3] = new Uint32Array([ 0, 0, 0 ]), _enums2default[_enums["default"].PARAM_INT4] = new Uint32Array([ 0, 0, 0, 0 ]), _enums2default[_enums["default"].PARAM_FLOAT] = new Float32Array([ 0 ]), _enums2default[_enums["default"].PARAM_FLOAT2] = new Float32Array([ 0, 0 ]), _enums2default[_enums["default"].PARAM_FLOAT3] = new Float32Array([ 0, 0, 0 ]), _enums2default[_enums["default"].PARAM_FLOAT4] = new Float32Array([ 0, 0, 0, 0 ]), _enums2default[_enums["default"].PARAM_MAT4] = new Float32Array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]), _enums2default[_enums["default"].PARAM_TEXTURE_2D] = null, _enums2default.number = 0, _enums2default["boolean"] = false, _enums2default); exports.enums2default = enums2default; var getInstanceType = function getInstanceType(t) { return enums2ctor[t] || enums2ctor["default"]; }; exports.getInstanceType = getInstanceType; var getInstanceCtor = function getInstanceCtor(t) { return ctor2default[getInstanceType(t)]; }; exports.getInstanceCtor = getInstanceCtor; var getClassName = function getClassName(t) { return cc.js.getClassName(getInstanceType(t)); }; exports.getClassName = getClassName; var className2InspectorName = { Number: "number", Boolean: "boolean" }; function getInspectorProps(prop) { var editor = { type: prop.type }; Object.assign(editor, prop.editor || prop.inspector); editor.defines = prop.defines; editor.value = getInstanceCtor(editor.type)(prop.value); prop.range && (editor.range = prop.range); var className = getClassName(editor.type); editor.typeName = className2InspectorName[className] || className; editor.valueCtor = enums2ctor[editor.type]; if ("cc.Texture2D" == editor.typeName) { editor.typeName = "cc.Asset"; editor.assetType = "cc.Texture2D"; } return editor; } }), { "../core/assets/CCTexture2D": 72, "../core/value-types": 232, "./enums": 254, "./gfx/texture-2d": 264 } ], 283: [ (function(require, module, exports) { "use strict"; var TiledMapAsset = cc.Class({ name: "cc.TiledMapAsset", extends: cc.Asset, properties: { tmxXmlStr: "", textures: { default: [], type: [ cc.Texture2D ] }, textureNames: [ cc.String ], textureSizes: { default: [], type: [ cc.Size ] }, imageLayerTextures: { default: [], type: [ cc.Texture2D ] }, imageLayerTextureNames: [ cc.String ], tsxFiles: [ cc.TextAsset ], tsxFileNames: [ cc.String ] }, statics: { preventDeferredLoadDependents: true }, createNode: false }); cc.TiledMapAsset = TiledMapAsset; module.exports = TiledMapAsset; }), {} ], 284: [ (function(require, module, exports) { "use strict"; require("./cocos2d/core"); require("./cocos2d/animation"); false; require("./cocos2d/particle"); require("./cocos2d/tilemap"); require("./cocos2d/videoplayer/CCVideoPlayer"); require("./cocos2d/webview/CCWebView"); require("./cocos2d/core/components/CCStudioComponent"); require("./extensions/ccpool/CCNodePool"); require("./cocos2d/actions"); require("./extensions/spine"); require("./extensions/dragonbones"); true; require("./cocos2d/deprecated"); }), { "./cocos2d/actions": 8, "./cocos2d/animation": 17, "./cocos2d/core": 127, "./cocos2d/core/components/CCStudioComponent": void 0, "./cocos2d/deprecated": 244, "./cocos2d/particle": void 0, "./cocos2d/particle/CCParticleAsset": 246, "./cocos2d/tilemap": void 0, "./cocos2d/tilemap/CCTiledMapAsset": 283, "./cocos2d/videoplayer/CCVideoPlayer": void 0, "./cocos2d/webview/CCWebView": void 0, "./extensions/ccpool/CCNodePool": void 0, "./extensions/dragonbones": void 0, "./extensions/spine": 287 } ], 285: [ (function(require, module, exports) { "use strict"; var _mat = _interopRequireDefault(require("../../cocos2d/core/value-types/mat4")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var RenderFlow = require("../../cocos2d/core/renderer/render-flow"); var FLAG_TRANSFORM = RenderFlow.FLAG_TRANSFORM; var EmptyHandle = function EmptyHandle() {}; var ATTACHED_ROOT_NAME = "ATTACHED_NODE_TREE"; var ATTACHED_PRE_NAME = "ATTACHED_NODE:"; var limitNode = function limitNode(node) { Object.defineProperty(node, "_worldMatDirty", { get: function get() { return true; }, set: function set(value) {} }); node._calculWorldMatrix = EmptyHandle; node._mulMat = EmptyHandle; }; var _tempMat4 = new _mat["default"](); var AttachUtil = cc.Class({ name: "sp.AttachUtil", ctor: function ctor() { this._inited = false; this._skeleton = null; this._skeletonNode = null; this._skeletonComp = null; this._attachedRootNode = null; this._attachedNodeArray = []; this._boneIndexToNode = {}; }, init: function init(skeletonComp) { this._inited = true; this._skeleton = skeletonComp._skeleton; this._skeletonNode = skeletonComp.node; this._skeletonComp = skeletonComp; }, reset: function reset() { this._inited = false; this._skeleton = null; this._skeletonNode = null; this._skeletonComp = null; }, _prepareAttachNode: function _prepareAttachNode() { var armature = this._skeleton; if (!armature) return; var rootNode = this._skeletonNode.getChildByName(ATTACHED_ROOT_NAME); if (!rootNode || !rootNode.isValid) { rootNode = new cc.Node(ATTACHED_ROOT_NAME); limitNode(rootNode); this._skeletonNode.addChild(rootNode); } var isCached = this._skeletonComp.isAnimationCached(); isCached && this._skeletonComp._frameCache && this._skeletonComp._frameCache.enableCacheAttachedInfo(); this._attachedRootNode = rootNode; return rootNode; }, _buildBoneAttachedNode: function _buildBoneAttachedNode(bone, boneIndex) { var boneNodeName = ATTACHED_PRE_NAME + bone.data.name; var boneNode = new cc.Node(boneNodeName); this._buildBoneRelation(boneNode, bone, boneIndex); return boneNode; }, _buildBoneRelation: function _buildBoneRelation(boneNode, bone, boneIndex) { limitNode(boneNode); boneNode._bone = bone; boneNode._boneIndex = boneIndex; this._attachedNodeArray.push(boneNode); this._boneIndexToNode[boneIndex] = boneNode; }, getAttachedRootNode: function getAttachedRootNode() { return this._attachedRootNode; }, getAttachedNodes: function getAttachedNodes(boneName) { var nodeArray = this._attachedNodeArray; var res = []; if (!this._inited) return res; for (var i = 0, n = nodeArray.length; i < n; i++) { var boneNode = nodeArray[i]; if (!boneNode || !boneNode.isValid) continue; boneNode.name === ATTACHED_PRE_NAME + boneName && res.push(boneNode); } return res; }, _rebuildNodeArray: function _rebuildNodeArray() { var findMap = this._boneIndexToNode = {}; var oldNodeArray = this._attachedNodeArray; var nodeArray = this._attachedNodeArray = []; for (var i = 0, n = oldNodeArray.length; i < n; i++) { var boneNode = oldNodeArray[i]; if (!boneNode || !boneNode.isValid || boneNode._toRemove) continue; nodeArray.push(boneNode); findMap[boneNode._boneIndex] = boneNode; } }, _sortNodeArray: function _sortNodeArray() { var nodeArray = this._attachedNodeArray; nodeArray.sort((function(a, b) { return a._boneIndex < b._boneIndex ? -1 : 1; })); }, _getNodeByBoneIndex: function _getNodeByBoneIndex(boneIndex) { var findMap = this._boneIndexToNode; var boneNode = findMap[boneIndex]; if (!boneNode || !boneNode.isValid) return null; return boneNode; }, destroyAttachedNodes: function destroyAttachedNodes(boneName) { if (!this._inited) return; var nodeArray = this._attachedNodeArray; var markTree = function markTree(rootNode) { var children = rootNode.children; for (var i = 0, n = children.length; i < n; i++) { var c = children[i]; c && markTree(c); } rootNode._toRemove = true; }; for (var i = 0, n = nodeArray.length; i < n; i++) { var boneNode = nodeArray[i]; if (!boneNode || !boneNode.isValid) continue; var delName = boneNode.name.split(ATTACHED_PRE_NAME)[1]; if (delName === boneName) { markTree(boneNode); boneNode.removeFromParent(true); boneNode.destroy(); nodeArray[i] = null; } } this._rebuildNodeArray(); }, generateAttachedNodes: function generateAttachedNodes(boneName) { var targetNodes = []; if (!this._inited) return targetNodes; var rootNode = this._prepareAttachNode(); if (!rootNode) return targetNodes; var res = []; var bones = this._skeleton.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; var boneData = bone.data; boneData.name == boneName && res.push(bone); } var buildBoneTree = function(bone) { if (!bone) return; var boneData = bone.data; var boneNode = this._getNodeByBoneIndex(boneData.index); if (boneNode) return boneNode; boneNode = this._buildBoneAttachedNode(bone, boneData.index); var parentBoneNode = buildBoneTree(bone.parent) || rootNode; boneNode.parent = parentBoneNode; return boneNode; }.bind(this); for (var _i = 0, _n = res.length; _i < _n; _i++) { var targetNode = buildBoneTree(res[_i]); targetNodes.push(targetNode); } this._sortNodeArray(); return targetNodes; }, destroyAllAttachedNodes: function destroyAllAttachedNodes() { this._attachedRootNode = null; this._attachedNodeArray.length = 0; this._boneIndexToNode = {}; if (!this._inited) return; var rootNode = this._skeletonNode.getChildByName(ATTACHED_ROOT_NAME); if (rootNode) { rootNode.removeFromParent(true); rootNode.destroy(); rootNode = null; } }, generateAllAttachedNodes: function generateAllAttachedNodes() { if (!this._inited) return; this._boneIndexToNode = {}; this._attachedNodeArray.length = 0; var rootNode = this._prepareAttachNode(); if (!rootNode) return; var bones = this._skeleton.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; var boneData = bone.data; var parentNode = null; if (bone.parent) { var parentIndex = bone.parent.data.index; parentNode = this._boneIndexToNode[parentIndex]; } else parentNode = rootNode; if (parentNode) { var boneNode = parentNode.getChildByName(ATTACHED_PRE_NAME + boneData.name); if (boneNode && boneNode.isValid) this._buildBoneRelation(boneNode, bone, boneData.index); else { boneNode = this._buildBoneAttachedNode(bone, boneData.index); parentNode.addChild(boneNode); } } } return rootNode; }, _hasAttachedNode: function _hasAttachedNode() { if (!this._inited) return false; var attachedRootNode = this._skeletonNode.getChildByName(ATTACHED_ROOT_NAME); return !!attachedRootNode; }, _associateAttachedNode: function _associateAttachedNode() { if (!this._inited) return; var rootNode = this._skeletonNode.getChildByName(ATTACHED_ROOT_NAME); if (!rootNode || !rootNode.isValid) return; this._attachedRootNode = rootNode; this._boneIndexToNode = {}; var nodeArray = this._attachedNodeArray; nodeArray.length = 0; limitNode(rootNode); true; var isCached = this._skeletonComp.isAnimationCached(); isCached && this._skeletonComp._frameCache && this._skeletonComp._frameCache.enableCacheAttachedInfo(); var bones = this._skeleton.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; var boneData = bone.data; var parentNode = null; if (bone.parent) { var parentIndex = bone.parent.data.index; parentNode = this._boneIndexToNode[parentIndex]; } else parentNode = rootNode; if (parentNode) { var boneNode = parentNode.getChildByName(ATTACHED_PRE_NAME + boneData.name); boneNode && boneNode.isValid && this._buildBoneRelation(boneNode, bone, boneData.index); } } }, _syncAttachedNode: function _syncAttachedNode() { if (!this._inited) return; var rootNode = this._attachedRootNode; var nodeArray = this._attachedNodeArray; if (!rootNode || !rootNode.isValid) { this._attachedRootNode = null; nodeArray.length = 0; return; } var rootMatrix = this._skeletonNode._worldMatrix; _mat["default"].copy(rootNode._worldMatrix, rootMatrix); rootNode._renderFlag &= ~FLAG_TRANSFORM; var boneInfos = null; var isCached = this._skeletonComp.isAnimationCached(); boneInfos = isCached ? this._skeletonComp._curFrame && this._skeletonComp._curFrame.boneInfos : this._skeleton.bones; if (!boneInfos) return; var mulMat = this._skeletonNode._mulMat; var matrixHandle = function matrixHandle(nodeMat, parentMat, bone) { var tm = _tempMat4.m; tm[0] = bone.a; tm[1] = bone.c; tm[4] = bone.b; tm[5] = bone.d; tm[12] = bone.worldX; tm[13] = bone.worldY; mulMat(nodeMat, parentMat, _tempMat4); }; var nodeArrayDirty = false; for (var i = 0, n = nodeArray.length; i < n; i++) { var boneNode = nodeArray[i]; if (!boneNode || !boneNode.isValid) { nodeArray[i] = null; nodeArrayDirty = true; continue; } var bone = boneInfos[boneNode._boneIndex]; if (!bone) { boneNode.removeFromParent(true); boneNode.destroy(); nodeArray[i] = null; nodeArrayDirty = true; continue; } matrixHandle(boneNode._worldMatrix, rootNode._worldMatrix, bone); boneNode._renderFlag &= ~FLAG_TRANSFORM; } nodeArrayDirty && this._rebuildNodeArray(); } }); module.exports = sp.AttachUtil = AttachUtil; }), { "../../cocos2d/core/renderer/render-flow": 161, "../../cocos2d/core/value-types/mat4": 234 } ], 286: [ (function(require, module, exports) { "use strict"; var TrackEntryListeners = require("./track-entry-listeners"); var RenderComponent = require("../../cocos2d/core/components/CCRenderComponent"); var spine = require("./lib/spine"); var Graphics = require("../../cocos2d/core/graphics/graphics"); var RenderFlow = require("../../cocos2d/core/renderer/render-flow"); var FLAG_POST_RENDER = RenderFlow.FLAG_POST_RENDER; var SkeletonCache = require("./skeleton-cache"); var AttachUtil = require("./AttachUtil"); var DefaultSkinsEnum = cc.Enum({ default: -1 }); var DefaultAnimsEnum = cc.Enum({ "": 0 }); var AnimationCacheMode = cc.Enum({ REALTIME: 0, SHARED_CACHE: 1, PRIVATE_CACHE: 2 }); function setEnumAttr(obj, propName, enumDef) { cc.Class.Attr.setClassAttr(obj, propName, "type", "Enum"); cc.Class.Attr.setClassAttr(obj, propName, "enumList", cc.Enum.getList(enumDef)); } sp.Skeleton = cc.Class({ name: "sp.Skeleton", extends: RenderComponent, editor: false, statics: { AnimationCacheMode: AnimationCacheMode }, properties: { paused: { default: false, visible: false }, skeletonData: { default: null, type: sp.SkeletonData, notify: function notify() { false; this.defaultSkin = ""; this.defaultAnimation = ""; this._updateSkeletonData(); }, tooltip: false }, defaultSkin: { default: "", visible: false }, defaultAnimation: { default: "", visible: false }, animation: { get: function get() { if (this.isAnimationCached()) return this._animationName; var entry = this.getCurrent(0); return entry && entry.animation.name || ""; }, set: function set(value) { this.defaultAnimation = value; if (value) this.setAnimation(0, value, this.loop); else if (!this.isAnimationCached()) { this.clearTrack(0); this.setToSetupPose(); } }, visible: false }, _defaultSkinIndex: { get: function get() { if (this.skeletonData) { var skinsEnum = this.skeletonData.getSkinsEnum(); if (skinsEnum) if ("" === this.defaultSkin) { if (skinsEnum.hasOwnProperty(0)) { this._defaultSkinIndex = 0; return 0; } } else { var skinIndex = skinsEnum[this.defaultSkin]; if (void 0 !== skinIndex) return skinIndex; } } return 0; }, set: function set(value) { var skinsEnum; this.skeletonData && (skinsEnum = this.skeletonData.getSkinsEnum()); if (!skinsEnum) return cc.errorID("", this.name); var skinName = skinsEnum[value]; if (void 0 !== skinName) { this.defaultSkin = skinName; this.setSkin(this.defaultSkin); false; } else cc.errorID(7501, this.name); }, type: DefaultSkinsEnum, visible: true, animatable: false, displayName: "Default Skin", tooltip: false }, _animationIndex: { get: function get() { var animationName = this.animation; if (this.skeletonData && animationName) { var animsEnum = this.skeletonData.getAnimsEnum(); if (animsEnum) { var animIndex = animsEnum[animationName]; if (void 0 !== animIndex) return animIndex; } } return 0; }, set: function set(value) { if (0 === value) { this.animation = ""; return; } var animsEnum; this.skeletonData && (animsEnum = this.skeletonData.getAnimsEnum()); if (!animsEnum) return cc.errorID(7502, this.name); var animName = animsEnum[value]; void 0 !== animName ? this.animation = animName : cc.errorID(7503, this.name); }, type: DefaultAnimsEnum, visible: true, animatable: false, displayName: "Animation", tooltip: false }, _preCacheMode: -1, _cacheMode: AnimationCacheMode.REALTIME, _defaultCacheMode: { default: 0, type: AnimationCacheMode, notify: function notify() { this.setAnimationCacheMode(this._defaultCacheMode); }, editorOnly: true, visible: true, animatable: false, displayName: "Animation Cache Mode", tooltip: false }, loop: { default: true, tooltip: false }, premultipliedAlpha: { default: true, tooltip: false }, timeScale: { default: 1, tooltip: false }, debugSlots: { default: false, editorOnly: true, tooltip: false, notify: function notify() { this._updateDebugDraw(); } }, debugBones: { default: false, editorOnly: true, tooltip: false, notify: function notify() { this._updateDebugDraw(); } }, debugMesh: { default: false, editorOnly: true, tooltip: false, notify: function notify() { this._updateDebugDraw(); } }, useTint: { default: false, tooltip: false, notify: function notify() { this._updateUseTint(); } }, enableBatch: { default: false, notify: function notify() { this._updateBatch(); }, tooltip: false }, _accTime: 0, _playCount: 0, _frameCache: null, _curFrame: null, _skeletonCache: null, _animationName: "", _animationQueue: [], _headAniInfo: null, _playTimes: 0, _isAniComplete: true, autoSwitchMaterial: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.autoSwitchMaterial === oldValue) return; this.setVertsDirty(); } }, allowDynamicAtlas: { type: RenderComponent.EnableType, default: RenderComponent.EnableType.GLOBAL, notify: function notify(oldValue) { if (this.allowDynamicAtlas === oldValue) return; this.setVertsDirty(); } } }, ctor: function ctor() { this._effectDelegate = null; this._skeleton = null; this._rootBone = null; this._listener = null; this._materialCache = {}; this._debugRenderer = null; this._startSlotIndex = -1; this._endSlotIndex = -1; this._startEntry = { animation: { name: "" }, trackIndex: 0 }; this._endEntry = { animation: { name: "" }, trackIndex: 0 }; this.attachUtil = new AttachUtil(); this._dataDirty = true; }, setVertsDirty: function setVertsDirty() { this._dataDirty = true; this.invalidAnimationCache(); this._materialCache = {}; this._super(); }, _getDefaultMaterial: function _getDefaultMaterial() { return cc.Material.getBuiltinMaterial("2d-spine"); }, _updateMaterial: function _updateMaterial() { var useTint = this.useTint; var baseMaterial = this.getMaterial(0); if (baseMaterial) { var isMultiSupport = baseMaterial.material.isMultiSupport(); if (isMultiSupport) this._defineMaterialTint(baseMaterial, useTint); else { baseMaterial.define("USE_TINT", useTint); baseMaterial.define("CC_USE_MODEL", !this.enableBatch); } var srcBlendFactor = this.premultipliedAlpha ? cc.gfx.BLEND_ONE : cc.gfx.BLEND_SRC_ALPHA; var dstBlendFactor = cc.gfx.BLEND_ONE_MINUS_SRC_ALPHA; baseMaterial.setBlend(true, cc.gfx.BLEND_FUNC_ADD, srcBlendFactor, srcBlendFactor, cc.gfx.BLEND_FUNC_ADD, dstBlendFactor, dstBlendFactor); isMultiSupport && (this.enableBatch || (this.enableBatch = true)); false; } this._materialCache = {}; }, disableRender: function disableRender() { this._super(); this.node._renderFlag &= ~FLAG_POST_RENDER; }, markForRender: function markForRender(enable) { this._super(enable); enable ? this.node._renderFlag |= FLAG_POST_RENDER : this.node._renderFlag &= ~FLAG_POST_RENDER; }, _updateUseTint: function _updateUseTint() { var baseMaterial = this.getMaterial(0); if (baseMaterial) { var useTint = this.useTint; baseMaterial.material.isMultiSupport() ? this._defineMaterialTint(baseMaterial, useTint) : baseMaterial.define("USE_TINT", useTint); } this._materialCache = {}; }, _defineMaterialTint: function _defineMaterialTint(material, useTint) { var passes = material._effect._passes; passes && passes.length > 0 && passes[0]._defines["USE_TINT"] != useTint && material.define("USE_TINT", useTint); }, _updateBatch: function _updateBatch() { var baseMaterial = this.getMaterial(0); baseMaterial && (baseMaterial.material.isMultiSupport() ? this.enableBatch || (this.enableBatch = true) : baseMaterial.define("CC_USE_MODEL", !this.enableBatch)); this._materialCache = {}; }, _validateRender: function _validateRender() { var skeletonData = this.skeletonData; if (!skeletonData || !skeletonData.isTexturesLoaded()) { this.disableRender(); return; } this._super(); }, setSkeletonData: function setSkeletonData(skeletonData) { null != skeletonData.width && null != skeletonData.height && this.node.setContentSize(skeletonData.width, skeletonData.height); true; if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) this._skeletonCache = SkeletonCache.sharedCache; else if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) { this._skeletonCache = new SkeletonCache(); this._skeletonCache.enablePrivateMode(); } if (this.isAnimationCached()) { (this.debugBones || this.debugSlots) && cc.warn("Debug bones or slots is invalid in cached mode"); var skeletonInfo = this._skeletonCache.getSkeletonCache(this.skeletonData._uuid, skeletonData); this._skeleton = skeletonInfo.skeleton; this._clipper = skeletonInfo.clipper; this._rootBone = this._skeleton.getRootBone(); } else { this._skeleton = new spine.Skeleton(skeletonData); this._clipper = new spine.SkeletonClipping(); this._rootBone = this._skeleton.getRootBone(); } this.markForRender(true); }, setSlotsRange: function setSlotsRange(startSlotIndex, endSlotIndex) { if (this.isAnimationCached()) cc.warn("Slots visible range can not be modified in cached mode."); else { this._startSlotIndex = startSlotIndex; this._endSlotIndex = endSlotIndex; } }, setAnimationStateData: function setAnimationStateData(stateData) { if (this.isAnimationCached()) cc.warn("'setAnimationStateData' interface can not be invoked in cached mode."); else { var state = new spine.AnimationState(stateData); if (this._listener) { this._state && this._state.removeListener(this._listener); state.addListener(this._listener); } this._state = state; } }, __preload: function __preload() { this._super(); var Flags; false; var children = this.node.children; for (var i = 0, n = children.length; i < n; i++) { var child = children[i]; child && "DEBUG_DRAW_NODE" === child._name && child.destroy(); } this._updateSkeletonData(); this._updateDebugDraw(); this._updateUseTint(); this._updateBatch(); }, setAnimationCacheMode: function setAnimationCacheMode(cacheMode) { if (this._preCacheMode !== cacheMode) { this._cacheMode = cacheMode; this._updateSkeletonData(); this._updateUseTint(); } }, isAnimationCached: function isAnimationCached() { false; return this._cacheMode !== AnimationCacheMode.REALTIME; }, update: function update(dt) { false; if (this.paused) return; dt *= this.timeScale * sp.timeScale; if (this.isAnimationCached()) { this._assembler && this._assembler.handleDynamicAtlasAndSwitchMaterial(this); if (this._isAniComplete) { if (0 === this._animationQueue.length && !this._headAniInfo) { var frameCache = this._frameCache; if (frameCache && frameCache.isInvalid()) { frameCache.updateToFrame(); var frames = frameCache.frames; this._curFrame = frames[frames.length - 1]; } return; } this._headAniInfo || (this._headAniInfo = this._animationQueue.shift()); this._accTime += dt; if (this._accTime > this._headAniInfo.delay) { var aniInfo = this._headAniInfo; this._headAniInfo = null; this.setAnimation(0, aniInfo.animationName, aniInfo.loop); } return; } this._updateCache(dt); } else this._updateRealtime(dt); }, _emitCacheCompleteEvent: function _emitCacheCompleteEvent() { if (!this._listener) return; this._endEntry.animation.name = this._animationName; this._listener.complete && this._listener.complete(this._endEntry); this._listener.end && this._listener.end(this._endEntry); }, _updateCache: function _updateCache(dt) { var frameCache = this._frameCache; if (!frameCache.isInited()) return; var frames = frameCache.frames; var frameTime = SkeletonCache.FrameTime; if (0 == this._accTime && 0 == this._playCount) { this._startEntry.animation.name = this._animationName; this._listener && this._listener.start && this._listener.start(this._startEntry); } this._accTime += dt; var frameIdx = Math.floor(this._accTime / frameTime); frameCache.isCompleted || frameCache.updateToFrame(frameIdx); if (frameCache.isCompleted && frameIdx >= frames.length) { this._playCount++; if (this._playTimes > 0 && this._playCount >= this._playTimes) { this._curFrame = frames[frames.length - 1]; this._accTime = 0; this._playCount = 0; this._isAniComplete = true; this._emitCacheCompleteEvent(); return; } this._accTime = 0; frameIdx = 0; this._emitCacheCompleteEvent(); } this._curFrame = frames[frameIdx]; }, _updateRealtime: function _updateRealtime(dt) { var skeleton = this._skeleton; var state = this._state; if (skeleton) { skeleton.update(dt); if (state) { state.update(dt); state.apply(skeleton); } } }, setVertexEffectDelegate: function setVertexEffectDelegate(effectDelegate) { this._effectDelegate = effectDelegate; }, updateWorldTransform: function updateWorldTransform() { if (!this.isAnimationCached()) return; this._skeleton && this._skeleton.updateWorldTransform(); }, setToSetupPose: function setToSetupPose() { this._skeleton && this._skeleton.setToSetupPose(); }, setBonesToSetupPose: function setBonesToSetupPose() { this._skeleton && this._skeleton.setBonesToSetupPose(); }, setSlotsToSetupPose: function setSlotsToSetupPose() { this._skeleton && this._skeleton.setSlotsToSetupPose(); }, updateAnimationCache: function updateAnimationCache(animName) { if (!this.isAnimationCached()) return; var uuid = this.skeletonData._uuid; this._skeletonCache && this._skeletonCache.updateAnimationCache(uuid, animName); }, invalidAnimationCache: function invalidAnimationCache() { if (!this.isAnimationCached()) return; this._skeletonCache && this._skeletonCache.invalidAnimationCache(this.skeletonData._uuid); }, findBone: function findBone(boneName) { if (this._skeleton) return this._skeleton.findBone(boneName); return null; }, findSlot: function findSlot(slotName) { if (this._skeleton) return this._skeleton.findSlot(slotName); return null; }, setSkin: function setSkin(skinName) { if (this._skeleton) { this._skeleton.setSkinByName(skinName); this._skeleton.setSlotsToSetupPose(); } this.invalidAnimationCache(); }, getAttachment: function getAttachment(slotName, attachmentName) { if (this._skeleton) return this._skeleton.getAttachmentByName(slotName, attachmentName); return null; }, setAttachment: function setAttachment(slotName, attachmentName) { this._skeleton && this._skeleton.setAttachment(slotName, attachmentName); this.invalidAnimationCache(); }, getRegionData: function getRegionData(slotName, attachmentName) { var attachment = this.getAttachment(slotName, attachmentName); if (attachment) return new sp.RegionData(attachment); return null; }, setRegionData: function setRegionData(slotName, attachmentName, regionData) { var attachment = this.getAttachment(slotName, attachmentName); if (attachment) { regionData.assignToAttachment(attachment); this.setVertsDirty(); return true; } return false; }, getTextureAtlas: function getTextureAtlas(regionAttachment) { return regionAttachment.region; }, setMix: function setMix(fromAnimation, toAnimation, duration) { this._state && this._state.data.setMix(fromAnimation, toAnimation, duration); }, setAnimation: function setAnimation(trackIndex, name, loop) { this._playTimes = loop ? 0 : 1; this._animationName = name; if (this.isAnimationCached()) { 0 !== trackIndex && cc.warn("Track index can not greater than 0 in cached mode."); if (!this._skeletonCache) return null; var cache = this._skeletonCache.getAnimationCache(this.skeletonData._uuid, name); cache || (cache = this._skeletonCache.initAnimationCache(this.skeletonData._uuid, name)); if (cache) { this._isAniComplete = false; this._accTime = 0; this._playCount = 0; this._frameCache = cache; this.attachUtil._hasAttachedNode() && this._frameCache.enableCacheAttachedInfo(); this._assembler && this._assembler.handleDynamicAtlasAndSwitchMaterial(this); this._frameCache.updateToFrame(0); this._curFrame = this._frameCache.frames[0]; } } else if (this._skeleton) { var animation = this._skeleton.data.findAnimation(name); if (!animation) { cc.logID(7509, name); return null; } var res = this._state.setAnimationWith(trackIndex, animation, loop); this._state.apply(this._skeleton); return res; } return null; }, addAnimation: function addAnimation(trackIndex, name, loop, delay) { delay = delay || 0; if (this.isAnimationCached()) { 0 !== trackIndex && cc.warn("Track index can not greater than 0 in cached mode."); this._animationQueue.push({ animationName: name, loop: loop, delay: delay }); } else if (this._skeleton) { var animation = this._skeleton.data.findAnimation(name); if (!animation) { cc.logID(7510, name); return null; } return this._state.addAnimationWith(trackIndex, animation, loop, delay); } return null; }, findAnimation: function findAnimation(name) { if (this._skeleton) return this._skeleton.data.findAnimation(name); return null; }, getCurrent: function getCurrent(trackIndex) { if (this.isAnimationCached()) cc.warn("'getCurrent' interface can not be invoked in cached mode."); else if (this._state) return this._state.getCurrent(trackIndex); return null; }, clearTracks: function clearTracks() { this.isAnimationCached() ? cc.warn("'clearTracks' interface can not be invoked in cached mode.") : this._state && this._state.clearTracks(); }, clearTrack: function clearTrack(trackIndex) { if (this.isAnimationCached()) cc.warn("'clearTrack' interface can not be invoked in cached mode."); else if (this._state) { this._state.clearTrack(trackIndex); false; } }, setStartListener: function setStartListener(listener) { this._ensureListener(); this._listener.start = listener; }, setInterruptListener: function setInterruptListener(listener) { this._ensureListener(); this._listener.interrupt = listener; }, setEndListener: function setEndListener(listener) { this._ensureListener(); this._listener.end = listener; }, setDisposeListener: function setDisposeListener(listener) { this._ensureListener(); this._listener.dispose = listener; }, setCompleteListener: function setCompleteListener(listener) { this._ensureListener(); this._listener.complete = listener; }, setEventListener: function setEventListener(listener) { this._ensureListener(); this._listener.event = listener; }, setTrackStartListener: function setTrackStartListener(entry, listener) { TrackEntryListeners.getListeners(entry).start = listener; }, setTrackInterruptListener: function setTrackInterruptListener(entry, listener) { TrackEntryListeners.getListeners(entry).interrupt = listener; }, setTrackEndListener: function setTrackEndListener(entry, listener) { TrackEntryListeners.getListeners(entry).end = listener; }, setTrackDisposeListener: function setTrackDisposeListener(entry, listener) { TrackEntryListeners.getListeners(entry).dispose = listener; }, setTrackCompleteListener: function setTrackCompleteListener(entry, listener) { TrackEntryListeners.getListeners(entry).complete = function(trackEntry) { var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); listener(trackEntry, loopCount); }; }, setTrackEventListener: function setTrackEventListener(entry, listener) { TrackEntryListeners.getListeners(entry).event = listener; }, getState: function getState() { return this._state; }, _resetDefaultAnim: false, _resetDefaultSkin: false, _updateAnimEnum: false, _updateSkinEnum: false, _ensureListener: function _ensureListener() { if (!this._listener) { this._listener = new TrackEntryListeners(); this._state && this._state.addListener(this._listener); } }, _updateSkeletonData: function _updateSkeletonData() { this._dataDirty = true; if (!this.skeletonData) { this.disableRender(); return; } var data = this.skeletonData.getRuntimeData(); if (!data) { this.disableRender(); return; } try { this.setSkeletonData(data); this.isAnimationCached() || this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); this.defaultSkin && this.setSkin(this.defaultSkin); } catch (e) { cc.warn(e); } this.attachUtil.init(this); this.attachUtil._associateAttachedNode(); this._preCacheMode = this._cacheMode; this.animation = this.defaultAnimation; }, _refreshInspector: function _refreshInspector() { this._updateAnimEnum(); this._updateSkinEnum(); Editor.Utils.refreshSelectedInspector("node", this.node.uuid); }, _updateDebugDraw: function _updateDebugDraw() { if (this.debugBones || this.debugSlots) { if (!this._debugRenderer) { var debugDrawNode = new cc.PrivateNode(); debugDrawNode.name = "DEBUG_DRAW_NODE"; var debugDraw = debugDrawNode.addComponent(Graphics); debugDraw.lineWidth = 1; debugDraw.strokeColor = cc.color(255, 0, 0, 255); this._debugRenderer = debugDraw; } this._debugRenderer.node.parent = this.node; this.isAnimationCached() && cc.warn("Debug bones or slots is invalid in cached mode"); } else this._debugRenderer && (this._debugRenderer.node.parent = null); } }); module.exports = sp.Skeleton; }), { "../../cocos2d/core/components/CCRenderComponent": 100, "../../cocos2d/core/graphics/graphics": 123, "../../cocos2d/core/renderer/render-flow": 161, "./AttachUtil": 285, "./lib/spine": 288, "./skeleton-cache": 289, "./track-entry-listeners": 293 } ], 287: [ (function(require, module, exports) { "use strict"; var _global = "undefined" === typeof window ? global : window; var _isUseSpine = true; true; _global.spine = require("./lib/spine"); if (_isUseSpine) { _global.sp = _global.sp || {}; sp._timeScale = 1; Object.defineProperty(sp, "timeScale", { get: function get() { return this._timeScale; }, set: function set(value) { this._timeScale = value; }, configurable: true }); sp.ATTACHMENT_TYPE = { REGION: 0, BOUNDING_BOX: 1, MESH: 2, SKINNED_MESH: 3 }; sp.AnimationEventType = cc.Enum({ START: 0, INTERRUPT: 1, END: 2, DISPOSE: 3, COMPLETE: 4, EVENT: 5 }); true; sp.spine = _global.spine; true; require("./skeleton-texture"); require("./skeleton-data"); require("./vertex-effect-delegate"); require("./Skeleton"); require("./spine-assembler"); } }), { "./Skeleton": 286, "./lib/spine": 288, "./skeleton-data": 290, "./skeleton-texture": 291, "./spine-assembler": 292, "./vertex-effect-delegate": 294 } ], 288: [ (function(require, module, exports) { "use strict"; var __extends = (void 0, (function() { var _extendStatics = function extendStatics(d, b) { _extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) { d.__proto__ = b; } || function(d, b) { for (var p in b) b.hasOwnProperty(p) && (d[p] = b[p]); }; return _extendStatics(d, b); }; return function(d, b) { _extendStatics(d, b); function __() { this.constructor = d; } d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })()); var spine; (function(spine) { var Animation = (function() { function Animation(name, timelines, duration) { if (null == name) throw new Error("name cannot be null."); if (null == timelines) throw new Error("timelines cannot be null."); this.name = name; this.timelines = timelines; this.timelineIds = []; for (var i = 0; i < timelines.length; i++) this.timelineIds[timelines[i].getPropertyId()] = true; this.duration = duration; } Animation.prototype.hasTimeline = function(id) { return true == this.timelineIds[id]; }; Animation.prototype.apply = function(skeleton, lastTime, time, loop, events, alpha, blend, direction) { if (null == skeleton) throw new Error("skeleton cannot be null."); if (loop && 0 != this.duration) { time %= this.duration; lastTime > 0 && (lastTime %= this.duration); } var timelines = this.timelines; for (var i = 0, n = timelines.length; i < n; i++) timelines[i].apply(skeleton, lastTime, time, events, alpha, blend, direction); }; Animation.binarySearch = function(values, target, step) { void 0 === step && (step = 1); var low = 0; var high = values.length / step - 2; if (0 == high) return step; var current = high >>> 1; while (true) { values[(current + 1) * step] <= target ? low = current + 1 : high = current; if (low == high) return (low + 1) * step; current = low + high >>> 1; } }; Animation.linearSearch = function(values, target, step) { for (var i = 0, last = values.length - step; i <= last; i += step) if (values[i] > target) return i; return -1; }; return Animation; })(); spine.Animation = Animation; var MixBlend; (function(MixBlend) { MixBlend[MixBlend["setup"] = 0] = "setup"; MixBlend[MixBlend["first"] = 1] = "first"; MixBlend[MixBlend["replace"] = 2] = "replace"; MixBlend[MixBlend["add"] = 3] = "add"; })(MixBlend = spine.MixBlend || (spine.MixBlend = {})); var MixDirection; (function(MixDirection) { MixDirection[MixDirection["mixIn"] = 0] = "mixIn"; MixDirection[MixDirection["mixOut"] = 1] = "mixOut"; })(MixDirection = spine.MixDirection || (spine.MixDirection = {})); var TimelineType; (function(TimelineType) { TimelineType[TimelineType["rotate"] = 0] = "rotate"; TimelineType[TimelineType["translate"] = 1] = "translate"; TimelineType[TimelineType["scale"] = 2] = "scale"; TimelineType[TimelineType["shear"] = 3] = "shear"; TimelineType[TimelineType["attachment"] = 4] = "attachment"; TimelineType[TimelineType["color"] = 5] = "color"; TimelineType[TimelineType["deform"] = 6] = "deform"; TimelineType[TimelineType["event"] = 7] = "event"; TimelineType[TimelineType["drawOrder"] = 8] = "drawOrder"; TimelineType[TimelineType["ikConstraint"] = 9] = "ikConstraint"; TimelineType[TimelineType["transformConstraint"] = 10] = "transformConstraint"; TimelineType[TimelineType["pathConstraintPosition"] = 11] = "pathConstraintPosition"; TimelineType[TimelineType["pathConstraintSpacing"] = 12] = "pathConstraintSpacing"; TimelineType[TimelineType["pathConstraintMix"] = 13] = "pathConstraintMix"; TimelineType[TimelineType["twoColor"] = 14] = "twoColor"; })(TimelineType = spine.TimelineType || (spine.TimelineType = {})); var CurveTimeline = (function() { function CurveTimeline(frameCount) { if (frameCount <= 0) throw new Error("frameCount must be > 0: " + frameCount); this.curves = spine.Utils.newFloatArray((frameCount - 1) * CurveTimeline.BEZIER_SIZE); } CurveTimeline.prototype.getFrameCount = function() { return this.curves.length / CurveTimeline.BEZIER_SIZE + 1; }; CurveTimeline.prototype.setLinear = function(frameIndex) { this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.LINEAR; }; CurveTimeline.prototype.setStepped = function(frameIndex) { this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.STEPPED; }; CurveTimeline.prototype.getCurveType = function(frameIndex) { var index = frameIndex * CurveTimeline.BEZIER_SIZE; if (index == this.curves.length) return CurveTimeline.LINEAR; var type = this.curves[index]; if (type == CurveTimeline.LINEAR) return CurveTimeline.LINEAR; if (type == CurveTimeline.STEPPED) return CurveTimeline.STEPPED; return CurveTimeline.BEZIER; }; CurveTimeline.prototype.setCurve = function(frameIndex, cx1, cy1, cx2, cy2) { var tmpx = .03 * (2 * -cx1 + cx2), tmpy = .03 * (2 * -cy1 + cy2); var dddfx = .006 * (3 * (cx1 - cx2) + 1), dddfy = .006 * (3 * (cy1 - cy2) + 1); var ddfx = 2 * tmpx + dddfx, ddfy = 2 * tmpy + dddfy; var dfx = .3 * cx1 + tmpx + .16666667 * dddfx, dfy = .3 * cy1 + tmpy + .16666667 * dddfy; var i = frameIndex * CurveTimeline.BEZIER_SIZE; var curves = this.curves; curves[i++] = CurveTimeline.BEZIER; var x = dfx, y = dfy; for (var n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) { curves[i] = x; curves[i + 1] = y; dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; x += dfx; y += dfy; } }; CurveTimeline.prototype.getCurvePercent = function(frameIndex, percent) { percent = spine.MathUtils.clamp(percent, 0, 1); var curves = this.curves; var i = frameIndex * CurveTimeline.BEZIER_SIZE; var type = curves[i]; if (type == CurveTimeline.LINEAR) return percent; if (type == CurveTimeline.STEPPED) return 0; i++; var x = 0; for (var start = i, n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) { x = curves[i]; if (x >= percent) { var prevX = void 0, prevY = void 0; if (i == start) { prevX = 0; prevY = 0; } else { prevX = curves[i - 2]; prevY = curves[i - 1]; } return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); } } var y = curves[i - 1]; return y + (1 - y) * (percent - x) / (1 - x); }; CurveTimeline.LINEAR = 0; CurveTimeline.STEPPED = 1; CurveTimeline.BEZIER = 2; CurveTimeline.BEZIER_SIZE = 19; return CurveTimeline; })(); spine.CurveTimeline = CurveTimeline; var RotateTimeline = (function(_super) { __extends(RotateTimeline, _super); function RotateTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount << 1); return _this; } RotateTimeline.prototype.getPropertyId = function() { return (TimelineType.rotate << 24) + this.boneIndex; }; RotateTimeline.prototype.setFrame = function(frameIndex, time, degrees) { frameIndex <<= 1; this.frames[frameIndex] = time; this.frames[frameIndex + RotateTimeline.ROTATION] = degrees; }; RotateTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, blend, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (!bone.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: bone.rotation = bone.data.rotation; return; case MixBlend.first: var r_1 = bone.data.rotation - bone.rotation; bone.rotation += (r_1 - 360 * (16384 - (16384.499999999996 - r_1 / 360 | 0))) * alpha; } return; } if (time >= frames[frames.length - RotateTimeline.ENTRIES]) { var r_2 = frames[frames.length + RotateTimeline.PREV_ROTATION]; switch (blend) { case MixBlend.setup: bone.rotation = bone.data.rotation + r_2 * alpha; break; case MixBlend.first: case MixBlend.replace: r_2 += bone.data.rotation - bone.rotation; r_2 -= 360 * (16384 - (16384.499999999996 - r_2 / 360 | 0)); case MixBlend.add: bone.rotation += r_2 * alpha; } return; } var frame = Animation.binarySearch(frames, time, RotateTimeline.ENTRIES); var prevRotation = frames[frame + RotateTimeline.PREV_ROTATION]; var frameTime = frames[frame]; var percent = this.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime)); var r = frames[frame + RotateTimeline.ROTATION] - prevRotation; r = prevRotation + (r - 360 * (16384 - (16384.499999999996 - r / 360 | 0))) * percent; switch (blend) { case MixBlend.setup: bone.rotation = bone.data.rotation + (r - 360 * (16384 - (16384.499999999996 - r / 360 | 0))) * alpha; break; case MixBlend.first: case MixBlend.replace: r += bone.data.rotation - bone.rotation; case MixBlend.add: bone.rotation += (r - 360 * (16384 - (16384.499999999996 - r / 360 | 0))) * alpha; } }; RotateTimeline.ENTRIES = 2; RotateTimeline.PREV_TIME = -2; RotateTimeline.PREV_ROTATION = -1; RotateTimeline.ROTATION = 1; return RotateTimeline; })(CurveTimeline); spine.RotateTimeline = RotateTimeline; var TranslateTimeline = (function(_super) { __extends(TranslateTimeline, _super); function TranslateTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount * TranslateTimeline.ENTRIES); return _this; } TranslateTimeline.prototype.getPropertyId = function() { return (TimelineType.translate << 24) + this.boneIndex; }; TranslateTimeline.prototype.setFrame = function(frameIndex, time, x, y) { frameIndex *= TranslateTimeline.ENTRIES; this.frames[frameIndex] = time; this.frames[frameIndex + TranslateTimeline.X] = x; this.frames[frameIndex + TranslateTimeline.Y] = y; }; TranslateTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, blend, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (!bone.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: bone.x = bone.data.x; bone.y = bone.data.y; return; case MixBlend.first: bone.x += (bone.data.x - bone.x) * alpha; bone.y += (bone.data.y - bone.y) * alpha; } return; } var x = 0, y = 0; if (time >= frames[frames.length - TranslateTimeline.ENTRIES]) { x = frames[frames.length + TranslateTimeline.PREV_X]; y = frames[frames.length + TranslateTimeline.PREV_Y]; } else { var frame = Animation.binarySearch(frames, time, TranslateTimeline.ENTRIES); x = frames[frame + TranslateTimeline.PREV_X]; y = frames[frame + TranslateTimeline.PREV_Y]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / TranslateTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TranslateTimeline.PREV_TIME] - frameTime)); x += (frames[frame + TranslateTimeline.X] - x) * percent; y += (frames[frame + TranslateTimeline.Y] - y) * percent; } switch (blend) { case MixBlend.setup: bone.x = bone.data.x + x * alpha; bone.y = bone.data.y + y * alpha; break; case MixBlend.first: case MixBlend.replace: bone.x += (bone.data.x + x - bone.x) * alpha; bone.y += (bone.data.y + y - bone.y) * alpha; break; case MixBlend.add: bone.x += x * alpha; bone.y += y * alpha; } }; TranslateTimeline.ENTRIES = 3; TranslateTimeline.PREV_TIME = -3; TranslateTimeline.PREV_X = -2; TranslateTimeline.PREV_Y = -1; TranslateTimeline.X = 1; TranslateTimeline.Y = 2; return TranslateTimeline; })(CurveTimeline); spine.TranslateTimeline = TranslateTimeline; var ScaleTimeline = (function(_super) { __extends(ScaleTimeline, _super); function ScaleTimeline(frameCount) { return _super.call(this, frameCount) || this; } ScaleTimeline.prototype.getPropertyId = function() { return (TimelineType.scale << 24) + this.boneIndex; }; ScaleTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, blend, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (!bone.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: bone.scaleX = bone.data.scaleX; bone.scaleY = bone.data.scaleY; return; case MixBlend.first: bone.scaleX += (bone.data.scaleX - bone.scaleX) * alpha; bone.scaleY += (bone.data.scaleY - bone.scaleY) * alpha; } return; } var x = 0, y = 0; if (time >= frames[frames.length - ScaleTimeline.ENTRIES]) { x = frames[frames.length + ScaleTimeline.PREV_X] * bone.data.scaleX; y = frames[frames.length + ScaleTimeline.PREV_Y] * bone.data.scaleY; } else { var frame = Animation.binarySearch(frames, time, ScaleTimeline.ENTRIES); x = frames[frame + ScaleTimeline.PREV_X]; y = frames[frame + ScaleTimeline.PREV_Y]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / ScaleTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ScaleTimeline.PREV_TIME] - frameTime)); x = (x + (frames[frame + ScaleTimeline.X] - x) * percent) * bone.data.scaleX; y = (y + (frames[frame + ScaleTimeline.Y] - y) * percent) * bone.data.scaleY; } if (1 == alpha) if (blend == MixBlend.add) { bone.scaleX += x - bone.data.scaleX; bone.scaleY += y - bone.data.scaleY; } else { bone.scaleX = x; bone.scaleY = y; } else { var bx = 0, by = 0; if (direction == MixDirection.mixOut) switch (blend) { case MixBlend.setup: bx = bone.data.scaleX; by = bone.data.scaleY; bone.scaleX = bx + (Math.abs(x) * spine.MathUtils.signum(bx) - bx) * alpha; bone.scaleY = by + (Math.abs(y) * spine.MathUtils.signum(by) - by) * alpha; break; case MixBlend.first: case MixBlend.replace: bx = bone.scaleX; by = bone.scaleY; bone.scaleX = bx + (Math.abs(x) * spine.MathUtils.signum(bx) - bx) * alpha; bone.scaleY = by + (Math.abs(y) * spine.MathUtils.signum(by) - by) * alpha; break; case MixBlend.add: bx = bone.scaleX; by = bone.scaleY; bone.scaleX = bx + (Math.abs(x) * spine.MathUtils.signum(bx) - bone.data.scaleX) * alpha; bone.scaleY = by + (Math.abs(y) * spine.MathUtils.signum(by) - bone.data.scaleY) * alpha; } else switch (blend) { case MixBlend.setup: bx = Math.abs(bone.data.scaleX) * spine.MathUtils.signum(x); by = Math.abs(bone.data.scaleY) * spine.MathUtils.signum(y); bone.scaleX = bx + (x - bx) * alpha; bone.scaleY = by + (y - by) * alpha; break; case MixBlend.first: case MixBlend.replace: bx = Math.abs(bone.scaleX) * spine.MathUtils.signum(x); by = Math.abs(bone.scaleY) * spine.MathUtils.signum(y); bone.scaleX = bx + (x - bx) * alpha; bone.scaleY = by + (y - by) * alpha; break; case MixBlend.add: bx = spine.MathUtils.signum(x); by = spine.MathUtils.signum(y); bone.scaleX = Math.abs(bone.scaleX) * bx + (x - Math.abs(bone.data.scaleX) * bx) * alpha; bone.scaleY = Math.abs(bone.scaleY) * by + (y - Math.abs(bone.data.scaleY) * by) * alpha; } } }; return ScaleTimeline; })(TranslateTimeline); spine.ScaleTimeline = ScaleTimeline; var ShearTimeline = (function(_super) { __extends(ShearTimeline, _super); function ShearTimeline(frameCount) { return _super.call(this, frameCount) || this; } ShearTimeline.prototype.getPropertyId = function() { return (TimelineType.shear << 24) + this.boneIndex; }; ShearTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, blend, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (!bone.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: bone.shearX = bone.data.shearX; bone.shearY = bone.data.shearY; return; case MixBlend.first: bone.shearX += (bone.data.shearX - bone.shearX) * alpha; bone.shearY += (bone.data.shearY - bone.shearY) * alpha; } return; } var x = 0, y = 0; if (time >= frames[frames.length - ShearTimeline.ENTRIES]) { x = frames[frames.length + ShearTimeline.PREV_X]; y = frames[frames.length + ShearTimeline.PREV_Y]; } else { var frame = Animation.binarySearch(frames, time, ShearTimeline.ENTRIES); x = frames[frame + ShearTimeline.PREV_X]; y = frames[frame + ShearTimeline.PREV_Y]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / ShearTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ShearTimeline.PREV_TIME] - frameTime)); x += (frames[frame + ShearTimeline.X] - x) * percent; y += (frames[frame + ShearTimeline.Y] - y) * percent; } switch (blend) { case MixBlend.setup: bone.shearX = bone.data.shearX + x * alpha; bone.shearY = bone.data.shearY + y * alpha; break; case MixBlend.first: case MixBlend.replace: bone.shearX += (bone.data.shearX + x - bone.shearX) * alpha; bone.shearY += (bone.data.shearY + y - bone.shearY) * alpha; break; case MixBlend.add: bone.shearX += x * alpha; bone.shearY += y * alpha; } }; return ShearTimeline; })(TranslateTimeline); spine.ShearTimeline = ShearTimeline; var ColorTimeline = (function(_super) { __extends(ColorTimeline, _super); function ColorTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount * ColorTimeline.ENTRIES); return _this; } ColorTimeline.prototype.getPropertyId = function() { return (TimelineType.color << 24) + this.slotIndex; }; ColorTimeline.prototype.setFrame = function(frameIndex, time, r, g, b, a) { frameIndex *= ColorTimeline.ENTRIES; this.frames[frameIndex] = time; this.frames[frameIndex + ColorTimeline.R] = r; this.frames[frameIndex + ColorTimeline.G] = g; this.frames[frameIndex + ColorTimeline.B] = b; this.frames[frameIndex + ColorTimeline.A] = a; }; ColorTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, blend, direction) { var slot = skeleton.slots[this.slotIndex]; if (!slot.bone.active) return; var frames = this.frames; if (time < frames[0]) { switch (blend) { case MixBlend.setup: slot.color.setFromColor(slot.data.color); return; case MixBlend.first: var color = slot.color, setup = slot.data.color; color.add((setup.r - color.r) * alpha, (setup.g - color.g) * alpha, (setup.b - color.b) * alpha, (setup.a - color.a) * alpha); } return; } var r = 0, g = 0, b = 0, a = 0; if (time >= frames[frames.length - ColorTimeline.ENTRIES]) { var i = frames.length; r = frames[i + ColorTimeline.PREV_R]; g = frames[i + ColorTimeline.PREV_G]; b = frames[i + ColorTimeline.PREV_B]; a = frames[i + ColorTimeline.PREV_A]; } else { var frame = Animation.binarySearch(frames, time, ColorTimeline.ENTRIES); r = frames[frame + ColorTimeline.PREV_R]; g = frames[frame + ColorTimeline.PREV_G]; b = frames[frame + ColorTimeline.PREV_B]; a = frames[frame + ColorTimeline.PREV_A]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / ColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ColorTimeline.PREV_TIME] - frameTime)); r += (frames[frame + ColorTimeline.R] - r) * percent; g += (frames[frame + ColorTimeline.G] - g) * percent; b += (frames[frame + ColorTimeline.B] - b) * percent; a += (frames[frame + ColorTimeline.A] - a) * percent; } if (1 == alpha) slot.color.set(r, g, b, a); else { var color = slot.color; blend == MixBlend.setup && color.setFromColor(slot.data.color); color.add((r - color.r) * alpha, (g - color.g) * alpha, (b - color.b) * alpha, (a - color.a) * alpha); } }; ColorTimeline.ENTRIES = 5; ColorTimeline.PREV_TIME = -5; ColorTimeline.PREV_R = -4; ColorTimeline.PREV_G = -3; ColorTimeline.PREV_B = -2; ColorTimeline.PREV_A = -1; ColorTimeline.R = 1; ColorTimeline.G = 2; ColorTimeline.B = 3; ColorTimeline.A = 4; return ColorTimeline; })(CurveTimeline); spine.ColorTimeline = ColorTimeline; var TwoColorTimeline = (function(_super) { __extends(TwoColorTimeline, _super); function TwoColorTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount * TwoColorTimeline.ENTRIES); return _this; } TwoColorTimeline.prototype.getPropertyId = function() { return (TimelineType.twoColor << 24) + this.slotIndex; }; TwoColorTimeline.prototype.setFrame = function(frameIndex, time, r, g, b, a, r2, g2, b2) { frameIndex *= TwoColorTimeline.ENTRIES; this.frames[frameIndex] = time; this.frames[frameIndex + TwoColorTimeline.R] = r; this.frames[frameIndex + TwoColorTimeline.G] = g; this.frames[frameIndex + TwoColorTimeline.B] = b; this.frames[frameIndex + TwoColorTimeline.A] = a; this.frames[frameIndex + TwoColorTimeline.R2] = r2; this.frames[frameIndex + TwoColorTimeline.G2] = g2; this.frames[frameIndex + TwoColorTimeline.B2] = b2; }; TwoColorTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, blend, direction) { var slot = skeleton.slots[this.slotIndex]; if (!slot.bone.active) return; var frames = this.frames; if (time < frames[0]) { switch (blend) { case MixBlend.setup: slot.color.setFromColor(slot.data.color); slot.darkColor.setFromColor(slot.data.darkColor); return; case MixBlend.first: var light = slot.color, dark = slot.darkColor, setupLight = slot.data.color, setupDark = slot.data.darkColor; light.add((setupLight.r - light.r) * alpha, (setupLight.g - light.g) * alpha, (setupLight.b - light.b) * alpha, (setupLight.a - light.a) * alpha); dark.add((setupDark.r - dark.r) * alpha, (setupDark.g - dark.g) * alpha, (setupDark.b - dark.b) * alpha, 0); } return; } var r = 0, g = 0, b = 0, a = 0, r2 = 0, g2 = 0, b2 = 0; if (time >= frames[frames.length - TwoColorTimeline.ENTRIES]) { var i = frames.length; r = frames[i + TwoColorTimeline.PREV_R]; g = frames[i + TwoColorTimeline.PREV_G]; b = frames[i + TwoColorTimeline.PREV_B]; a = frames[i + TwoColorTimeline.PREV_A]; r2 = frames[i + TwoColorTimeline.PREV_R2]; g2 = frames[i + TwoColorTimeline.PREV_G2]; b2 = frames[i + TwoColorTimeline.PREV_B2]; } else { var frame = Animation.binarySearch(frames, time, TwoColorTimeline.ENTRIES); r = frames[frame + TwoColorTimeline.PREV_R]; g = frames[frame + TwoColorTimeline.PREV_G]; b = frames[frame + TwoColorTimeline.PREV_B]; a = frames[frame + TwoColorTimeline.PREV_A]; r2 = frames[frame + TwoColorTimeline.PREV_R2]; g2 = frames[frame + TwoColorTimeline.PREV_G2]; b2 = frames[frame + TwoColorTimeline.PREV_B2]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / TwoColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TwoColorTimeline.PREV_TIME] - frameTime)); r += (frames[frame + TwoColorTimeline.R] - r) * percent; g += (frames[frame + TwoColorTimeline.G] - g) * percent; b += (frames[frame + TwoColorTimeline.B] - b) * percent; a += (frames[frame + TwoColorTimeline.A] - a) * percent; r2 += (frames[frame + TwoColorTimeline.R2] - r2) * percent; g2 += (frames[frame + TwoColorTimeline.G2] - g2) * percent; b2 += (frames[frame + TwoColorTimeline.B2] - b2) * percent; } if (1 == alpha) { slot.color.set(r, g, b, a); slot.darkColor.set(r2, g2, b2, 1); } else { var light = slot.color, dark = slot.darkColor; if (blend == MixBlend.setup) { light.setFromColor(slot.data.color); dark.setFromColor(slot.data.darkColor); } light.add((r - light.r) * alpha, (g - light.g) * alpha, (b - light.b) * alpha, (a - light.a) * alpha); dark.add((r2 - dark.r) * alpha, (g2 - dark.g) * alpha, (b2 - dark.b) * alpha, 0); } }; TwoColorTimeline.ENTRIES = 8; TwoColorTimeline.PREV_TIME = -8; TwoColorTimeline.PREV_R = -7; TwoColorTimeline.PREV_G = -6; TwoColorTimeline.PREV_B = -5; TwoColorTimeline.PREV_A = -4; TwoColorTimeline.PREV_R2 = -3; TwoColorTimeline.PREV_G2 = -2; TwoColorTimeline.PREV_B2 = -1; TwoColorTimeline.R = 1; TwoColorTimeline.G = 2; TwoColorTimeline.B = 3; TwoColorTimeline.A = 4; TwoColorTimeline.R2 = 5; TwoColorTimeline.G2 = 6; TwoColorTimeline.B2 = 7; return TwoColorTimeline; })(CurveTimeline); spine.TwoColorTimeline = TwoColorTimeline; var AttachmentTimeline = (function() { function AttachmentTimeline(frameCount) { this.frames = spine.Utils.newFloatArray(frameCount); this.attachmentNames = new Array(frameCount); } AttachmentTimeline.prototype.getPropertyId = function() { return (TimelineType.attachment << 24) + this.slotIndex; }; AttachmentTimeline.prototype.getFrameCount = function() { return this.frames.length; }; AttachmentTimeline.prototype.setFrame = function(frameIndex, time, attachmentName) { this.frames[frameIndex] = time; this.attachmentNames[frameIndex] = attachmentName; }; AttachmentTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, blend, direction) { var slot = skeleton.slots[this.slotIndex]; if (!slot.bone.active) return; if (direction == MixDirection.mixOut && blend == MixBlend.setup) { var attachmentName_1 = slot.data.attachmentName; slot.setAttachment(null == attachmentName_1 ? null : skeleton.getAttachment(this.slotIndex, attachmentName_1)); return; } var frames = this.frames; if (time < frames[0]) { if (blend == MixBlend.setup || blend == MixBlend.first) { var attachmentName_2 = slot.data.attachmentName; slot.setAttachment(null == attachmentName_2 ? null : skeleton.getAttachment(this.slotIndex, attachmentName_2)); } return; } var frameIndex = 0; frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : Animation.binarySearch(frames, time, 1) - 1; var attachmentName = this.attachmentNames[frameIndex]; skeleton.slots[this.slotIndex].setAttachment(null == attachmentName ? null : skeleton.getAttachment(this.slotIndex, attachmentName)); }; return AttachmentTimeline; })(); spine.AttachmentTimeline = AttachmentTimeline; var zeros = null; var DeformTimeline = (function(_super) { __extends(DeformTimeline, _super); function DeformTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount); _this.frameVertices = new Array(frameCount); null == zeros && (zeros = spine.Utils.newFloatArray(64)); return _this; } DeformTimeline.prototype.getPropertyId = function() { return (TimelineType.deform << 27) + +this.attachment.id + this.slotIndex; }; DeformTimeline.prototype.setFrame = function(frameIndex, time, vertices) { this.frames[frameIndex] = time; this.frameVertices[frameIndex] = vertices; }; DeformTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { var slot = skeleton.slots[this.slotIndex]; if (!slot.bone.active) return; var slotAttachment = slot.getAttachment(); if (!(slotAttachment instanceof spine.VertexAttachment) || !(slotAttachment.deformAttachment == this.attachment)) return; var deformArray = slot.deform; 0 == deformArray.length && (blend = MixBlend.setup); var frameVertices = this.frameVertices; var vertexCount = frameVertices[0].length; var frames = this.frames; if (time < frames[0]) { var vertexAttachment = slotAttachment; switch (blend) { case MixBlend.setup: deformArray.length = 0; return; case MixBlend.first: if (1 == alpha) { deformArray.length = 0; break; } var deform_1 = spine.Utils.setArraySize(deformArray, vertexCount); if (null == vertexAttachment.bones) { var setupVertices = vertexAttachment.vertices; for (var i = 0; i < vertexCount; i++) deform_1[i] += (setupVertices[i] - deform_1[i]) * alpha; } else { alpha = 1 - alpha; for (var i = 0; i < vertexCount; i++) deform_1[i] *= alpha; } } return; } var deform = spine.Utils.setArraySize(deformArray, vertexCount); if (time >= frames[frames.length - 1]) { var lastVertices = frameVertices[frames.length - 1]; if (1 == alpha) if (blend == MixBlend.add) { var vertexAttachment = slotAttachment; if (null == vertexAttachment.bones) { var setupVertices = vertexAttachment.vertices; for (var i_1 = 0; i_1 < vertexCount; i_1++) deform[i_1] += lastVertices[i_1] - setupVertices[i_1]; } else for (var i_2 = 0; i_2 < vertexCount; i_2++) deform[i_2] += lastVertices[i_2]; } else spine.Utils.arrayCopy(lastVertices, 0, deform, 0, vertexCount); else switch (blend) { case MixBlend.setup: var vertexAttachment_1 = slotAttachment; if (null == vertexAttachment_1.bones) { var setupVertices = vertexAttachment_1.vertices; for (var i_3 = 0; i_3 < vertexCount; i_3++) { var setup = setupVertices[i_3]; deform[i_3] = setup + (lastVertices[i_3] - setup) * alpha; } } else for (var i_4 = 0; i_4 < vertexCount; i_4++) deform[i_4] = lastVertices[i_4] * alpha; break; case MixBlend.first: case MixBlend.replace: for (var i_5 = 0; i_5 < vertexCount; i_5++) deform[i_5] += (lastVertices[i_5] - deform[i_5]) * alpha; case MixBlend.add: var vertexAttachment = slotAttachment; if (null == vertexAttachment.bones) { var setupVertices = vertexAttachment.vertices; for (var i_6 = 0; i_6 < vertexCount; i_6++) deform[i_6] += (lastVertices[i_6] - setupVertices[i_6]) * alpha; } else for (var i_7 = 0; i_7 < vertexCount; i_7++) deform[i_7] += lastVertices[i_7] * alpha; } return; } var frame = Animation.binarySearch(frames, time); var prevVertices = frameVertices[frame - 1]; var nextVertices = frameVertices[frame]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime)); if (1 == alpha) if (blend == MixBlend.add) { var vertexAttachment = slotAttachment; if (null == vertexAttachment.bones) { var setupVertices = vertexAttachment.vertices; for (var i_8 = 0; i_8 < vertexCount; i_8++) { var prev = prevVertices[i_8]; deform[i_8] += prev + (nextVertices[i_8] - prev) * percent - setupVertices[i_8]; } } else for (var i_9 = 0; i_9 < vertexCount; i_9++) { var prev = prevVertices[i_9]; deform[i_9] += prev + (nextVertices[i_9] - prev) * percent; } } else for (var i_10 = 0; i_10 < vertexCount; i_10++) { var prev = prevVertices[i_10]; deform[i_10] = prev + (nextVertices[i_10] - prev) * percent; } else switch (blend) { case MixBlend.setup: var vertexAttachment_2 = slotAttachment; if (null == vertexAttachment_2.bones) { var setupVertices = vertexAttachment_2.vertices; for (var i_11 = 0; i_11 < vertexCount; i_11++) { var prev = prevVertices[i_11], setup = setupVertices[i_11]; deform[i_11] = setup + (prev + (nextVertices[i_11] - prev) * percent - setup) * alpha; } } else for (var i_12 = 0; i_12 < vertexCount; i_12++) { var prev = prevVertices[i_12]; deform[i_12] = (prev + (nextVertices[i_12] - prev) * percent) * alpha; } break; case MixBlend.first: case MixBlend.replace: for (var i_13 = 0; i_13 < vertexCount; i_13++) { var prev = prevVertices[i_13]; deform[i_13] += (prev + (nextVertices[i_13] - prev) * percent - deform[i_13]) * alpha; } break; case MixBlend.add: var vertexAttachment = slotAttachment; if (null == vertexAttachment.bones) { var setupVertices = vertexAttachment.vertices; for (var i_14 = 0; i_14 < vertexCount; i_14++) { var prev = prevVertices[i_14]; deform[i_14] += (prev + (nextVertices[i_14] - prev) * percent - setupVertices[i_14]) * alpha; } } else for (var i_15 = 0; i_15 < vertexCount; i_15++) { var prev = prevVertices[i_15]; deform[i_15] += (prev + (nextVertices[i_15] - prev) * percent) * alpha; } } }; return DeformTimeline; })(CurveTimeline); spine.DeformTimeline = DeformTimeline; var EventTimeline = (function() { function EventTimeline(frameCount) { this.frames = spine.Utils.newFloatArray(frameCount); this.events = new Array(frameCount); } EventTimeline.prototype.getPropertyId = function() { return TimelineType.event << 24; }; EventTimeline.prototype.getFrameCount = function() { return this.frames.length; }; EventTimeline.prototype.setFrame = function(frameIndex, event) { this.frames[frameIndex] = event.time; this.events[frameIndex] = event; }; EventTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { if (null == firedEvents) return; var frames = this.frames; var frameCount = this.frames.length; if (lastTime > time) { this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha, blend, direction); lastTime = -1; } else if (lastTime >= frames[frameCount - 1]) return; if (time < frames[0]) return; var frame = 0; if (lastTime < frames[0]) frame = 0; else { frame = Animation.binarySearch(frames, lastTime); var frameTime = frames[frame]; while (frame > 0) { if (frames[frame - 1] != frameTime) break; frame--; } } for (;frame < frameCount && time >= frames[frame]; frame++) firedEvents.push(this.events[frame]); }; return EventTimeline; })(); spine.EventTimeline = EventTimeline; var DrawOrderTimeline = (function() { function DrawOrderTimeline(frameCount) { this.frames = spine.Utils.newFloatArray(frameCount); this.drawOrders = new Array(frameCount); } DrawOrderTimeline.prototype.getPropertyId = function() { return TimelineType.drawOrder << 24; }; DrawOrderTimeline.prototype.getFrameCount = function() { return this.frames.length; }; DrawOrderTimeline.prototype.setFrame = function(frameIndex, time, drawOrder) { this.frames[frameIndex] = time; this.drawOrders[frameIndex] = drawOrder; }; DrawOrderTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { var drawOrder = skeleton.drawOrder; var slots = skeleton.slots; if (direction == MixDirection.mixOut && blend == MixBlend.setup) { spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length); return; } var frames = this.frames; if (time < frames[0]) { blend != MixBlend.setup && blend != MixBlend.first || spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length); return; } var frame = 0; frame = time >= frames[frames.length - 1] ? frames.length - 1 : Animation.binarySearch(frames, time) - 1; var drawOrderToSetupIndex = this.drawOrders[frame]; if (null == drawOrderToSetupIndex) spine.Utils.arrayCopy(slots, 0, drawOrder, 0, slots.length); else for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++) drawOrder[i] = slots[drawOrderToSetupIndex[i]]; }; return DrawOrderTimeline; })(); spine.DrawOrderTimeline = DrawOrderTimeline; var IkConstraintTimeline = (function(_super) { __extends(IkConstraintTimeline, _super); function IkConstraintTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount * IkConstraintTimeline.ENTRIES); return _this; } IkConstraintTimeline.prototype.getPropertyId = function() { return (TimelineType.ikConstraint << 24) + this.ikConstraintIndex; }; IkConstraintTimeline.prototype.setFrame = function(frameIndex, time, mix, softness, bendDirection, compress, stretch) { frameIndex *= IkConstraintTimeline.ENTRIES; this.frames[frameIndex] = time; this.frames[frameIndex + IkConstraintTimeline.MIX] = mix; this.frames[frameIndex + IkConstraintTimeline.SOFTNESS] = softness; this.frames[frameIndex + IkConstraintTimeline.BEND_DIRECTION] = bendDirection; this.frames[frameIndex + IkConstraintTimeline.COMPRESS] = compress ? 1 : 0; this.frames[frameIndex + IkConstraintTimeline.STRETCH] = stretch ? 1 : 0; }; IkConstraintTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { var frames = this.frames; var constraint = skeleton.ikConstraints[this.ikConstraintIndex]; if (!constraint.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: constraint.mix = constraint.data.mix; constraint.softness = constraint.data.softness; constraint.bendDirection = constraint.data.bendDirection; constraint.compress = constraint.data.compress; constraint.stretch = constraint.data.stretch; return; case MixBlend.first: constraint.mix += (constraint.data.mix - constraint.mix) * alpha; constraint.softness += (constraint.data.softness - constraint.softness) * alpha; constraint.bendDirection = constraint.data.bendDirection; constraint.compress = constraint.data.compress; constraint.stretch = constraint.data.stretch; } return; } if (time >= frames[frames.length - IkConstraintTimeline.ENTRIES]) { if (blend == MixBlend.setup) { constraint.mix = constraint.data.mix + (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.data.mix) * alpha; constraint.softness = constraint.data.softness + (frames[frames.length + IkConstraintTimeline.PREV_SOFTNESS] - constraint.data.softness) * alpha; if (direction == MixDirection.mixOut) { constraint.bendDirection = constraint.data.bendDirection; constraint.compress = constraint.data.compress; constraint.stretch = constraint.data.stretch; } else { constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION]; constraint.compress = 0 != frames[frames.length + IkConstraintTimeline.PREV_COMPRESS]; constraint.stretch = 0 != frames[frames.length + IkConstraintTimeline.PREV_STRETCH]; } } else { constraint.mix += (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.mix) * alpha; constraint.softness += (frames[frames.length + IkConstraintTimeline.PREV_SOFTNESS] - constraint.softness) * alpha; if (direction == MixDirection.mixIn) { constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION]; constraint.compress = 0 != frames[frames.length + IkConstraintTimeline.PREV_COMPRESS]; constraint.stretch = 0 != frames[frames.length + IkConstraintTimeline.PREV_STRETCH]; } } return; } var frame = Animation.binarySearch(frames, time, IkConstraintTimeline.ENTRIES); var mix = frames[frame + IkConstraintTimeline.PREV_MIX]; var softness = frames[frame + IkConstraintTimeline.PREV_SOFTNESS]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / IkConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + IkConstraintTimeline.PREV_TIME] - frameTime)); if (blend == MixBlend.setup) { constraint.mix = constraint.data.mix + (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.data.mix) * alpha; constraint.softness = constraint.data.softness + (softness + (frames[frame + IkConstraintTimeline.SOFTNESS] - softness) * percent - constraint.data.softness) * alpha; if (direction == MixDirection.mixOut) { constraint.bendDirection = constraint.data.bendDirection; constraint.compress = constraint.data.compress; constraint.stretch = constraint.data.stretch; } else { constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]; constraint.compress = 0 != frames[frame + IkConstraintTimeline.PREV_COMPRESS]; constraint.stretch = 0 != frames[frame + IkConstraintTimeline.PREV_STRETCH]; } } else { constraint.mix += (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.mix) * alpha; constraint.softness += (softness + (frames[frame + IkConstraintTimeline.SOFTNESS] - softness) * percent - constraint.softness) * alpha; if (direction == MixDirection.mixIn) { constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]; constraint.compress = 0 != frames[frame + IkConstraintTimeline.PREV_COMPRESS]; constraint.stretch = 0 != frames[frame + IkConstraintTimeline.PREV_STRETCH]; } } }; IkConstraintTimeline.ENTRIES = 6; IkConstraintTimeline.PREV_TIME = -6; IkConstraintTimeline.PREV_MIX = -5; IkConstraintTimeline.PREV_SOFTNESS = -4; IkConstraintTimeline.PREV_BEND_DIRECTION = -3; IkConstraintTimeline.PREV_COMPRESS = -2; IkConstraintTimeline.PREV_STRETCH = -1; IkConstraintTimeline.MIX = 1; IkConstraintTimeline.SOFTNESS = 2; IkConstraintTimeline.BEND_DIRECTION = 3; IkConstraintTimeline.COMPRESS = 4; IkConstraintTimeline.STRETCH = 5; return IkConstraintTimeline; })(CurveTimeline); spine.IkConstraintTimeline = IkConstraintTimeline; var TransformConstraintTimeline = (function(_super) { __extends(TransformConstraintTimeline, _super); function TransformConstraintTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount * TransformConstraintTimeline.ENTRIES); return _this; } TransformConstraintTimeline.prototype.getPropertyId = function() { return (TimelineType.transformConstraint << 24) + this.transformConstraintIndex; }; TransformConstraintTimeline.prototype.setFrame = function(frameIndex, time, rotateMix, translateMix, scaleMix, shearMix) { frameIndex *= TransformConstraintTimeline.ENTRIES; this.frames[frameIndex] = time; this.frames[frameIndex + TransformConstraintTimeline.ROTATE] = rotateMix; this.frames[frameIndex + TransformConstraintTimeline.TRANSLATE] = translateMix; this.frames[frameIndex + TransformConstraintTimeline.SCALE] = scaleMix; this.frames[frameIndex + TransformConstraintTimeline.SHEAR] = shearMix; }; TransformConstraintTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { var frames = this.frames; var constraint = skeleton.transformConstraints[this.transformConstraintIndex]; if (!constraint.active) return; if (time < frames[0]) { var data = constraint.data; switch (blend) { case MixBlend.setup: constraint.rotateMix = data.rotateMix; constraint.translateMix = data.translateMix; constraint.scaleMix = data.scaleMix; constraint.shearMix = data.shearMix; return; case MixBlend.first: constraint.rotateMix += (data.rotateMix - constraint.rotateMix) * alpha; constraint.translateMix += (data.translateMix - constraint.translateMix) * alpha; constraint.scaleMix += (data.scaleMix - constraint.scaleMix) * alpha; constraint.shearMix += (data.shearMix - constraint.shearMix) * alpha; } return; } var rotate = 0, translate = 0, scale = 0, shear = 0; if (time >= frames[frames.length - TransformConstraintTimeline.ENTRIES]) { var i = frames.length; rotate = frames[i + TransformConstraintTimeline.PREV_ROTATE]; translate = frames[i + TransformConstraintTimeline.PREV_TRANSLATE]; scale = frames[i + TransformConstraintTimeline.PREV_SCALE]; shear = frames[i + TransformConstraintTimeline.PREV_SHEAR]; } else { var frame = Animation.binarySearch(frames, time, TransformConstraintTimeline.ENTRIES); rotate = frames[frame + TransformConstraintTimeline.PREV_ROTATE]; translate = frames[frame + TransformConstraintTimeline.PREV_TRANSLATE]; scale = frames[frame + TransformConstraintTimeline.PREV_SCALE]; shear = frames[frame + TransformConstraintTimeline.PREV_SHEAR]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / TransformConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TransformConstraintTimeline.PREV_TIME] - frameTime)); rotate += (frames[frame + TransformConstraintTimeline.ROTATE] - rotate) * percent; translate += (frames[frame + TransformConstraintTimeline.TRANSLATE] - translate) * percent; scale += (frames[frame + TransformConstraintTimeline.SCALE] - scale) * percent; shear += (frames[frame + TransformConstraintTimeline.SHEAR] - shear) * percent; } if (blend == MixBlend.setup) { var data = constraint.data; constraint.rotateMix = data.rotateMix + (rotate - data.rotateMix) * alpha; constraint.translateMix = data.translateMix + (translate - data.translateMix) * alpha; constraint.scaleMix = data.scaleMix + (scale - data.scaleMix) * alpha; constraint.shearMix = data.shearMix + (shear - data.shearMix) * alpha; } else { constraint.rotateMix += (rotate - constraint.rotateMix) * alpha; constraint.translateMix += (translate - constraint.translateMix) * alpha; constraint.scaleMix += (scale - constraint.scaleMix) * alpha; constraint.shearMix += (shear - constraint.shearMix) * alpha; } }; TransformConstraintTimeline.ENTRIES = 5; TransformConstraintTimeline.PREV_TIME = -5; TransformConstraintTimeline.PREV_ROTATE = -4; TransformConstraintTimeline.PREV_TRANSLATE = -3; TransformConstraintTimeline.PREV_SCALE = -2; TransformConstraintTimeline.PREV_SHEAR = -1; TransformConstraintTimeline.ROTATE = 1; TransformConstraintTimeline.TRANSLATE = 2; TransformConstraintTimeline.SCALE = 3; TransformConstraintTimeline.SHEAR = 4; return TransformConstraintTimeline; })(CurveTimeline); spine.TransformConstraintTimeline = TransformConstraintTimeline; var PathConstraintPositionTimeline = (function(_super) { __extends(PathConstraintPositionTimeline, _super); function PathConstraintPositionTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintPositionTimeline.ENTRIES); return _this; } PathConstraintPositionTimeline.prototype.getPropertyId = function() { return (TimelineType.pathConstraintPosition << 24) + this.pathConstraintIndex; }; PathConstraintPositionTimeline.prototype.setFrame = function(frameIndex, time, value) { frameIndex *= PathConstraintPositionTimeline.ENTRIES; this.frames[frameIndex] = time; this.frames[frameIndex + PathConstraintPositionTimeline.VALUE] = value; }; PathConstraintPositionTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { var frames = this.frames; var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; if (!constraint.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: constraint.position = constraint.data.position; return; case MixBlend.first: constraint.position += (constraint.data.position - constraint.position) * alpha; } return; } var position = 0; if (time >= frames[frames.length - PathConstraintPositionTimeline.ENTRIES]) position = frames[frames.length + PathConstraintPositionTimeline.PREV_VALUE]; else { var frame = Animation.binarySearch(frames, time, PathConstraintPositionTimeline.ENTRIES); position = frames[frame + PathConstraintPositionTimeline.PREV_VALUE]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / PathConstraintPositionTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintPositionTimeline.PREV_TIME] - frameTime)); position += (frames[frame + PathConstraintPositionTimeline.VALUE] - position) * percent; } blend == MixBlend.setup ? constraint.position = constraint.data.position + (position - constraint.data.position) * alpha : constraint.position += (position - constraint.position) * alpha; }; PathConstraintPositionTimeline.ENTRIES = 2; PathConstraintPositionTimeline.PREV_TIME = -2; PathConstraintPositionTimeline.PREV_VALUE = -1; PathConstraintPositionTimeline.VALUE = 1; return PathConstraintPositionTimeline; })(CurveTimeline); spine.PathConstraintPositionTimeline = PathConstraintPositionTimeline; var PathConstraintSpacingTimeline = (function(_super) { __extends(PathConstraintSpacingTimeline, _super); function PathConstraintSpacingTimeline(frameCount) { return _super.call(this, frameCount) || this; } PathConstraintSpacingTimeline.prototype.getPropertyId = function() { return (TimelineType.pathConstraintSpacing << 24) + this.pathConstraintIndex; }; PathConstraintSpacingTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { var frames = this.frames; var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; if (!constraint.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: constraint.spacing = constraint.data.spacing; return; case MixBlend.first: constraint.spacing += (constraint.data.spacing - constraint.spacing) * alpha; } return; } var spacing = 0; if (time >= frames[frames.length - PathConstraintSpacingTimeline.ENTRIES]) spacing = frames[frames.length + PathConstraintSpacingTimeline.PREV_VALUE]; else { var frame = Animation.binarySearch(frames, time, PathConstraintSpacingTimeline.ENTRIES); spacing = frames[frame + PathConstraintSpacingTimeline.PREV_VALUE]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / PathConstraintSpacingTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintSpacingTimeline.PREV_TIME] - frameTime)); spacing += (frames[frame + PathConstraintSpacingTimeline.VALUE] - spacing) * percent; } blend == MixBlend.setup ? constraint.spacing = constraint.data.spacing + (spacing - constraint.data.spacing) * alpha : constraint.spacing += (spacing - constraint.spacing) * alpha; }; return PathConstraintSpacingTimeline; })(PathConstraintPositionTimeline); spine.PathConstraintSpacingTimeline = PathConstraintSpacingTimeline; var PathConstraintMixTimeline = (function(_super) { __extends(PathConstraintMixTimeline, _super); function PathConstraintMixTimeline(frameCount) { var _this = _super.call(this, frameCount) || this; _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintMixTimeline.ENTRIES); return _this; } PathConstraintMixTimeline.prototype.getPropertyId = function() { return (TimelineType.pathConstraintMix << 24) + this.pathConstraintIndex; }; PathConstraintMixTimeline.prototype.setFrame = function(frameIndex, time, rotateMix, translateMix) { frameIndex *= PathConstraintMixTimeline.ENTRIES; this.frames[frameIndex] = time; this.frames[frameIndex + PathConstraintMixTimeline.ROTATE] = rotateMix; this.frames[frameIndex + PathConstraintMixTimeline.TRANSLATE] = translateMix; }; PathConstraintMixTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, blend, direction) { var frames = this.frames; var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; if (!constraint.active) return; if (time < frames[0]) { switch (blend) { case MixBlend.setup: constraint.rotateMix = constraint.data.rotateMix; constraint.translateMix = constraint.data.translateMix; return; case MixBlend.first: constraint.rotateMix += (constraint.data.rotateMix - constraint.rotateMix) * alpha; constraint.translateMix += (constraint.data.translateMix - constraint.translateMix) * alpha; } return; } var rotate = 0, translate = 0; if (time >= frames[frames.length - PathConstraintMixTimeline.ENTRIES]) { rotate = frames[frames.length + PathConstraintMixTimeline.PREV_ROTATE]; translate = frames[frames.length + PathConstraintMixTimeline.PREV_TRANSLATE]; } else { var frame = Animation.binarySearch(frames, time, PathConstraintMixTimeline.ENTRIES); rotate = frames[frame + PathConstraintMixTimeline.PREV_ROTATE]; translate = frames[frame + PathConstraintMixTimeline.PREV_TRANSLATE]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / PathConstraintMixTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintMixTimeline.PREV_TIME] - frameTime)); rotate += (frames[frame + PathConstraintMixTimeline.ROTATE] - rotate) * percent; translate += (frames[frame + PathConstraintMixTimeline.TRANSLATE] - translate) * percent; } if (blend == MixBlend.setup) { constraint.rotateMix = constraint.data.rotateMix + (rotate - constraint.data.rotateMix) * alpha; constraint.translateMix = constraint.data.translateMix + (translate - constraint.data.translateMix) * alpha; } else { constraint.rotateMix += (rotate - constraint.rotateMix) * alpha; constraint.translateMix += (translate - constraint.translateMix) * alpha; } }; PathConstraintMixTimeline.ENTRIES = 3; PathConstraintMixTimeline.PREV_TIME = -3; PathConstraintMixTimeline.PREV_ROTATE = -2; PathConstraintMixTimeline.PREV_TRANSLATE = -1; PathConstraintMixTimeline.ROTATE = 1; PathConstraintMixTimeline.TRANSLATE = 2; return PathConstraintMixTimeline; })(CurveTimeline); spine.PathConstraintMixTimeline = PathConstraintMixTimeline; })(spine || (spine = {})); var spine; (function(spine) { var AnimationState = (function() { function AnimationState(data) { this.tracks = new Array(); this.timeScale = 1; this.events = new Array(); this.listeners = new Array(); this.queue = new EventQueue(this); this.propertyIDs = new spine.IntSet(); this.animationsChanged = false; this.trackEntryPool = new spine.Pool(function() { return new TrackEntry(); }); this.data = data; } AnimationState.prototype.update = function(delta) { delta *= this.timeScale; var tracks = this.tracks; for (var i = 0, n = tracks.length; i < n; i++) { var current = tracks[i]; if (null == current) continue; current.animationLast = current.nextAnimationLast; current.trackLast = current.nextTrackLast; var currentDelta = delta * current.timeScale; if (current.delay > 0) { current.delay -= currentDelta; if (current.delay > 0) continue; currentDelta = -current.delay; current.delay = 0; } var next = current.next; if (null != next) { var nextTime = current.trackLast - next.delay; if (nextTime >= 0) { next.delay = 0; next.trackTime += 0 == current.timeScale ? 0 : (nextTime / current.timeScale + delta) * next.timeScale; current.trackTime += currentDelta; this.setCurrent(i, next, true); while (null != next.mixingFrom) { next.mixTime += delta; next = next.mixingFrom; } continue; } } else if (current.trackLast >= current.trackEnd && null == current.mixingFrom) { tracks[i] = null; this.queue.end(current); this.disposeNext(current); continue; } if (null != current.mixingFrom && this.updateMixingFrom(current, delta)) { var from = current.mixingFrom; current.mixingFrom = null; null != from && (from.mixingTo = null); while (null != from) { this.queue.end(from); from = from.mixingFrom; } } current.trackTime += currentDelta; } this.queue.drain(); }; AnimationState.prototype.updateMixingFrom = function(to, delta) { var from = to.mixingFrom; if (null == from) return true; var finished = this.updateMixingFrom(from, delta); from.animationLast = from.nextAnimationLast; from.trackLast = from.nextTrackLast; if (to.mixTime > 0 && to.mixTime >= to.mixDuration) { if (0 == from.totalAlpha || 0 == to.mixDuration) { to.mixingFrom = from.mixingFrom; null != from.mixingFrom && (from.mixingFrom.mixingTo = to); to.interruptAlpha = from.interruptAlpha; this.queue.end(from); } return finished; } from.trackTime += delta * from.timeScale; to.mixTime += delta; return false; }; AnimationState.prototype.apply = function(skeleton) { if (null == skeleton) throw new Error("skeleton cannot be null."); this.animationsChanged && this._animationsChanged(); var events = this.events; var tracks = this.tracks; var applied = false; for (var i = 0, n = tracks.length; i < n; i++) { var current = tracks[i]; if (null == current || current.delay > 0) continue; applied = true; var blend = 0 == i ? spine.MixBlend.first : current.mixBlend; var mix = current.alpha; null != current.mixingFrom ? mix *= this.applyMixingFrom(current, skeleton, blend) : current.trackTime >= current.trackEnd && null == current.next && (mix = 0); var animationLast = current.animationLast, animationTime = current.getAnimationTime(); var timelineCount = current.animation.timelines.length; var timelines = current.animation.timelines; if (0 == i && 1 == mix || blend == spine.MixBlend.add) for (var ii = 0; ii < timelineCount; ii++) { spine.Utils.webkit602BugfixHelper(mix, blend); timelines[ii].apply(skeleton, animationLast, animationTime, events, mix, blend, spine.MixDirection.mixIn); } else { var timelineMode = current.timelineMode; var firstFrame = 0 == current.timelinesRotation.length; firstFrame && spine.Utils.setArraySize(current.timelinesRotation, timelineCount << 1, null); var timelinesRotation = current.timelinesRotation; for (var ii = 0; ii < timelineCount; ii++) { var timeline = timelines[ii]; var timelineBlend = (timelineMode[ii] & AnimationState.NOT_LAST - 1) == AnimationState.SUBSEQUENT ? blend : spine.MixBlend.setup; if (timeline instanceof spine.RotateTimeline) this.applyRotateTimeline(timeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation, ii << 1, firstFrame); else { spine.Utils.webkit602BugfixHelper(mix, blend); timeline.apply(skeleton, animationLast, animationTime, events, mix, timelineBlend, spine.MixDirection.mixIn); } } } this.queueEvents(current, animationTime); events.length = 0; current.nextAnimationLast = animationTime; current.nextTrackLast = current.trackTime; } this.queue.drain(); return applied; }; AnimationState.prototype.applyMixingFrom = function(to, skeleton, blend) { var from = to.mixingFrom; null != from.mixingFrom && this.applyMixingFrom(from, skeleton, blend); var mix = 0; if (0 == to.mixDuration) { mix = 1; blend == spine.MixBlend.first && (blend = spine.MixBlend.setup); } else { mix = to.mixTime / to.mixDuration; mix > 1 && (mix = 1); blend != spine.MixBlend.first && (blend = from.mixBlend); } var events = mix < from.eventThreshold ? this.events : null; var attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold; var animationLast = from.animationLast, animationTime = from.getAnimationTime(); var timelineCount = from.animation.timelines.length; var timelines = from.animation.timelines; var alphaHold = from.alpha * to.interruptAlpha, alphaMix = alphaHold * (1 - mix); if (blend == spine.MixBlend.add) for (var i = 0; i < timelineCount; i++) timelines[i].apply(skeleton, animationLast, animationTime, events, alphaMix, blend, spine.MixDirection.mixOut); else { var timelineMode = from.timelineMode; var timelineHoldMix = from.timelineHoldMix; var firstFrame = 0 == from.timelinesRotation.length; firstFrame && spine.Utils.setArraySize(from.timelinesRotation, timelineCount << 1, null); var timelinesRotation = from.timelinesRotation; from.totalAlpha = 0; for (var i = 0; i < timelineCount; i++) { var timeline = timelines[i]; var direction = spine.MixDirection.mixOut; var timelineBlend = void 0; var alpha = 0; switch (timelineMode[i] & AnimationState.NOT_LAST - 1) { case AnimationState.SUBSEQUENT: timelineBlend = blend; if (!attachments && timeline instanceof spine.AttachmentTimeline) { if ((timelineMode[i] & AnimationState.NOT_LAST) == AnimationState.NOT_LAST) continue; timelineBlend = spine.MixBlend.setup; } if (!drawOrder && timeline instanceof spine.DrawOrderTimeline) continue; alpha = alphaMix; break; case AnimationState.FIRST: timelineBlend = spine.MixBlend.setup; alpha = alphaMix; break; case AnimationState.HOLD: timelineBlend = spine.MixBlend.setup; alpha = alphaHold; break; default: timelineBlend = spine.MixBlend.setup; var holdMix = timelineHoldMix[i]; alpha = alphaHold * Math.max(0, 1 - holdMix.mixTime / holdMix.mixDuration); } from.totalAlpha += alpha; if (timeline instanceof spine.RotateTimeline) this.applyRotateTimeline(timeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation, i << 1, firstFrame); else { spine.Utils.webkit602BugfixHelper(alpha, blend); timelineBlend == spine.MixBlend.setup && (timeline instanceof spine.AttachmentTimeline ? (attachments || (timelineMode[i] & AnimationState.NOT_LAST) == AnimationState.NOT_LAST) && (direction = spine.MixDirection.mixIn) : timeline instanceof spine.DrawOrderTimeline && drawOrder && (direction = spine.MixDirection.mixIn)); timeline.apply(skeleton, animationLast, animationTime, events, alpha, timelineBlend, direction); } } } to.mixDuration > 0 && this.queueEvents(from, animationTime); this.events.length = 0; from.nextAnimationLast = animationTime; from.nextTrackLast = from.trackTime; return mix; }; AnimationState.prototype.applyRotateTimeline = function(timeline, skeleton, time, alpha, blend, timelinesRotation, i, firstFrame) { firstFrame && (timelinesRotation[i] = 0); if (1 == alpha) { timeline.apply(skeleton, 0, time, null, 1, blend, spine.MixDirection.mixIn); return; } var rotateTimeline = timeline; var frames = rotateTimeline.frames; var bone = skeleton.bones[rotateTimeline.boneIndex]; if (!bone.active) return; var r1 = 0, r2 = 0; if (time < frames[0]) switch (blend) { case spine.MixBlend.setup: bone.rotation = bone.data.rotation; default: return; case spine.MixBlend.first: r1 = bone.rotation; r2 = bone.data.rotation; } else { r1 = blend == spine.MixBlend.setup ? bone.data.rotation : bone.rotation; if (time >= frames[frames.length - spine.RotateTimeline.ENTRIES]) r2 = bone.data.rotation + frames[frames.length + spine.RotateTimeline.PREV_ROTATION]; else { var frame = spine.Animation.binarySearch(frames, time, spine.RotateTimeline.ENTRIES); var prevRotation = frames[frame + spine.RotateTimeline.PREV_ROTATION]; var frameTime = frames[frame]; var percent = rotateTimeline.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + spine.RotateTimeline.PREV_TIME] - frameTime)); r2 = frames[frame + spine.RotateTimeline.ROTATION] - prevRotation; r2 -= 360 * (16384 - (16384.499999999996 - r2 / 360 | 0)); r2 = prevRotation + r2 * percent + bone.data.rotation; r2 -= 360 * (16384 - (16384.499999999996 - r2 / 360 | 0)); } } var total = 0, diff = r2 - r1; diff -= 360 * (16384 - (16384.499999999996 - diff / 360 | 0)); if (0 == diff) total = timelinesRotation[i]; else { var lastTotal = 0, lastDiff = 0; if (firstFrame) { lastTotal = 0; lastDiff = diff; } else { lastTotal = timelinesRotation[i]; lastDiff = timelinesRotation[i + 1]; } var current = diff > 0, dir = lastTotal >= 0; if (spine.MathUtils.signum(lastDiff) != spine.MathUtils.signum(diff) && Math.abs(lastDiff) <= 90) { Math.abs(lastTotal) > 180 && (lastTotal += 360 * spine.MathUtils.signum(lastTotal)); dir = current; } total = diff + lastTotal - lastTotal % 360; dir != current && (total += 360 * spine.MathUtils.signum(lastTotal)); timelinesRotation[i] = total; } timelinesRotation[i + 1] = diff; r1 += total * alpha; bone.rotation = r1 - 360 * (16384 - (16384.499999999996 - r1 / 360 | 0)); }; AnimationState.prototype.queueEvents = function(entry, animationTime) { var animationStart = entry.animationStart, animationEnd = entry.animationEnd; var duration = animationEnd - animationStart; var trackLastWrapped = entry.trackLast % duration; var events = this.events; var i = 0, n = events.length; for (;i < n; i++) { var event_1 = events[i]; if (event_1.time < trackLastWrapped) break; if (event_1.time > animationEnd) continue; this.queue.event(entry, event_1); } var complete = false; complete = entry.loop ? 0 == duration || trackLastWrapped > entry.trackTime % duration : animationTime >= animationEnd && entry.animationLast < animationEnd; complete && this.queue.complete(entry); for (;i < n; i++) { var event_2 = events[i]; if (event_2.time < animationStart) continue; this.queue.event(entry, events[i]); } }; AnimationState.prototype.clearTracks = function() { var oldDrainDisabled = this.queue.drainDisabled; this.queue.drainDisabled = true; for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); this.tracks.length = 0; this.queue.drainDisabled = oldDrainDisabled; this.queue.drain(); }; AnimationState.prototype.clearTrack = function(trackIndex) { if (trackIndex >= this.tracks.length) return; var current = this.tracks[trackIndex]; if (null == current) return; this.queue.end(current); this.disposeNext(current); var entry = current; while (true) { var from = entry.mixingFrom; if (null == from) break; this.queue.end(from); entry.mixingFrom = null; entry.mixingTo = null; entry = from; } this.tracks[current.trackIndex] = null; this.queue.drain(); }; AnimationState.prototype.setCurrent = function(index, current, interrupt) { var from = this.expandToIndex(index); this.tracks[index] = current; if (null != from) { interrupt && this.queue.interrupt(from); current.mixingFrom = from; from.mixingTo = current; current.mixTime = 0; null != from.mixingFrom && from.mixDuration > 0 && (current.interruptAlpha *= Math.min(1, from.mixTime / from.mixDuration)); from.timelinesRotation.length = 0; } this.queue.start(current); }; AnimationState.prototype.setAnimation = function(trackIndex, animationName, loop) { var animation = this.data.skeletonData.findAnimation(animationName); if (null == animation) throw new Error("Animation not found: " + animationName); return this.setAnimationWith(trackIndex, animation, loop); }; AnimationState.prototype.setAnimationWith = function(trackIndex, animation, loop) { if (null == animation) throw new Error("animation cannot be null."); var interrupt = true; var current = this.expandToIndex(trackIndex); if (null != current) if (-1 == current.nextTrackLast) { this.tracks[trackIndex] = current.mixingFrom; this.queue.interrupt(current); this.queue.end(current); this.disposeNext(current); current = current.mixingFrom; interrupt = false; } else this.disposeNext(current); var entry = this.trackEntry(trackIndex, animation, loop, current); this.setCurrent(trackIndex, entry, interrupt); this.queue.drain(); return entry; }; AnimationState.prototype.addAnimation = function(trackIndex, animationName, loop, delay) { var animation = this.data.skeletonData.findAnimation(animationName); if (null == animation) throw new Error("Animation not found: " + animationName); return this.addAnimationWith(trackIndex, animation, loop, delay); }; AnimationState.prototype.addAnimationWith = function(trackIndex, animation, loop, delay) { if (null == animation) throw new Error("animation cannot be null."); var last = this.expandToIndex(trackIndex); if (null != last) while (null != last.next) last = last.next; var entry = this.trackEntry(trackIndex, animation, loop, last); if (null == last) { this.setCurrent(trackIndex, entry, true); this.queue.drain(); } else { last.next = entry; if (delay <= 0) { var duration = last.animationEnd - last.animationStart; if (0 != duration) { last.loop ? delay += duration * (1 + (last.trackTime / duration | 0)) : delay += Math.max(duration, last.trackTime); delay -= this.data.getMix(last.animation, animation); } else delay = last.trackTime; } } entry.delay = delay; return entry; }; AnimationState.prototype.setEmptyAnimation = function(trackIndex, mixDuration) { var entry = this.setAnimationWith(trackIndex, AnimationState.emptyAnimation, false); entry.mixDuration = mixDuration; entry.trackEnd = mixDuration; return entry; }; AnimationState.prototype.addEmptyAnimation = function(trackIndex, mixDuration, delay) { delay <= 0 && (delay -= mixDuration); var entry = this.addAnimationWith(trackIndex, AnimationState.emptyAnimation, false, delay); entry.mixDuration = mixDuration; entry.trackEnd = mixDuration; return entry; }; AnimationState.prototype.setEmptyAnimations = function(mixDuration) { var oldDrainDisabled = this.queue.drainDisabled; this.queue.drainDisabled = true; for (var i = 0, n = this.tracks.length; i < n; i++) { var current = this.tracks[i]; null != current && this.setEmptyAnimation(current.trackIndex, mixDuration); } this.queue.drainDisabled = oldDrainDisabled; this.queue.drain(); }; AnimationState.prototype.expandToIndex = function(index) { if (index < this.tracks.length) return this.tracks[index]; spine.Utils.ensureArrayCapacity(this.tracks, index + 1, null); this.tracks.length = index + 1; return null; }; AnimationState.prototype.trackEntry = function(trackIndex, animation, loop, last) { var entry = this.trackEntryPool.obtain(); entry.trackIndex = trackIndex; entry.animation = animation; entry.loop = loop; entry.holdPrevious = false; entry.eventThreshold = 0; entry.attachmentThreshold = 0; entry.drawOrderThreshold = 0; entry.animationStart = 0; entry.animationEnd = animation.duration; entry.animationLast = -1; entry.nextAnimationLast = -1; entry.delay = 0; entry.trackTime = 0; entry.trackLast = -1; entry.nextTrackLast = -1; entry.trackEnd = Number.MAX_VALUE; entry.timeScale = 1; entry.alpha = 1; entry.interruptAlpha = 1; entry.mixTime = 0; entry.mixDuration = null == last ? 0 : this.data.getMix(last.animation, animation); return entry; }; AnimationState.prototype.disposeNext = function(entry) { var next = entry.next; while (null != next) { this.queue.dispose(next); next = next.next; } entry.next = null; }; AnimationState.prototype._animationsChanged = function() { this.animationsChanged = false; this.propertyIDs.clear(); for (var i = 0, n = this.tracks.length; i < n; i++) { var entry = this.tracks[i]; if (null == entry) continue; while (null != entry.mixingFrom) entry = entry.mixingFrom; do { null != entry.mixingFrom && entry.mixBlend == spine.MixBlend.add || this.computeHold(entry); entry = entry.mixingTo; } while (null != entry); } this.propertyIDs.clear(); for (var i = this.tracks.length - 1; i >= 0; i--) { var entry = this.tracks[i]; while (null != entry) { this.computeNotLast(entry); entry = entry.mixingFrom; } } }; AnimationState.prototype.computeHold = function(entry) { var to = entry.mixingTo; var timelines = entry.animation.timelines; var timelinesCount = entry.animation.timelines.length; var timelineMode = spine.Utils.setArraySize(entry.timelineMode, timelinesCount); entry.timelineHoldMix.length = 0; var timelineDipMix = spine.Utils.setArraySize(entry.timelineHoldMix, timelinesCount); var propertyIDs = this.propertyIDs; if (null != to && to.holdPrevious) { for (var i = 0; i < timelinesCount; i++) { propertyIDs.add(timelines[i].getPropertyId()); timelineMode[i] = AnimationState.HOLD; } return; } outer: for (var i = 0; i < timelinesCount; i++) { var timeline = timelines[i]; var id = timeline.getPropertyId(); if (propertyIDs.add(id)) if (null == to || timeline instanceof spine.AttachmentTimeline || timeline instanceof spine.DrawOrderTimeline || timeline instanceof spine.EventTimeline || !to.animation.hasTimeline(id)) timelineMode[i] = AnimationState.FIRST; else { for (var next = to.mixingTo; null != next; next = next.mixingTo) { if (next.animation.hasTimeline(id)) continue; if (entry.mixDuration > 0) { timelineMode[i] = AnimationState.HOLD_MIX; timelineDipMix[i] = next; continue outer; } break; } timelineMode[i] = AnimationState.HOLD; } else timelineMode[i] = AnimationState.SUBSEQUENT; } }; AnimationState.prototype.computeNotLast = function(entry) { var timelines = entry.animation.timelines; var timelinesCount = entry.animation.timelines.length; var timelineMode = entry.timelineMode; var propertyIDs = this.propertyIDs; for (var i = 0; i < timelinesCount; i++) if (timelines[i] instanceof spine.AttachmentTimeline) { var timeline = timelines[i]; propertyIDs.add(timeline.slotIndex) || (timelineMode[i] |= AnimationState.NOT_LAST); } }; AnimationState.prototype.getCurrent = function(trackIndex) { if (trackIndex >= this.tracks.length) return null; return this.tracks[trackIndex]; }; AnimationState.prototype.addListener = function(listener) { if (null == listener) throw new Error("listener cannot be null."); this.listeners.push(listener); }; AnimationState.prototype.removeListener = function(listener) { var index = this.listeners.indexOf(listener); index >= 0 && this.listeners.splice(index, 1); }; AnimationState.prototype.clearListeners = function() { this.listeners.length = 0; }; AnimationState.prototype.clearListenerNotifications = function() { this.queue.clear(); }; AnimationState.emptyAnimation = new spine.Animation("", [], 0); AnimationState.SUBSEQUENT = 0; AnimationState.FIRST = 1; AnimationState.HOLD = 2; AnimationState.HOLD_MIX = 3; AnimationState.NOT_LAST = 4; return AnimationState; })(); spine.AnimationState = AnimationState; var TrackEntry = (function() { function TrackEntry() { this.mixBlend = spine.MixBlend.replace; this.timelineMode = new Array(); this.timelineHoldMix = new Array(); this.timelinesRotation = new Array(); } TrackEntry.prototype.reset = function() { this.next = null; this.mixingFrom = null; this.mixingTo = null; this.animation = null; this.listener = null; this.timelineMode.length = 0; this.timelineHoldMix.length = 0; this.timelinesRotation.length = 0; }; TrackEntry.prototype.getAnimationTime = function() { if (this.loop) { var duration = this.animationEnd - this.animationStart; if (0 == duration) return this.animationStart; return this.trackTime % duration + this.animationStart; } return Math.min(this.trackTime + this.animationStart, this.animationEnd); }; TrackEntry.prototype.setAnimationLast = function(animationLast) { this.animationLast = animationLast; this.nextAnimationLast = animationLast; }; TrackEntry.prototype.isComplete = function() { return this.trackTime >= this.animationEnd - this.animationStart; }; TrackEntry.prototype.resetRotationDirections = function() { this.timelinesRotation.length = 0; }; return TrackEntry; })(); spine.TrackEntry = TrackEntry; var EventQueue = (function() { function EventQueue(animState) { this.objects = []; this.drainDisabled = false; this.animState = animState; } EventQueue.prototype.start = function(entry) { this.objects.push(EventType.start); this.objects.push(entry); this.animState.animationsChanged = true; }; EventQueue.prototype.interrupt = function(entry) { this.objects.push(EventType.interrupt); this.objects.push(entry); }; EventQueue.prototype.end = function(entry) { this.objects.push(EventType.end); this.objects.push(entry); this.animState.animationsChanged = true; }; EventQueue.prototype.dispose = function(entry) { this.objects.push(EventType.dispose); this.objects.push(entry); }; EventQueue.prototype.complete = function(entry) { this.objects.push(EventType.complete); this.objects.push(entry); }; EventQueue.prototype.event = function(entry, event) { this.objects.push(EventType.event); this.objects.push(entry); this.objects.push(event); }; EventQueue.prototype.drain = function() { if (this.drainDisabled) return; this.drainDisabled = true; var objects = this.objects; var listeners = this.animState.listeners; for (var i = 0; i < objects.length; i += 2) { var type = objects[i]; var entry = objects[i + 1]; switch (type) { case EventType.start: null != entry.listener && entry.listener.start && entry.listener.start(entry); for (var ii = 0; ii < listeners.length; ii++) listeners[ii].start && listeners[ii].start(entry); break; case EventType.interrupt: null != entry.listener && entry.listener.interrupt && entry.listener.interrupt(entry); for (var ii = 0; ii < listeners.length; ii++) listeners[ii].interrupt && listeners[ii].interrupt(entry); break; case EventType.end: null != entry.listener && entry.listener.end && entry.listener.end(entry); for (var ii = 0; ii < listeners.length; ii++) listeners[ii].end && listeners[ii].end(entry); case EventType.dispose: null != entry.listener && entry.listener.dispose && entry.listener.dispose(entry); for (var ii = 0; ii < listeners.length; ii++) listeners[ii].dispose && listeners[ii].dispose(entry); this.animState.trackEntryPool.free(entry); break; case EventType.complete: null != entry.listener && entry.listener.complete && entry.listener.complete(entry); for (var ii = 0; ii < listeners.length; ii++) listeners[ii].complete && listeners[ii].complete(entry); break; case EventType.event: var event_3 = objects[2 + i++]; null != entry.listener && entry.listener.event && entry.listener.event(entry, event_3); for (var ii = 0; ii < listeners.length; ii++) listeners[ii].event && listeners[ii].event(entry, event_3); } } this.clear(); this.drainDisabled = false; }; EventQueue.prototype.clear = function() { this.objects.length = 0; }; return EventQueue; })(); spine.EventQueue = EventQueue; var EventType; (function(EventType) { EventType[EventType["start"] = 0] = "start"; EventType[EventType["interrupt"] = 1] = "interrupt"; EventType[EventType["end"] = 2] = "end"; EventType[EventType["dispose"] = 3] = "dispose"; EventType[EventType["complete"] = 4] = "complete"; EventType[EventType["event"] = 5] = "event"; })(EventType = spine.EventType || (spine.EventType = {})); var AnimationStateAdapter = (function() { function AnimationStateAdapter() {} AnimationStateAdapter.prototype.start = function(entry) {}; AnimationStateAdapter.prototype.interrupt = function(entry) {}; AnimationStateAdapter.prototype.end = function(entry) {}; AnimationStateAdapter.prototype.dispose = function(entry) {}; AnimationStateAdapter.prototype.complete = function(entry) {}; AnimationStateAdapter.prototype.event = function(entry, event) {}; return AnimationStateAdapter; })(); spine.AnimationStateAdapter = AnimationStateAdapter; })(spine || (spine = {})); var spine; (function(spine) { var AnimationStateData = (function() { function AnimationStateData(skeletonData) { this.animationToMixTime = {}; this.defaultMix = 0; if (null == skeletonData) throw new Error("skeletonData cannot be null."); this.skeletonData = skeletonData; } AnimationStateData.prototype.setMix = function(fromName, toName, duration) { var from = this.skeletonData.findAnimation(fromName); if (null == from) throw new Error("Animation not found: " + fromName); var to = this.skeletonData.findAnimation(toName); if (null == to) throw new Error("Animation not found: " + toName); this.setMixWith(from, to, duration); }; AnimationStateData.prototype.setMixWith = function(from, to, duration) { if (null == from) throw new Error("from cannot be null."); if (null == to) throw new Error("to cannot be null."); var key = from.name + "." + to.name; this.animationToMixTime[key] = duration; }; AnimationStateData.prototype.getMix = function(from, to) { var key = from.name + "." + to.name; var value = this.animationToMixTime[key]; return void 0 === value ? this.defaultMix : value; }; return AnimationStateData; })(); spine.AnimationStateData = AnimationStateData; })(spine || (spine = {})); var spine; (function(spine) { var AssetManager = (function() { function AssetManager(textureLoader, pathPrefix) { void 0 === pathPrefix && (pathPrefix = ""); this.assets = {}; this.errors = {}; this.toLoad = 0; this.loaded = 0; this.textureLoader = textureLoader; this.pathPrefix = pathPrefix; } AssetManager.downloadText = function(url, success, error) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = function() { 200 == request.status ? success(request.responseText) : error(request.status, request.responseText); }; request.onerror = function() { error(request.status, request.responseText); }; request.send(); }; AssetManager.downloadBinary = function(url, success, error) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; request.onload = function() { 200 == request.status ? success(new Uint8Array(request.response)) : error(request.status, request.responseText); }; request.onerror = function() { error(request.status, request.responseText); }; request.send(); }; AssetManager.prototype.loadBinary = function(path, success, error) { var _this = this; void 0 === success && (success = null); void 0 === error && (error = null); path = this.pathPrefix + path; this.toLoad++; AssetManager.downloadBinary(path, (function(data) { _this.assets[path] = data; success && success(path, data); _this.toLoad--; _this.loaded++; }), (function(state, responseText) { _this.errors[path] = "Couldn't load binary " + path + ": status " + status + ", " + responseText; error && error(path, "Couldn't load binary " + path + ": status " + status + ", " + responseText); _this.toLoad--; _this.loaded++; })); }; AssetManager.prototype.loadText = function(path, success, error) { var _this = this; void 0 === success && (success = null); void 0 === error && (error = null); path = this.pathPrefix + path; this.toLoad++; AssetManager.downloadText(path, (function(data) { _this.assets[path] = data; success && success(path, data); _this.toLoad--; _this.loaded++; }), (function(state, responseText) { _this.errors[path] = "Couldn't load text " + path + ": status " + status + ", " + responseText; error && error(path, "Couldn't load text " + path + ": status " + status + ", " + responseText); _this.toLoad--; _this.loaded++; })); }; AssetManager.prototype.loadTexture = function(path, success, error) { var _this = this; void 0 === success && (success = null); void 0 === error && (error = null); path = this.pathPrefix + path; this.toLoad++; var img = new Image(); img.crossOrigin = "anonymous"; img.onload = function(ev) { var texture = _this.textureLoader(img); _this.assets[path] = texture; _this.toLoad--; _this.loaded++; success && success(path, img); }; img.onerror = function(ev) { _this.errors[path] = "Couldn't load image " + path; _this.toLoad--; _this.loaded++; error && error(path, "Couldn't load image " + path); }; img.src = path; }; AssetManager.prototype.loadTextureData = function(path, data, success, error) { var _this = this; void 0 === success && (success = null); void 0 === error && (error = null); path = this.pathPrefix + path; this.toLoad++; var img = new Image(); img.onload = function(ev) { var texture = _this.textureLoader(img); _this.assets[path] = texture; _this.toLoad--; _this.loaded++; success && success(path, img); }; img.onerror = function(ev) { _this.errors[path] = "Couldn't load image " + path; _this.toLoad--; _this.loaded++; error && error(path, "Couldn't load image " + path); }; img.src = data; }; AssetManager.prototype.loadTextureAtlas = function(path, success, error) { var _this = this; void 0 === success && (success = null); void 0 === error && (error = null); var parent = path.lastIndexOf("/") >= 0 ? path.substring(0, path.lastIndexOf("/")) : ""; path = this.pathPrefix + path; this.toLoad++; AssetManager.downloadText(path, (function(atlasData) { var pagesLoaded = { count: 0 }; var atlasPages = new Array(); try { var atlas = new spine.TextureAtlas(atlasData, function(path) { atlasPages.push(parent + "/" + path); var image = document.createElement("img"); image.width = 16; image.height = 16; return new spine.FakeTexture(image); }); } catch (e) { var ex = e; _this.errors[path] = "Couldn't load texture atlas " + path + ": " + ex.message; error && error(path, "Couldn't load texture atlas " + path + ": " + ex.message); _this.toLoad--; _this.loaded++; return; } var _loop_1 = function _loop_1(atlasPage) { var pageLoadError = false; _this.loadTexture(atlasPage, (function(imagePath, image) { pagesLoaded.count++; if (pagesLoaded.count == atlasPages.length) if (pageLoadError) { _this.errors[path] = "Couldn't load texture atlas page " + imagePath + "} of atlas " + path; error && error(path, "Couldn't load texture atlas page " + imagePath + " of atlas " + path); _this.toLoad--; _this.loaded++; } else try { var atlas = new spine.TextureAtlas(atlasData, function(path) { return _this.get(parent + "/" + path); }); _this.assets[path] = atlas; success && success(path, atlas); _this.toLoad--; _this.loaded++; } catch (e) { var ex = e; _this.errors[path] = "Couldn't load texture atlas " + path + ": " + ex.message; error && error(path, "Couldn't load texture atlas " + path + ": " + ex.message); _this.toLoad--; _this.loaded++; } }), (function(imagePath, errorMessage) { pageLoadError = true; pagesLoaded.count++; if (pagesLoaded.count == atlasPages.length) { _this.errors[path] = "Couldn't load texture atlas page " + imagePath + "} of atlas " + path; error && error(path, "Couldn't load texture atlas page " + imagePath + " of atlas " + path); _this.toLoad--; _this.loaded++; } })); }; for (var _i = 0, atlasPages_1 = atlasPages; _i < atlasPages_1.length; _i++) { var atlasPage = atlasPages_1[_i]; _loop_1(atlasPage); } }), (function(state, responseText) { _this.errors[path] = "Couldn't load texture atlas " + path + ": status " + status + ", " + responseText; error && error(path, "Couldn't load texture atlas " + path + ": status " + status + ", " + responseText); _this.toLoad--; _this.loaded++; })); }; AssetManager.prototype.get = function(path) { path = this.pathPrefix + path; return this.assets[path]; }; AssetManager.prototype.remove = function(path) { path = this.pathPrefix + path; var asset = this.assets[path]; asset.dispose && asset.dispose(); this.assets[path] = null; }; AssetManager.prototype.removeAll = function() { for (var key in this.assets) { var asset = this.assets[key]; asset.dispose && asset.dispose(); } this.assets = {}; }; AssetManager.prototype.isLoadingComplete = function() { return 0 == this.toLoad; }; AssetManager.prototype.getToLoad = function() { return this.toLoad; }; AssetManager.prototype.getLoaded = function() { return this.loaded; }; AssetManager.prototype.dispose = function() { this.removeAll(); }; AssetManager.prototype.hasErrors = function() { return Object.keys(this.errors).length > 0; }; AssetManager.prototype.getErrors = function() { return this.errors; }; return AssetManager; })(); spine.AssetManager = AssetManager; })(spine || (spine = {})); var spine; (function(spine) { var AtlasAttachmentLoader = (function() { function AtlasAttachmentLoader(atlas) { this.atlas = atlas; } AtlasAttachmentLoader.prototype.newRegionAttachment = function(skin, name, path) { var region = this.atlas.findRegion(path); if (null == region) return null; region.renderObject = region; var attachment = new spine.RegionAttachment(name); attachment.setRegion(region); return attachment; }; AtlasAttachmentLoader.prototype.newMeshAttachment = function(skin, name, path) { var region = this.atlas.findRegion(path); if (null == region) return null; region.renderObject = region; var attachment = new spine.MeshAttachment(name); attachment.region = region; return attachment; }; AtlasAttachmentLoader.prototype.newBoundingBoxAttachment = function(skin, name) { return new spine.BoundingBoxAttachment(name); }; AtlasAttachmentLoader.prototype.newPathAttachment = function(skin, name) { return new spine.PathAttachment(name); }; AtlasAttachmentLoader.prototype.newPointAttachment = function(skin, name) { return new spine.PointAttachment(name); }; AtlasAttachmentLoader.prototype.newClippingAttachment = function(skin, name) { return new spine.ClippingAttachment(name); }; return AtlasAttachmentLoader; })(); spine.AtlasAttachmentLoader = AtlasAttachmentLoader; })(spine || (spine = {})); var spine; (function(spine) { var BlendMode; (function(BlendMode) { BlendMode[BlendMode["Normal"] = 0] = "Normal"; BlendMode[BlendMode["Additive"] = 1] = "Additive"; BlendMode[BlendMode["Multiply"] = 2] = "Multiply"; BlendMode[BlendMode["Screen"] = 3] = "Screen"; })(BlendMode = spine.BlendMode || (spine.BlendMode = {})); })(spine || (spine = {})); var spine; (function(spine) { var Bone = (function() { function Bone(data, skeleton, parent) { this.children = new Array(); this.x = 0; this.y = 0; this.rotation = 0; this.scaleX = 0; this.scaleY = 0; this.shearX = 0; this.shearY = 0; this.ax = 0; this.ay = 0; this.arotation = 0; this.ascaleX = 0; this.ascaleY = 0; this.ashearX = 0; this.ashearY = 0; this.appliedValid = false; this.a = 0; this.b = 0; this.c = 0; this.d = 0; this.worldY = 0; this.worldX = 0; this.sorted = false; this.active = false; if (null == data) throw new Error("data cannot be null."); if (null == skeleton) throw new Error("skeleton cannot be null."); this.data = data; this.skeleton = skeleton; this.parent = parent; this.setToSetupPose(); } Bone.prototype.isActive = function() { return this.active; }; Bone.prototype.update = function() { this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); }; Bone.prototype.updateWorldTransform = function() { this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); }; Bone.prototype.updateWorldTransformWith = function(x, y, rotation, scaleX, scaleY, shearX, shearY) { this.ax = x; this.ay = y; this.arotation = rotation; this.ascaleX = scaleX; this.ascaleY = scaleY; this.ashearX = shearX; this.ashearY = shearY; this.appliedValid = true; var parent = this.parent; if (null == parent) { var skeleton = this.skeleton; var rotationY = rotation + 90 + shearY; var sx = skeleton.scaleX; var sy = skeleton.scaleY; this.a = spine.MathUtils.cosDeg(rotation + shearX) * scaleX * sx; this.b = spine.MathUtils.cosDeg(rotationY) * scaleY * sx; this.c = spine.MathUtils.sinDeg(rotation + shearX) * scaleX * sy; this.d = spine.MathUtils.sinDeg(rotationY) * scaleY * sy; this.worldX = x * sx + skeleton.x; this.worldY = y * sy + skeleton.y; return; } var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; this.worldX = pa * x + pb * y + parent.worldX; this.worldY = pc * x + pd * y + parent.worldY; switch (this.data.transformMode) { case spine.TransformMode.Normal: var rotationY = rotation + 90 + shearY; var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX; var lb = spine.MathUtils.cosDeg(rotationY) * scaleY; var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX; var ld = spine.MathUtils.sinDeg(rotationY) * scaleY; this.a = pa * la + pb * lc; this.b = pa * lb + pb * ld; this.c = pc * la + pd * lc; this.d = pc * lb + pd * ld; return; case spine.TransformMode.OnlyTranslation: var rotationY = rotation + 90 + shearY; this.a = spine.MathUtils.cosDeg(rotation + shearX) * scaleX; this.b = spine.MathUtils.cosDeg(rotationY) * scaleY; this.c = spine.MathUtils.sinDeg(rotation + shearX) * scaleX; this.d = spine.MathUtils.sinDeg(rotationY) * scaleY; break; case spine.TransformMode.NoRotationOrReflection: var s = pa * pa + pc * pc; var prx = 0; if (s > 1e-4) { s = Math.abs(pa * pd - pb * pc) / s; pb = pc * s; pd = pa * s; prx = Math.atan2(pc, pa) * spine.MathUtils.radDeg; } else { pa = 0; pc = 0; prx = 90 - Math.atan2(pd, pb) * spine.MathUtils.radDeg; } var rx = rotation + shearX - prx; var ry = rotation + shearY - prx + 90; var la = spine.MathUtils.cosDeg(rx) * scaleX; var lb = spine.MathUtils.cosDeg(ry) * scaleY; var lc = spine.MathUtils.sinDeg(rx) * scaleX; var ld = spine.MathUtils.sinDeg(ry) * scaleY; this.a = pa * la - pb * lc; this.b = pa * lb - pb * ld; this.c = pc * la + pd * lc; this.d = pc * lb + pd * ld; break; case spine.TransformMode.NoScale: case spine.TransformMode.NoScaleOrReflection: var cos = spine.MathUtils.cosDeg(rotation); var sin = spine.MathUtils.sinDeg(rotation); var za = (pa * cos + pb * sin) / this.skeleton.scaleX; var zc = (pc * cos + pd * sin) / this.skeleton.scaleY; var s = Math.sqrt(za * za + zc * zc); s > 1e-5 && (s = 1 / s); za *= s; zc *= s; s = Math.sqrt(za * za + zc * zc); this.data.transformMode == spine.TransformMode.NoScale && pa * pd - pb * pc < 0 != (this.skeleton.scaleX < 0 != this.skeleton.scaleY < 0) && (s = -s); var r = Math.PI / 2 + Math.atan2(zc, za); var zb = Math.cos(r) * s; var zd = Math.sin(r) * s; var la = spine.MathUtils.cosDeg(shearX) * scaleX; var lb = spine.MathUtils.cosDeg(90 + shearY) * scaleY; var lc = spine.MathUtils.sinDeg(shearX) * scaleX; var ld = spine.MathUtils.sinDeg(90 + shearY) * scaleY; this.a = za * la + zb * lc; this.b = za * lb + zb * ld; this.c = zc * la + zd * lc; this.d = zc * lb + zd * ld; } this.a *= this.skeleton.scaleX; this.b *= this.skeleton.scaleX; this.c *= this.skeleton.scaleY; this.d *= this.skeleton.scaleY; }; Bone.prototype.setToSetupPose = function() { var data = this.data; this.x = data.x; this.y = data.y; this.rotation = data.rotation; this.scaleX = data.scaleX; this.scaleY = data.scaleY; this.shearX = data.shearX; this.shearY = data.shearY; }; Bone.prototype.getWorldRotationX = function() { return Math.atan2(this.c, this.a) * spine.MathUtils.radDeg; }; Bone.prototype.getWorldRotationY = function() { return Math.atan2(this.d, this.b) * spine.MathUtils.radDeg; }; Bone.prototype.getWorldScaleX = function() { return Math.sqrt(this.a * this.a + this.c * this.c); }; Bone.prototype.getWorldScaleY = function() { return Math.sqrt(this.b * this.b + this.d * this.d); }; Bone.prototype.updateAppliedTransform = function() { this.appliedValid = true; var parent = this.parent; if (null == parent) { this.ax = this.worldX; this.ay = this.worldY; this.arotation = Math.atan2(this.c, this.a) * spine.MathUtils.radDeg; this.ascaleX = Math.sqrt(this.a * this.a + this.c * this.c); this.ascaleY = Math.sqrt(this.b * this.b + this.d * this.d); this.ashearX = 0; this.ashearY = Math.atan2(this.a * this.b + this.c * this.d, this.a * this.d - this.b * this.c) * spine.MathUtils.radDeg; return; } var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; var pid = 1 / (pa * pd - pb * pc); var dx = this.worldX - parent.worldX, dy = this.worldY - parent.worldY; this.ax = dx * pd * pid - dy * pb * pid; this.ay = dy * pa * pid - dx * pc * pid; var ia = pid * pd; var id = pid * pa; var ib = pid * pb; var ic = pid * pc; var ra = ia * this.a - ib * this.c; var rb = ia * this.b - ib * this.d; var rc = id * this.c - ic * this.a; var rd = id * this.d - ic * this.b; this.ashearX = 0; this.ascaleX = Math.sqrt(ra * ra + rc * rc); if (this.ascaleX > 1e-4) { var det = ra * rd - rb * rc; this.ascaleY = det / this.ascaleX; this.ashearY = Math.atan2(ra * rb + rc * rd, det) * spine.MathUtils.radDeg; this.arotation = Math.atan2(rc, ra) * spine.MathUtils.radDeg; } else { this.ascaleX = 0; this.ascaleY = Math.sqrt(rb * rb + rd * rd); this.ashearY = 0; this.arotation = 90 - Math.atan2(rd, rb) * spine.MathUtils.radDeg; } }; Bone.prototype.worldToLocal = function(world) { var a = this.a, b = this.b, c = this.c, d = this.d; var invDet = 1 / (a * d - b * c); var x = world.x - this.worldX, y = world.y - this.worldY; world.x = x * d * invDet - y * b * invDet; world.y = y * a * invDet - x * c * invDet; return world; }; Bone.prototype.localToWorld = function(local) { var x = local.x, y = local.y; local.x = x * this.a + y * this.b + this.worldX; local.y = x * this.c + y * this.d + this.worldY; return local; }; Bone.prototype.worldToLocalRotation = function(worldRotation) { var sin = spine.MathUtils.sinDeg(worldRotation), cos = spine.MathUtils.cosDeg(worldRotation); return Math.atan2(this.a * sin - this.c * cos, this.d * cos - this.b * sin) * spine.MathUtils.radDeg + this.rotation - this.shearX; }; Bone.prototype.localToWorldRotation = function(localRotation) { localRotation -= this.rotation - this.shearX; var sin = spine.MathUtils.sinDeg(localRotation), cos = spine.MathUtils.cosDeg(localRotation); return Math.atan2(cos * this.c + sin * this.d, cos * this.a + sin * this.b) * spine.MathUtils.radDeg; }; Bone.prototype.rotateWorld = function(degrees) { var a = this.a, b = this.b, c = this.c, d = this.d; var cos = spine.MathUtils.cosDeg(degrees), sin = spine.MathUtils.sinDeg(degrees); this.a = cos * a - sin * c; this.b = cos * b - sin * d; this.c = sin * a + cos * c; this.d = sin * b + cos * d; this.appliedValid = false; }; return Bone; })(); spine.Bone = Bone; })(spine || (spine = {})); var spine; (function(spine) { var BoneData = (function() { function BoneData(index, name, parent) { this.x = 0; this.y = 0; this.rotation = 0; this.scaleX = 1; this.scaleY = 1; this.shearX = 0; this.shearY = 0; this.transformMode = TransformMode.Normal; this.skinRequired = false; this.color = new spine.Color(); if (index < 0) throw new Error("index must be >= 0."); if (null == name) throw new Error("name cannot be null."); this.index = index; this.name = name; this.parent = parent; } return BoneData; })(); spine.BoneData = BoneData; var TransformMode; (function(TransformMode) { TransformMode[TransformMode["Normal"] = 0] = "Normal"; TransformMode[TransformMode["OnlyTranslation"] = 1] = "OnlyTranslation"; TransformMode[TransformMode["NoRotationOrReflection"] = 2] = "NoRotationOrReflection"; TransformMode[TransformMode["NoScale"] = 3] = "NoScale"; TransformMode[TransformMode["NoScaleOrReflection"] = 4] = "NoScaleOrReflection"; })(TransformMode = spine.TransformMode || (spine.TransformMode = {})); })(spine || (spine = {})); var spine; (function(spine) { var ConstraintData = (function() { function ConstraintData(name, order, skinRequired) { this.name = name; this.order = order; this.skinRequired = skinRequired; } return ConstraintData; })(); spine.ConstraintData = ConstraintData; })(spine || (spine = {})); var spine; (function(spine) { var Event = (function() { function Event(time, data) { if (null == data) throw new Error("data cannot be null."); this.time = time; this.data = data; } return Event; })(); spine.Event = Event; })(spine || (spine = {})); var spine; (function(spine) { var EventData = (function() { function EventData(name) { this.name = name; } return EventData; })(); spine.EventData = EventData; })(spine || (spine = {})); var spine; (function(spine) { var IkConstraint = (function() { function IkConstraint(data, skeleton) { this.bendDirection = 0; this.compress = false; this.stretch = false; this.mix = 1; this.softness = 0; this.active = false; if (null == data) throw new Error("data cannot be null."); if (null == skeleton) throw new Error("skeleton cannot be null."); this.data = data; this.mix = data.mix; this.softness = data.softness; this.bendDirection = data.bendDirection; this.compress = data.compress; this.stretch = data.stretch; this.bones = new Array(); for (var i = 0; i < data.bones.length; i++) this.bones.push(skeleton.findBone(data.bones[i].name)); this.target = skeleton.findBone(data.target.name); } IkConstraint.prototype.isActive = function() { return this.active; }; IkConstraint.prototype.apply = function() { this.update(); }; IkConstraint.prototype.update = function() { var target = this.target; var bones = this.bones; switch (bones.length) { case 1: this.apply1(bones[0], target.worldX, target.worldY, this.compress, this.stretch, this.data.uniform, this.mix); break; case 2: this.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.stretch, this.softness, this.mix); } }; IkConstraint.prototype.apply1 = function(bone, targetX, targetY, compress, stretch, uniform, alpha) { bone.appliedValid || bone.updateAppliedTransform(); var p = bone.parent; var id = 1 / (p.a * p.d - p.b * p.c); var x = targetX - p.worldX, y = targetY - p.worldY; var tx = (x * p.d - y * p.b) * id - bone.ax, ty = (y * p.a - x * p.c) * id - bone.ay; var rotationIK = Math.atan2(ty, tx) * spine.MathUtils.radDeg - bone.ashearX - bone.arotation; bone.ascaleX < 0 && (rotationIK += 180); rotationIK > 180 ? rotationIK -= 360 : rotationIK < -180 && (rotationIK += 360); var sx = bone.ascaleX, sy = bone.ascaleY; if (compress || stretch) { var b = bone.data.length * sx, dd = Math.sqrt(tx * tx + ty * ty); if (compress && dd < b || stretch && dd > b && b > 1e-4) { var s = (dd / b - 1) * alpha + 1; sx *= s; uniform && (sy *= s); } } bone.updateWorldTransformWith(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, sx, sy, bone.ashearX, bone.ashearY); }; IkConstraint.prototype.apply2 = function(parent, child, targetX, targetY, bendDir, stretch, softness, alpha) { if (0 == alpha) { child.updateWorldTransform(); return; } parent.appliedValid || parent.updateAppliedTransform(); child.appliedValid || child.updateAppliedTransform(); var px = parent.ax, py = parent.ay, psx = parent.ascaleX, sx = psx, psy = parent.ascaleY, csx = child.ascaleX; var os1 = 0, os2 = 0, s2 = 0; if (psx < 0) { psx = -psx; os1 = 180; s2 = -1; } else { os1 = 0; s2 = 1; } if (psy < 0) { psy = -psy; s2 = -s2; } if (csx < 0) { csx = -csx; os2 = 180; } else os2 = 0; var cx = child.ax, cy = 0, cwx = 0, cwy = 0, a = parent.a, b = parent.b, c = parent.c, d = parent.d; var u = Math.abs(psx - psy) <= 1e-4; if (u) { cy = child.ay; cwx = a * cx + b * cy + parent.worldX; cwy = c * cx + d * cy + parent.worldY; } else { cy = 0; cwx = a * cx + parent.worldX; cwy = c * cx + parent.worldY; } var pp = parent.parent; a = pp.a; b = pp.b; c = pp.c; d = pp.d; var id = 1 / (a * d - b * c), x = cwx - pp.worldX, y = cwy - pp.worldY; var dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py; var l1 = Math.sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2; if (l1 < 1e-4) { this.apply1(parent, targetX, targetY, false, stretch, false, alpha); child.updateWorldTransformWith(cx, cy, 0, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY); return; } x = targetX - pp.worldX; y = targetY - pp.worldY; var tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py; var dd = tx * tx + ty * ty; if (0 != softness) { softness *= psx * (csx + 1) / 2; var td = Math.sqrt(dd), sd = td - l1 - l2 * psx + softness; if (sd > 0) { var p = Math.min(1, sd / (2 * softness)) - 1; p = (sd - softness * (1 - p * p)) / td; tx -= p * tx; ty -= p * ty; dd = tx * tx + ty * ty; } } outer: if (u) { l2 *= psx; var cos = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2); if (cos < -1) cos = -1; else if (cos > 1) { cos = 1; stretch && (sx *= (Math.sqrt(dd) / (l1 + l2) - 1) * alpha + 1); } a2 = Math.acos(cos) * bendDir; a = l1 + l2 * cos; b = l2 * Math.sin(a2); a1 = Math.atan2(ty * a - tx * b, tx * a + ty * b); } else { a = psx * l2; b = psy * l2; var aa = a * a, bb = b * b, ta = Math.atan2(ty, tx); c = bb * l1 * l1 + aa * dd - aa * bb; var c1 = -2 * bb * l1, c2 = bb - aa; d = c1 * c1 - 4 * c2 * c; if (d >= 0) { var q = Math.sqrt(d); c1 < 0 && (q = -q); q = -(c1 + q) / 2; var r0 = q / c2, r1 = c / q; var r = Math.abs(r0) < Math.abs(r1) ? r0 : r1; if (r * r <= dd) { y = Math.sqrt(dd - r * r) * bendDir; a1 = ta - Math.atan2(y, r); a2 = Math.atan2(y / psy, (r - l1) / psx); break outer; } } var minAngle = spine.MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0; var maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0; c = -a * l1 / (aa - bb); if (c >= -1 && c <= 1) { c = Math.acos(c); x = a * Math.cos(c) + l1; y = b * Math.sin(c); d = x * x + y * y; if (d < minDist) { minAngle = c; minDist = d; minX = x; minY = y; } if (d > maxDist) { maxAngle = c; maxDist = d; maxX = x; maxY = y; } } if (dd <= (minDist + maxDist) / 2) { a1 = ta - Math.atan2(minY * bendDir, minX); a2 = minAngle * bendDir; } else { a1 = ta - Math.atan2(maxY * bendDir, maxX); a2 = maxAngle * bendDir; } } var os = Math.atan2(cy, cx) * s2; var rotation = parent.arotation; a1 = (a1 - os) * spine.MathUtils.radDeg + os1 - rotation; a1 > 180 ? a1 -= 360 : a1 < -180 && (a1 += 360); parent.updateWorldTransformWith(px, py, rotation + a1 * alpha, sx, parent.ascaleY, 0, 0); rotation = child.arotation; a2 = ((a2 + os) * spine.MathUtils.radDeg - child.ashearX) * s2 + os2 - rotation; a2 > 180 ? a2 -= 360 : a2 < -180 && (a2 += 360); child.updateWorldTransformWith(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY); }; return IkConstraint; })(); spine.IkConstraint = IkConstraint; })(spine || (spine = {})); var spine; (function(spine) { var IkConstraintData = (function(_super) { __extends(IkConstraintData, _super); function IkConstraintData(name) { var _this = _super.call(this, name, 0, false) || this; _this.bones = new Array(); _this.bendDirection = 1; _this.compress = false; _this.stretch = false; _this.uniform = false; _this.mix = 1; _this.softness = 0; return _this; } return IkConstraintData; })(spine.ConstraintData); spine.IkConstraintData = IkConstraintData; })(spine || (spine = {})); var spine; (function(spine) { var PathConstraint = (function() { function PathConstraint(data, skeleton) { this.position = 0; this.spacing = 0; this.rotateMix = 0; this.translateMix = 0; this.spaces = new Array(); this.positions = new Array(); this.world = new Array(); this.curves = new Array(); this.lengths = new Array(); this.segments = new Array(); this.active = false; if (null == data) throw new Error("data cannot be null."); if (null == skeleton) throw new Error("skeleton cannot be null."); this.data = data; this.bones = new Array(); for (var i = 0, n = data.bones.length; i < n; i++) this.bones.push(skeleton.findBone(data.bones[i].name)); this.target = skeleton.findSlot(data.target.name); this.position = data.position; this.spacing = data.spacing; this.rotateMix = data.rotateMix; this.translateMix = data.translateMix; } PathConstraint.prototype.isActive = function() { return this.active; }; PathConstraint.prototype.apply = function() { this.update(); }; PathConstraint.prototype.update = function() { var attachment = this.target.getAttachment(); if (!(attachment instanceof spine.PathAttachment)) return; var rotateMix = this.rotateMix, translateMix = this.translateMix; var translate = translateMix > 0, rotate = rotateMix > 0; if (!translate && !rotate) return; var data = this.data; var percentSpacing = data.spacingMode == spine.SpacingMode.Percent; var rotateMode = data.rotateMode; var tangents = rotateMode == spine.RotateMode.Tangent, scale = rotateMode == spine.RotateMode.ChainScale; var boneCount = this.bones.length, spacesCount = tangents ? boneCount : boneCount + 1; var bones = this.bones; var spaces = spine.Utils.setArraySize(this.spaces, spacesCount), lengths = null; var spacing = this.spacing; if (scale || !percentSpacing) { scale && (lengths = spine.Utils.setArraySize(this.lengths, boneCount)); var lengthSpacing = data.spacingMode == spine.SpacingMode.Length; for (var i = 0, n = spacesCount - 1; i < n; ) { var bone = bones[i]; var setupLength = bone.data.length; if (setupLength < PathConstraint.epsilon) { scale && (lengths[i] = 0); spaces[++i] = 0; } else if (percentSpacing) { if (scale) { var x = setupLength * bone.a, y = setupLength * bone.c; var length_1 = Math.sqrt(x * x + y * y); lengths[i] = length_1; } spaces[++i] = spacing; } else { var x = setupLength * bone.a, y = setupLength * bone.c; var length_2 = Math.sqrt(x * x + y * y); scale && (lengths[i] = length_2); spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length_2 / setupLength; } } } else for (var i = 1; i < spacesCount; i++) spaces[i] = spacing; var positions = this.computeWorldPositions(attachment, spacesCount, tangents, data.positionMode == spine.PositionMode.Percent, percentSpacing); var boneX = positions[0], boneY = positions[1], offsetRotation = data.offsetRotation; var tip = false; if (0 == offsetRotation) tip = rotateMode == spine.RotateMode.Chain; else { tip = false; var p = this.target.bone; offsetRotation *= p.a * p.d - p.b * p.c > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad; } for (var i = 0, p = 3; i < boneCount; i++, p += 3) { var bone = bones[i]; bone.worldX += (boneX - bone.worldX) * translateMix; bone.worldY += (boneY - bone.worldY) * translateMix; var x = positions[p], y = positions[p + 1], dx = x - boneX, dy = y - boneY; if (scale) { var length_3 = lengths[i]; if (0 != length_3) { var s = (Math.sqrt(dx * dx + dy * dy) / length_3 - 1) * rotateMix + 1; bone.a *= s; bone.c *= s; } } boneX = x; boneY = y; if (rotate) { var a = bone.a, b = bone.b, c = bone.c, d = bone.d, r = 0, cos = 0, sin = 0; r = tangents ? positions[p - 1] : 0 == spaces[i + 1] ? positions[p + 2] : Math.atan2(dy, dx); r -= Math.atan2(c, a); if (tip) { cos = Math.cos(r); sin = Math.sin(r); var length_4 = bone.data.length; boneX += (length_4 * (cos * a - sin * c) - dx) * rotateMix; boneY += (length_4 * (sin * a + cos * c) - dy) * rotateMix; } else r += offsetRotation; r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : r < -spine.MathUtils.PI && (r += spine.MathUtils.PI2); r *= rotateMix; cos = Math.cos(r); sin = Math.sin(r); bone.a = cos * a - sin * c; bone.b = cos * b - sin * d; bone.c = sin * a + cos * c; bone.d = sin * b + cos * d; } bone.appliedValid = false; } }; PathConstraint.prototype.computeWorldPositions = function(path, spacesCount, tangents, percentPosition, percentSpacing) { var target = this.target; var position = this.position; var spaces = this.spaces, out = spine.Utils.setArraySize(this.positions, 3 * spacesCount + 2), world = null; var closed = path.closed; var verticesLength = path.worldVerticesLength, curveCount = verticesLength / 6, prevCurve = PathConstraint.NONE; if (!path.constantSpeed) { var lengths = path.lengths; curveCount -= closed ? 1 : 2; var pathLength_1 = lengths[curveCount]; percentPosition && (position *= pathLength_1); if (percentSpacing) for (var i = 1; i < spacesCount; i++) spaces[i] *= pathLength_1; world = spine.Utils.setArraySize(this.world, 8); for (var i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) { var space = spaces[i]; position += space; var p = position; if (closed) { p %= pathLength_1; p < 0 && (p += pathLength_1); curve = 0; } else { if (p < 0) { if (prevCurve != PathConstraint.BEFORE) { prevCurve = PathConstraint.BEFORE; path.computeWorldVertices(target, 2, 4, world, 0, 2); } this.addBeforePosition(p, world, 0, out, o); continue; } if (p > pathLength_1) { if (prevCurve != PathConstraint.AFTER) { prevCurve = PathConstraint.AFTER; path.computeWorldVertices(target, verticesLength - 6, 4, world, 0, 2); } this.addAfterPosition(p - pathLength_1, world, 0, out, o); continue; } } for (;;curve++) { var length_5 = lengths[curve]; if (p > length_5) continue; if (0 == curve) p /= length_5; else { var prev = lengths[curve - 1]; p = (p - prev) / (length_5 - prev); } break; } if (curve != prevCurve) { prevCurve = curve; if (closed && curve == curveCount) { path.computeWorldVertices(target, verticesLength - 4, 4, world, 0, 2); path.computeWorldVertices(target, 0, 4, world, 4, 2); } else path.computeWorldVertices(target, 6 * curve + 2, 8, world, 0, 2); } this.addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], out, o, tangents || i > 0 && 0 == space); } return out; } if (closed) { verticesLength += 2; world = spine.Utils.setArraySize(this.world, verticesLength); path.computeWorldVertices(target, 2, verticesLength - 4, world, 0, 2); path.computeWorldVertices(target, 0, 2, world, verticesLength - 4, 2); world[verticesLength - 2] = world[0]; world[verticesLength - 1] = world[1]; } else { curveCount--; verticesLength -= 4; world = spine.Utils.setArraySize(this.world, verticesLength); path.computeWorldVertices(target, 2, verticesLength, world, 0, 2); } var curves = spine.Utils.setArraySize(this.curves, curveCount); var pathLength = 0; var x1 = world[0], y1 = world[1], cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, x2 = 0, y2 = 0; var tmpx = 0, tmpy = 0, dddfx = 0, dddfy = 0, ddfx = 0, ddfy = 0, dfx = 0, dfy = 0; for (var i = 0, w = 2; i < curveCount; i++, w += 6) { cx1 = world[w]; cy1 = world[w + 1]; cx2 = world[w + 2]; cy2 = world[w + 3]; x2 = world[w + 4]; y2 = world[w + 5]; tmpx = .1875 * (x1 - 2 * cx1 + cx2); tmpy = .1875 * (y1 - 2 * cy1 + cy2); dddfx = .09375 * (3 * (cx1 - cx2) - x1 + x2); dddfy = .09375 * (3 * (cy1 - cy2) - y1 + y2); ddfx = 2 * tmpx + dddfx; ddfy = 2 * tmpy + dddfy; dfx = .75 * (cx1 - x1) + tmpx + .16666667 * dddfx; dfy = .75 * (cy1 - y1) + tmpy + .16666667 * dddfy; pathLength += Math.sqrt(dfx * dfx + dfy * dfy); dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; pathLength += Math.sqrt(dfx * dfx + dfy * dfy); dfx += ddfx; dfy += ddfy; pathLength += Math.sqrt(dfx * dfx + dfy * dfy); dfx += ddfx + dddfx; dfy += ddfy + dddfy; pathLength += Math.sqrt(dfx * dfx + dfy * dfy); curves[i] = pathLength; x1 = x2; y1 = y2; } position *= percentPosition ? pathLength : pathLength / path.lengths[curveCount - 1]; if (percentSpacing) for (var i = 1; i < spacesCount; i++) spaces[i] *= pathLength; var segments = this.segments; var curveLength = 0; for (var i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) { var space = spaces[i]; position += space; var p = position; if (closed) { p %= pathLength; p < 0 && (p += pathLength); curve = 0; } else { if (p < 0) { this.addBeforePosition(p, world, 0, out, o); continue; } if (p > pathLength) { this.addAfterPosition(p - pathLength, world, verticesLength - 4, out, o); continue; } } for (;;curve++) { var length_6 = curves[curve]; if (p > length_6) continue; if (0 == curve) p /= length_6; else { var prev = curves[curve - 1]; p = (p - prev) / (length_6 - prev); } break; } if (curve != prevCurve) { prevCurve = curve; var ii = 6 * curve; x1 = world[ii]; y1 = world[ii + 1]; cx1 = world[ii + 2]; cy1 = world[ii + 3]; cx2 = world[ii + 4]; cy2 = world[ii + 5]; x2 = world[ii + 6]; y2 = world[ii + 7]; tmpx = .03 * (x1 - 2 * cx1 + cx2); tmpy = .03 * (y1 - 2 * cy1 + cy2); dddfx = .006 * (3 * (cx1 - cx2) - x1 + x2); dddfy = .006 * (3 * (cy1 - cy2) - y1 + y2); ddfx = 2 * tmpx + dddfx; ddfy = 2 * tmpy + dddfy; dfx = .3 * (cx1 - x1) + tmpx + .16666667 * dddfx; dfy = .3 * (cy1 - y1) + tmpy + .16666667 * dddfy; curveLength = Math.sqrt(dfx * dfx + dfy * dfy); segments[0] = curveLength; for (ii = 1; ii < 8; ii++) { dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; curveLength += Math.sqrt(dfx * dfx + dfy * dfy); segments[ii] = curveLength; } dfx += ddfx; dfy += ddfy; curveLength += Math.sqrt(dfx * dfx + dfy * dfy); segments[8] = curveLength; dfx += ddfx + dddfx; dfy += ddfy + dddfy; curveLength += Math.sqrt(dfx * dfx + dfy * dfy); segments[9] = curveLength; segment = 0; } p *= curveLength; for (;;segment++) { var length_7 = segments[segment]; if (p > length_7) continue; if (0 == segment) p /= length_7; else { var prev = segments[segment - 1]; p = segment + (p - prev) / (length_7 - prev); } break; } this.addCurvePosition(.1 * p, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents || i > 0 && 0 == space); } return out; }; PathConstraint.prototype.addBeforePosition = function(p, temp, i, out, o) { var x1 = temp[i], y1 = temp[i + 1], dx = temp[i + 2] - x1, dy = temp[i + 3] - y1, r = Math.atan2(dy, dx); out[o] = x1 + p * Math.cos(r); out[o + 1] = y1 + p * Math.sin(r); out[o + 2] = r; }; PathConstraint.prototype.addAfterPosition = function(p, temp, i, out, o) { var x1 = temp[i + 2], y1 = temp[i + 3], dx = x1 - temp[i], dy = y1 - temp[i + 1], r = Math.atan2(dy, dx); out[o] = x1 + p * Math.cos(r); out[o + 1] = y1 + p * Math.sin(r); out[o + 2] = r; }; PathConstraint.prototype.addCurvePosition = function(p, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents) { if (0 == p || isNaN(p)) { out[o] = x1; out[o + 1] = y1; out[o + 2] = Math.atan2(cy1 - y1, cx1 - x1); return; } var tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u; var ut = u * p, ut3 = 3 * ut, uut3 = u * ut3, utt3 = ut3 * p; var x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt, y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt; out[o] = x; out[o + 1] = y; tangents && (out[o + 2] = p < .001 ? Math.atan2(cy1 - y1, cx1 - x1) : Math.atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt))); }; PathConstraint.NONE = -1; PathConstraint.BEFORE = -2; PathConstraint.AFTER = -3; PathConstraint.epsilon = 1e-5; return PathConstraint; })(); spine.PathConstraint = PathConstraint; })(spine || (spine = {})); var spine; (function(spine) { var PathConstraintData = (function(_super) { __extends(PathConstraintData, _super); function PathConstraintData(name) { var _this = _super.call(this, name, 0, false) || this; _this.bones = new Array(); return _this; } return PathConstraintData; })(spine.ConstraintData); spine.PathConstraintData = PathConstraintData; var PositionMode; (function(PositionMode) { PositionMode[PositionMode["Fixed"] = 0] = "Fixed"; PositionMode[PositionMode["Percent"] = 1] = "Percent"; })(PositionMode = spine.PositionMode || (spine.PositionMode = {})); var SpacingMode; (function(SpacingMode) { SpacingMode[SpacingMode["Length"] = 0] = "Length"; SpacingMode[SpacingMode["Fixed"] = 1] = "Fixed"; SpacingMode[SpacingMode["Percent"] = 2] = "Percent"; })(SpacingMode = spine.SpacingMode || (spine.SpacingMode = {})); var RotateMode; (function(RotateMode) { RotateMode[RotateMode["Tangent"] = 0] = "Tangent"; RotateMode[RotateMode["Chain"] = 1] = "Chain"; RotateMode[RotateMode["ChainScale"] = 2] = "ChainScale"; })(RotateMode = spine.RotateMode || (spine.RotateMode = {})); })(spine || (spine = {})); var spine; (function(spine) { var Assets = (function() { function Assets(clientId) { this.toLoad = new Array(); this.assets = {}; this.clientId = clientId; } Assets.prototype.loaded = function() { var i = 0; for (var v in this.assets) i++; return i; }; return Assets; })(); var SharedAssetManager = (function() { function SharedAssetManager(pathPrefix) { void 0 === pathPrefix && (pathPrefix = ""); this.clientAssets = {}; this.queuedAssets = {}; this.rawAssets = {}; this.errors = {}; this.pathPrefix = pathPrefix; } SharedAssetManager.prototype.queueAsset = function(clientId, textureLoader, path) { var clientAssets = this.clientAssets[clientId]; if (null === clientAssets || void 0 === clientAssets) { clientAssets = new Assets(clientId); this.clientAssets[clientId] = clientAssets; } null !== textureLoader && (clientAssets.textureLoader = textureLoader); clientAssets.toLoad.push(path); if (this.queuedAssets[path] === path) return false; this.queuedAssets[path] = path; return true; }; SharedAssetManager.prototype.loadText = function(clientId, path) { var _this = this; path = this.pathPrefix + path; if (!this.queueAsset(clientId, null, path)) return; var request = new XMLHttpRequest(); request.onreadystatechange = function() { request.readyState == XMLHttpRequest.DONE && (request.status >= 200 && request.status < 300 ? _this.rawAssets[path] = request.responseText : _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText); }; request.open("GET", path, true); request.send(); }; SharedAssetManager.prototype.loadJson = function(clientId, path) { var _this = this; path = this.pathPrefix + path; if (!this.queueAsset(clientId, null, path)) return; var request = new XMLHttpRequest(); request.onreadystatechange = function() { request.readyState == XMLHttpRequest.DONE && (request.status >= 200 && request.status < 300 ? _this.rawAssets[path] = JSON.parse(request.responseText) : _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText); }; request.open("GET", path, true); request.send(); }; SharedAssetManager.prototype.loadTexture = function(clientId, textureLoader, path) { var _this = this; path = this.pathPrefix + path; if (!this.queueAsset(clientId, textureLoader, path)) return; var img = new Image(); img.src = path; img.crossOrigin = "anonymous"; img.onload = function(ev) { _this.rawAssets[path] = img; }; img.onerror = function(ev) { _this.errors[path] = "Couldn't load image " + path; }; }; SharedAssetManager.prototype.get = function(clientId, path) { path = this.pathPrefix + path; var clientAssets = this.clientAssets[clientId]; if (null === clientAssets || void 0 === clientAssets) return true; return clientAssets.assets[path]; }; SharedAssetManager.prototype.updateClientAssets = function(clientAssets) { for (var i = 0; i < clientAssets.toLoad.length; i++) { var path = clientAssets.toLoad[i]; var asset = clientAssets.assets[path]; if (null === asset || void 0 === asset) { var rawAsset = this.rawAssets[path]; if (null === rawAsset || void 0 === rawAsset) continue; rawAsset instanceof HTMLImageElement ? clientAssets.assets[path] = clientAssets.textureLoader(rawAsset) : clientAssets.assets[path] = rawAsset; } } }; SharedAssetManager.prototype.isLoadingComplete = function(clientId) { var clientAssets = this.clientAssets[clientId]; if (null === clientAssets || void 0 === clientAssets) return true; this.updateClientAssets(clientAssets); return clientAssets.toLoad.length == clientAssets.loaded(); }; SharedAssetManager.prototype.dispose = function() {}; SharedAssetManager.prototype.hasErrors = function() { return Object.keys(this.errors).length > 0; }; SharedAssetManager.prototype.getErrors = function() { return this.errors; }; return SharedAssetManager; })(); spine.SharedAssetManager = SharedAssetManager; })(spine || (spine = {})); var spine; (function(spine) { var Skeleton = (function() { function Skeleton(data) { this._updateCache = new Array(); this.updateCacheReset = new Array(); this.time = 0; this.scaleX = 1; this.scaleY = 1; this.x = 0; this.y = 0; if (null == data) throw new Error("data cannot be null."); this.data = data; this.bones = new Array(); for (var i = 0; i < data.bones.length; i++) { var boneData = data.bones[i]; var bone = void 0; if (null == boneData.parent) bone = new spine.Bone(boneData, this, null); else { var parent_1 = this.bones[boneData.parent.index]; bone = new spine.Bone(boneData, this, parent_1); parent_1.children.push(bone); } this.bones.push(bone); } this.slots = new Array(); this.drawOrder = new Array(); for (var i = 0; i < data.slots.length; i++) { var slotData = data.slots[i]; var bone = this.bones[slotData.boneData.index]; var slot = new spine.Slot(slotData, bone); this.slots.push(slot); this.drawOrder.push(slot); } this.ikConstraints = new Array(); for (var i = 0; i < data.ikConstraints.length; i++) { var ikConstraintData = data.ikConstraints[i]; this.ikConstraints.push(new spine.IkConstraint(ikConstraintData, this)); } this.transformConstraints = new Array(); for (var i = 0; i < data.transformConstraints.length; i++) { var transformConstraintData = data.transformConstraints[i]; this.transformConstraints.push(new spine.TransformConstraint(transformConstraintData, this)); } this.pathConstraints = new Array(); for (var i = 0; i < data.pathConstraints.length; i++) { var pathConstraintData = data.pathConstraints[i]; this.pathConstraints.push(new spine.PathConstraint(pathConstraintData, this)); } this.color = new spine.Color(1, 1, 1, 1); this.updateCache(); } Skeleton.prototype.updateCache = function() { var updateCache = this._updateCache; updateCache.length = 0; this.updateCacheReset.length = 0; var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; bone.sorted = bone.data.skinRequired; bone.active = !bone.sorted; } if (null != this.skin) { var skinBones = this.skin.bones; for (var i = 0, n = this.skin.bones.length; i < n; i++) { var bone = this.bones[skinBones[i].index]; do { bone.sorted = false; bone.active = true; bone = bone.parent; } while (null != bone); } } var ikConstraints = this.ikConstraints; var transformConstraints = this.transformConstraints; var pathConstraints = this.pathConstraints; var ikCount = ikConstraints.length, transformCount = transformConstraints.length, pathCount = pathConstraints.length; var constraintCount = ikCount + transformCount + pathCount; outer: for (var i = 0; i < constraintCount; i++) { for (var ii = 0; ii < ikCount; ii++) { var constraint = ikConstraints[ii]; if (constraint.data.order == i) { this.sortIkConstraint(constraint); continue outer; } } for (var ii = 0; ii < transformCount; ii++) { var constraint = transformConstraints[ii]; if (constraint.data.order == i) { this.sortTransformConstraint(constraint); continue outer; } } for (var ii = 0; ii < pathCount; ii++) { var constraint = pathConstraints[ii]; if (constraint.data.order == i) { this.sortPathConstraint(constraint); continue outer; } } } for (var i = 0, n = bones.length; i < n; i++) this.sortBone(bones[i]); }; Skeleton.prototype.sortIkConstraint = function(constraint) { constraint.active = constraint.target.isActive() && (!constraint.data.skinRequired || null != this.skin && spine.Utils.contains(this.skin.constraints, constraint.data, true)); if (!constraint.active) return; var target = constraint.target; this.sortBone(target); var constrained = constraint.bones; var parent = constrained[0]; this.sortBone(parent); if (constrained.length > 1) { var child = constrained[constrained.length - 1]; this._updateCache.indexOf(child) > -1 || this.updateCacheReset.push(child); } this._updateCache.push(constraint); this.sortReset(parent.children); constrained[constrained.length - 1].sorted = true; }; Skeleton.prototype.sortPathConstraint = function(constraint) { constraint.active = constraint.target.bone.isActive() && (!constraint.data.skinRequired || null != this.skin && spine.Utils.contains(this.skin.constraints, constraint.data, true)); if (!constraint.active) return; var slot = constraint.target; var slotIndex = slot.data.index; var slotBone = slot.bone; null != this.skin && this.sortPathConstraintAttachment(this.skin, slotIndex, slotBone); null != this.data.defaultSkin && this.data.defaultSkin != this.skin && this.sortPathConstraintAttachment(this.data.defaultSkin, slotIndex, slotBone); for (var i = 0, n = this.data.skins.length; i < n; i++) this.sortPathConstraintAttachment(this.data.skins[i], slotIndex, slotBone); var attachment = slot.getAttachment(); attachment instanceof spine.PathAttachment && this.sortPathConstraintAttachmentWith(attachment, slotBone); var constrained = constraint.bones; var boneCount = constrained.length; for (var i = 0; i < boneCount; i++) this.sortBone(constrained[i]); this._updateCache.push(constraint); for (var i = 0; i < boneCount; i++) this.sortReset(constrained[i].children); for (var i = 0; i < boneCount; i++) constrained[i].sorted = true; }; Skeleton.prototype.sortTransformConstraint = function(constraint) { constraint.active = constraint.target.isActive() && (!constraint.data.skinRequired || null != this.skin && spine.Utils.contains(this.skin.constraints, constraint.data, true)); if (!constraint.active) return; this.sortBone(constraint.target); var constrained = constraint.bones; var boneCount = constrained.length; if (constraint.data.local) for (var i = 0; i < boneCount; i++) { var child = constrained[i]; this.sortBone(child.parent); this._updateCache.indexOf(child) > -1 || this.updateCacheReset.push(child); } else for (var i = 0; i < boneCount; i++) this.sortBone(constrained[i]); this._updateCache.push(constraint); for (var ii = 0; ii < boneCount; ii++) this.sortReset(constrained[ii].children); for (var ii = 0; ii < boneCount; ii++) constrained[ii].sorted = true; }; Skeleton.prototype.sortPathConstraintAttachment = function(skin, slotIndex, slotBone) { var attachments = skin.attachments[slotIndex]; if (!attachments) return; for (var key in attachments) this.sortPathConstraintAttachmentWith(attachments[key], slotBone); }; Skeleton.prototype.sortPathConstraintAttachmentWith = function(attachment, slotBone) { if (!(attachment instanceof spine.PathAttachment)) return; var pathBones = attachment.bones; if (null == pathBones) this.sortBone(slotBone); else { var bones = this.bones; var i = 0; while (i < pathBones.length) { var boneCount = pathBones[i++]; for (var n = i + boneCount; i < n; i++) { var boneIndex = pathBones[i]; this.sortBone(bones[boneIndex]); } } } }; Skeleton.prototype.sortBone = function(bone) { if (bone.sorted) return; var parent = bone.parent; null != parent && this.sortBone(parent); bone.sorted = true; this._updateCache.push(bone); }; Skeleton.prototype.sortReset = function(bones) { for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; if (!bone.active) continue; bone.sorted && this.sortReset(bone.children); bone.sorted = false; } }; Skeleton.prototype.updateWorldTransform = function() { var updateCacheReset = this.updateCacheReset; for (var i = 0, n = updateCacheReset.length; i < n; i++) { var bone = updateCacheReset[i]; bone.ax = bone.x; bone.ay = bone.y; bone.arotation = bone.rotation; bone.ascaleX = bone.scaleX; bone.ascaleY = bone.scaleY; bone.ashearX = bone.shearX; bone.ashearY = bone.shearY; bone.appliedValid = true; } var updateCache = this._updateCache; for (var i = 0, n = updateCache.length; i < n; i++) updateCache[i].update(); }; Skeleton.prototype.setToSetupPose = function() { this.setBonesToSetupPose(); this.setSlotsToSetupPose(); }; Skeleton.prototype.setBonesToSetupPose = function() { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) bones[i].setToSetupPose(); var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) { var constraint = ikConstraints[i]; constraint.mix = constraint.data.mix; constraint.softness = constraint.data.softness; constraint.bendDirection = constraint.data.bendDirection; constraint.compress = constraint.data.compress; constraint.stretch = constraint.data.stretch; } var transformConstraints = this.transformConstraints; for (var i = 0, n = transformConstraints.length; i < n; i++) { var constraint = transformConstraints[i]; var data = constraint.data; constraint.rotateMix = data.rotateMix; constraint.translateMix = data.translateMix; constraint.scaleMix = data.scaleMix; constraint.shearMix = data.shearMix; } var pathConstraints = this.pathConstraints; for (var i = 0, n = pathConstraints.length; i < n; i++) { var constraint = pathConstraints[i]; var data = constraint.data; constraint.position = data.position; constraint.spacing = data.spacing; constraint.rotateMix = data.rotateMix; constraint.translateMix = data.translateMix; } }; Skeleton.prototype.setSlotsToSetupPose = function() { var slots = this.slots; spine.Utils.arrayCopy(slots, 0, this.drawOrder, 0, slots.length); for (var i = 0, n = slots.length; i < n; i++) slots[i].setToSetupPose(); }; Skeleton.prototype.getRootBone = function() { if (0 == this.bones.length) return null; return this.bones[0]; }; Skeleton.prototype.findBone = function(boneName) { if (null == boneName) throw new Error("boneName cannot be null."); var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; if (bone.data.name == boneName) return bone; } return null; }; Skeleton.prototype.findBoneIndex = function(boneName) { if (null == boneName) throw new Error("boneName cannot be null."); var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].data.name == boneName) return i; return -1; }; Skeleton.prototype.findSlot = function(slotName) { if (null == slotName) throw new Error("slotName cannot be null."); var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) { var slot = slots[i]; if (slot.data.name == slotName) return slot; } return null; }; Skeleton.prototype.findSlotIndex = function(slotName) { if (null == slotName) throw new Error("slotName cannot be null."); var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].data.name == slotName) return i; return -1; }; Skeleton.prototype.setSkinByName = function(skinName) { var skin = this.data.findSkin(skinName); if (null == skin) throw new Error("Skin not found: " + skinName); this.setSkin(skin); }; Skeleton.prototype.setSkin = function(newSkin) { if (newSkin == this.skin) return; if (null != newSkin) if (null != this.skin) newSkin.attachAll(this, this.skin); else { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) { var slot = slots[i]; var name_1 = slot.data.attachmentName; if (null != name_1) { var attachment = newSkin.getAttachment(i, name_1); null != attachment && slot.setAttachment(attachment); } } } this.skin = newSkin; this.updateCache(); }; Skeleton.prototype.getAttachmentByName = function(slotName, attachmentName) { return this.getAttachment(this.data.findSlotIndex(slotName), attachmentName); }; Skeleton.prototype.getAttachment = function(slotIndex, attachmentName) { if (null == attachmentName) throw new Error("attachmentName cannot be null."); if (null != this.skin) { var attachment = this.skin.getAttachment(slotIndex, attachmentName); if (null != attachment) return attachment; } if (null != this.data.defaultSkin) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName); return null; }; Skeleton.prototype.setAttachment = function(slotName, attachmentName) { if (null == slotName) throw new Error("slotName cannot be null."); var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) { var slot = slots[i]; if (slot.data.name == slotName) { var attachment = null; if (null != attachmentName) { attachment = this.getAttachment(i, attachmentName); if (null == attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName); } slot.setAttachment(attachment); return; } } throw new Error("Slot not found: " + slotName); }; Skeleton.prototype.findIkConstraint = function(constraintName) { if (null == constraintName) throw new Error("constraintName cannot be null."); var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) { var ikConstraint = ikConstraints[i]; if (ikConstraint.data.name == constraintName) return ikConstraint; } return null; }; Skeleton.prototype.findTransformConstraint = function(constraintName) { if (null == constraintName) throw new Error("constraintName cannot be null."); var transformConstraints = this.transformConstraints; for (var i = 0, n = transformConstraints.length; i < n; i++) { var constraint = transformConstraints[i]; if (constraint.data.name == constraintName) return constraint; } return null; }; Skeleton.prototype.findPathConstraint = function(constraintName) { if (null == constraintName) throw new Error("constraintName cannot be null."); var pathConstraints = this.pathConstraints; for (var i = 0, n = pathConstraints.length; i < n; i++) { var constraint = pathConstraints[i]; if (constraint.data.name == constraintName) return constraint; } return null; }; Skeleton.prototype.getBounds = function(offset, size, temp) { void 0 === temp && (temp = new Array(2)); if (null == offset) throw new Error("offset cannot be null."); if (null == size) throw new Error("size cannot be null."); var drawOrder = this.drawOrder; var minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY; for (var i = 0, n = drawOrder.length; i < n; i++) { var slot = drawOrder[i]; if (!slot.bone.active) continue; var verticesLength = 0; var vertices = null; var attachment = slot.getAttachment(); if (attachment instanceof spine.RegionAttachment) { verticesLength = 8; vertices = spine.Utils.setArraySize(temp, verticesLength, 0); attachment.computeWorldVertices(slot.bone, vertices, 0, 2); } else if (attachment instanceof spine.MeshAttachment) { var mesh = attachment; verticesLength = mesh.worldVerticesLength; vertices = spine.Utils.setArraySize(temp, verticesLength, 0); mesh.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2); } if (null != vertices) for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) { var x = vertices[ii], y = vertices[ii + 1]; minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } } offset.set(minX, minY); size.set(maxX - minX, maxY - minY); }; Skeleton.prototype.update = function(delta) { this.time += delta; }; return Skeleton; })(); spine.Skeleton = Skeleton; })(spine || (spine = {})); var spine; (function(spine) { var SkeletonBinary = (function() { function SkeletonBinary(attachmentLoader) { this.scale = 1; this.linkedMeshes = new Array(); this.attachmentLoader = attachmentLoader; } SkeletonBinary.prototype.readSkeletonData = function(binary) { var scale = this.scale; var skeletonData = new spine.SkeletonData(); skeletonData.name = ""; var input = new BinaryInput(binary); skeletonData.hash = input.readString(); skeletonData.version = input.readString(); skeletonData.x = input.readFloat(); skeletonData.y = input.readFloat(); skeletonData.width = input.readFloat(); skeletonData.height = input.readFloat(); var nonessential = input.readBoolean(); if (nonessential) { skeletonData.fps = input.readFloat(); skeletonData.imagesPath = input.readString(); skeletonData.audioPath = input.readString(); } var n = 0; n = input.readInt(true); for (var i = 0; i < n; i++) input.strings.push(input.readString()); n = input.readInt(true); for (var i = 0; i < n; i++) { var name_2 = input.readString(); var parent_2 = 0 == i ? null : skeletonData.bones[input.readInt(true)]; var data = new spine.BoneData(i, name_2, parent_2); data.rotation = input.readFloat(); data.x = input.readFloat() * scale; data.y = input.readFloat() * scale; data.scaleX = input.readFloat(); data.scaleY = input.readFloat(); data.shearX = input.readFloat(); data.shearY = input.readFloat(); data.length = input.readFloat() * scale; data.transformMode = SkeletonBinary.TransformModeValues[input.readInt(true)]; data.skinRequired = input.readBoolean(); nonessential && spine.Color.rgba8888ToColor(data.color, input.readInt32()); skeletonData.bones.push(data); } n = input.readInt(true); for (var i = 0; i < n; i++) { var slotName = input.readString(); var boneData = skeletonData.bones[input.readInt(true)]; var data = new spine.SlotData(i, slotName, boneData); spine.Color.rgba8888ToColor(data.color, input.readInt32()); var darkColor = input.readInt32(); -1 != darkColor && spine.Color.rgb888ToColor(data.darkColor = new spine.Color(), darkColor); data.attachmentName = input.readStringRef(); data.blendMode = SkeletonBinary.BlendModeValues[input.readInt(true)]; skeletonData.slots.push(data); } n = input.readInt(true); for (var i = 0, nn = void 0; i < n; i++) { var data = new spine.IkConstraintData(input.readString()); data.order = input.readInt(true); data.skinRequired = input.readBoolean(); nn = input.readInt(true); for (var ii = 0; ii < nn; ii++) data.bones.push(skeletonData.bones[input.readInt(true)]); data.target = skeletonData.bones[input.readInt(true)]; data.mix = input.readFloat(); data.softness = input.readFloat() * scale; data.bendDirection = input.readByte(); data.compress = input.readBoolean(); data.stretch = input.readBoolean(); data.uniform = input.readBoolean(); skeletonData.ikConstraints.push(data); } n = input.readInt(true); for (var i = 0, nn = void 0; i < n; i++) { var data = new spine.TransformConstraintData(input.readString()); data.order = input.readInt(true); data.skinRequired = input.readBoolean(); nn = input.readInt(true); for (var ii = 0; ii < nn; ii++) data.bones.push(skeletonData.bones[input.readInt(true)]); data.target = skeletonData.bones[input.readInt(true)]; data.local = input.readBoolean(); data.relative = input.readBoolean(); data.offsetRotation = input.readFloat(); data.offsetX = input.readFloat() * scale; data.offsetY = input.readFloat() * scale; data.offsetScaleX = input.readFloat(); data.offsetScaleY = input.readFloat(); data.offsetShearY = input.readFloat(); data.rotateMix = input.readFloat(); data.translateMix = input.readFloat(); data.scaleMix = input.readFloat(); data.shearMix = input.readFloat(); skeletonData.transformConstraints.push(data); } n = input.readInt(true); for (var i = 0, nn = void 0; i < n; i++) { var data = new spine.PathConstraintData(input.readString()); data.order = input.readInt(true); data.skinRequired = input.readBoolean(); nn = input.readInt(true); for (var ii = 0; ii < nn; ii++) data.bones.push(skeletonData.bones[input.readInt(true)]); data.target = skeletonData.slots[input.readInt(true)]; data.positionMode = SkeletonBinary.PositionModeValues[input.readInt(true)]; data.spacingMode = SkeletonBinary.SpacingModeValues[input.readInt(true)]; data.rotateMode = SkeletonBinary.RotateModeValues[input.readInt(true)]; data.offsetRotation = input.readFloat(); data.position = input.readFloat(); data.positionMode == spine.PositionMode.Fixed && (data.position *= scale); data.spacing = input.readFloat(); data.spacingMode != spine.SpacingMode.Length && data.spacingMode != spine.SpacingMode.Fixed || (data.spacing *= scale); data.rotateMix = input.readFloat(); data.translateMix = input.readFloat(); skeletonData.pathConstraints.push(data); } var defaultSkin = this.readSkin(input, skeletonData, true, nonessential); if (null != defaultSkin) { skeletonData.defaultSkin = defaultSkin; skeletonData.skins.push(defaultSkin); } var i = skeletonData.skins.length; spine.Utils.setArraySize(skeletonData.skins, n = i + input.readInt(true)); for (;i < n; i++) skeletonData.skins[i] = this.readSkin(input, skeletonData, false, nonessential); n = this.linkedMeshes.length; for (var i = 0; i < n; i++) { var linkedMesh = this.linkedMeshes[i]; var skin = null == linkedMesh.skin ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin); if (null == skin) throw new Error("Skin not found: " + linkedMesh.skin); var parent_3 = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent); if (null == parent_3) throw new Error("Parent mesh not found: " + linkedMesh.parent); linkedMesh.mesh.deformAttachment = linkedMesh.inheritDeform ? parent_3 : linkedMesh.mesh; linkedMesh.mesh.setParentMesh(parent_3); linkedMesh.mesh.updateUVs(); } this.linkedMeshes.length = 0; n = input.readInt(true); for (var i = 0; i < n; i++) { var data = new spine.EventData(input.readStringRef()); data.intValue = input.readInt(false); data.floatValue = input.readFloat(); data.stringValue = input.readString(); data.audioPath = input.readString(); if (null != data.audioPath) { data.volume = input.readFloat(); data.balance = input.readFloat(); } skeletonData.events.push(data); } n = input.readInt(true); for (var i = 0; i < n; i++) skeletonData.animations.push(this.readAnimation(input, input.readString(), skeletonData)); return skeletonData; }; SkeletonBinary.prototype.readSkin = function(input, skeletonData, defaultSkin, nonessential) { var skin = null; var slotCount = 0; if (defaultSkin) { slotCount = input.readInt(true); if (0 == slotCount) return null; skin = new spine.Skin("default"); } else { skin = new spine.Skin(input.readStringRef()); skin.bones.length = input.readInt(true); for (var i = 0, n = skin.bones.length; i < n; i++) skin.bones[i] = skeletonData.bones[input.readInt(true)]; for (var i = 0, n = input.readInt(true); i < n; i++) skin.constraints.push(skeletonData.ikConstraints[input.readInt(true)]); for (var i = 0, n = input.readInt(true); i < n; i++) skin.constraints.push(skeletonData.transformConstraints[input.readInt(true)]); for (var i = 0, n = input.readInt(true); i < n; i++) skin.constraints.push(skeletonData.pathConstraints[input.readInt(true)]); slotCount = input.readInt(true); } for (var i = 0; i < slotCount; i++) { var slotIndex = input.readInt(true); for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) { var name_3 = input.readStringRef(); var attachment = this.readAttachment(input, skeletonData, skin, slotIndex, name_3, nonessential); null != attachment && skin.setAttachment(slotIndex, name_3, attachment); } } return skin; }; SkeletonBinary.prototype.readAttachment = function(input, skeletonData, skin, slotIndex, attachmentName, nonessential) { var scale = this.scale; var name = input.readStringRef(); null == name && (name = attachmentName); var typeIndex = input.readByte(); var type = SkeletonBinary.AttachmentTypeValues[typeIndex]; switch (type) { case spine.AttachmentType.Region: var path = input.readStringRef(); var rotation = input.readFloat(); var x = input.readFloat(); var y = input.readFloat(); var scaleX = input.readFloat(); var scaleY = input.readFloat(); var width = input.readFloat(); var height = input.readFloat(); var color = input.readInt32(); null == path && (path = name); var region = this.attachmentLoader.newRegionAttachment(skin, name, path); if (null == region) return null; region.path = path; region.x = x * scale; region.y = y * scale; region.scaleX = scaleX; region.scaleY = scaleY; region.rotation = rotation; region.width = width * scale; region.height = height * scale; spine.Color.rgba8888ToColor(region.color, color); region.updateOffset(); return region; case spine.AttachmentType.BoundingBox: var vertexCount = input.readInt(true); var vertices = this.readVertices(input, vertexCount); var color = nonessential ? input.readInt32() : 0; var box = this.attachmentLoader.newBoundingBoxAttachment(skin, name); if (null == box) return null; box.worldVerticesLength = vertexCount << 1; box.vertices = vertices.vertices; box.bones = vertices.bones; nonessential && spine.Color.rgba8888ToColor(box.color, color); return box; case spine.AttachmentType.Mesh: var path = input.readStringRef(); var color = input.readInt32(); var vertexCount = input.readInt(true); var uvs = this.readFloatArray(input, vertexCount << 1, 1); var triangles = this.readShortArray(input); var vertices = this.readVertices(input, vertexCount); var hullLength = input.readInt(true); var edges = null; var width = 0, height = 0; if (nonessential) { edges = this.readShortArray(input); width = input.readFloat(); height = input.readFloat(); } null == path && (path = name); var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (null == mesh) return null; mesh.path = path; spine.Color.rgba8888ToColor(mesh.color, color); mesh.bones = vertices.bones; mesh.vertices = vertices.vertices; mesh.worldVerticesLength = vertexCount << 1; mesh.triangles = triangles; mesh.regionUVs = uvs; mesh.updateUVs(); mesh.hullLength = hullLength << 1; if (nonessential) { mesh.edges = edges; mesh.width = width * scale; mesh.height = height * scale; } return mesh; case spine.AttachmentType.LinkedMesh: var path = input.readStringRef(); var color = input.readInt32(); var skinName = input.readStringRef(); var parent_4 = input.readStringRef(); var inheritDeform = input.readBoolean(); var width = 0, height = 0; if (nonessential) { width = input.readFloat(); height = input.readFloat(); } null == path && (path = name); var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (null == mesh) return null; mesh.path = path; spine.Color.rgba8888ToColor(mesh.color, color); if (nonessential) { mesh.width = width * scale; mesh.height = height * scale; } this.linkedMeshes.push(new LinkedMesh(mesh, skinName, slotIndex, parent_4, inheritDeform)); return mesh; case spine.AttachmentType.Path: var closed_1 = input.readBoolean(); var constantSpeed = input.readBoolean(); var vertexCount = input.readInt(true); var vertices = this.readVertices(input, vertexCount); var lengths = spine.Utils.newArray(vertexCount / 3, 0); for (var i = 0, n = lengths.length; i < n; i++) lengths[i] = input.readFloat() * scale; var color = nonessential ? input.readInt32() : 0; var path = this.attachmentLoader.newPathAttachment(skin, name); if (null == path) return null; path.closed = closed_1; path.constantSpeed = constantSpeed; path.worldVerticesLength = vertexCount << 1; path.vertices = vertices.vertices; path.bones = vertices.bones; path.lengths = lengths; nonessential && spine.Color.rgba8888ToColor(path.color, color); return path; case spine.AttachmentType.Point: var rotation = input.readFloat(); var x = input.readFloat(); var y = input.readFloat(); var color = nonessential ? input.readInt32() : 0; var point = this.attachmentLoader.newPointAttachment(skin, name); if (null == point) return null; point.x = x * scale; point.y = y * scale; point.rotation = rotation; nonessential && spine.Color.rgba8888ToColor(point.color, color); return point; case spine.AttachmentType.Clipping: var endSlotIndex = input.readInt(true); var vertexCount = input.readInt(true); var vertices = this.readVertices(input, vertexCount); var color = nonessential ? input.readInt32() : 0; var clip = this.attachmentLoader.newClippingAttachment(skin, name); if (null == clip) return null; clip.endSlot = skeletonData.slots[endSlotIndex]; clip.worldVerticesLength = vertexCount << 1; clip.vertices = vertices.vertices; clip.bones = vertices.bones; nonessential && spine.Color.rgba8888ToColor(clip.color, color); return clip; } return null; }; SkeletonBinary.prototype.readVertices = function(input, vertexCount) { var verticesLength = vertexCount << 1; var vertices = new Vertices(); var scale = this.scale; if (!input.readBoolean()) { vertices.vertices = this.readFloatArray(input, verticesLength, scale); return vertices; } var weights = new Array(); var bonesArray = new Array(); for (var i = 0; i < vertexCount; i++) { var boneCount = input.readInt(true); bonesArray.push(boneCount); for (var ii = 0; ii < boneCount; ii++) { bonesArray.push(input.readInt(true)); weights.push(input.readFloat() * scale); weights.push(input.readFloat() * scale); weights.push(input.readFloat()); } } vertices.vertices = spine.Utils.toFloatArray(weights); vertices.bones = bonesArray; return vertices; }; SkeletonBinary.prototype.readFloatArray = function(input, n, scale) { var array = new Array(n); if (1 == scale) for (var i = 0; i < n; i++) array[i] = input.readFloat(); else for (var i = 0; i < n; i++) array[i] = input.readFloat() * scale; return array; }; SkeletonBinary.prototype.readShortArray = function(input) { var n = input.readInt(true); var array = new Array(n); for (var i = 0; i < n; i++) array[i] = input.readShort(); return array; }; SkeletonBinary.prototype.readAnimation = function(input, name, skeletonData) { var timelines = new Array(); var scale = this.scale; var duration = 0; var tempColor1 = new spine.Color(); var tempColor2 = new spine.Color(); for (var i = 0, n = input.readInt(true); i < n; i++) { var slotIndex = input.readInt(true); for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) { var timelineType = input.readByte(); var frameCount = input.readInt(true); switch (timelineType) { case SkeletonBinary.SLOT_ATTACHMENT: var timeline = new spine.AttachmentTimeline(frameCount); timeline.slotIndex = slotIndex; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) timeline.setFrame(frameIndex, input.readFloat(), input.readStringRef()); timelines.push(timeline); duration = Math.max(duration, timeline.frames[frameCount - 1]); break; case SkeletonBinary.SLOT_COLOR: var timeline = new spine.ColorTimeline(frameCount); timeline.slotIndex = slotIndex; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { var time = input.readFloat(); spine.Color.rgba8888ToColor(tempColor1, input.readInt32()); timeline.setFrame(frameIndex, time, tempColor1.r, tempColor1.g, tempColor1.b, tempColor1.a); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.ColorTimeline.ENTRIES]); break; case SkeletonBinary.SLOT_TWO_COLOR: var timeline = new spine.TwoColorTimeline(frameCount); timeline.slotIndex = slotIndex; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { var time = input.readFloat(); spine.Color.rgba8888ToColor(tempColor1, input.readInt32()); spine.Color.rgb888ToColor(tempColor2, input.readInt32()); timeline.setFrame(frameIndex, time, tempColor1.r, tempColor1.g, tempColor1.b, tempColor1.a, tempColor2.r, tempColor2.g, tempColor2.b); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.TwoColorTimeline.ENTRIES]); } } } for (var i = 0, n = input.readInt(true); i < n; i++) { var boneIndex = input.readInt(true); for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) { var timelineType = input.readByte(); var frameCount = input.readInt(true); switch (timelineType) { case SkeletonBinary.BONE_ROTATE: var timeline = new spine.RotateTimeline(frameCount); timeline.boneIndex = boneIndex; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.setFrame(frameIndex, input.readFloat(), input.readFloat()); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.RotateTimeline.ENTRIES]); break; case SkeletonBinary.BONE_TRANSLATE: case SkeletonBinary.BONE_SCALE: case SkeletonBinary.BONE_SHEAR: var timeline = void 0; var timelineScale = 1; if (timelineType == SkeletonBinary.BONE_SCALE) timeline = new spine.ScaleTimeline(frameCount); else if (timelineType == SkeletonBinary.BONE_SHEAR) timeline = new spine.ShearTimeline(frameCount); else { timeline = new spine.TranslateTimeline(frameCount); timelineScale = scale; } timeline.boneIndex = boneIndex; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.setFrame(frameIndex, input.readFloat(), input.readFloat() * timelineScale, input.readFloat() * timelineScale); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.TranslateTimeline.ENTRIES]); } } } for (var i = 0, n = input.readInt(true); i < n; i++) { var index = input.readInt(true); var frameCount = input.readInt(true); var timeline = new spine.IkConstraintTimeline(frameCount); timeline.ikConstraintIndex = index; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.setFrame(frameIndex, input.readFloat(), input.readFloat(), input.readFloat() * scale, input.readByte(), input.readBoolean(), input.readBoolean()); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.IkConstraintTimeline.ENTRIES]); } for (var i = 0, n = input.readInt(true); i < n; i++) { var index = input.readInt(true); var frameCount = input.readInt(true); var timeline = new spine.TransformConstraintTimeline(frameCount); timeline.transformConstraintIndex = index; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.setFrame(frameIndex, input.readFloat(), input.readFloat(), input.readFloat(), input.readFloat(), input.readFloat()); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.TransformConstraintTimeline.ENTRIES]); } for (var i = 0, n = input.readInt(true); i < n; i++) { var index = input.readInt(true); var data = skeletonData.pathConstraints[index]; for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) { var timelineType = input.readByte(); var frameCount = input.readInt(true); switch (timelineType) { case SkeletonBinary.PATH_POSITION: case SkeletonBinary.PATH_SPACING: var timeline = void 0; var timelineScale = 1; if (timelineType == SkeletonBinary.PATH_SPACING) { timeline = new spine.PathConstraintSpacingTimeline(frameCount); data.spacingMode != spine.SpacingMode.Length && data.spacingMode != spine.SpacingMode.Fixed || (timelineScale = scale); } else { timeline = new spine.PathConstraintPositionTimeline(frameCount); data.positionMode == spine.PositionMode.Fixed && (timelineScale = scale); } timeline.pathConstraintIndex = index; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.setFrame(frameIndex, input.readFloat(), input.readFloat() * timelineScale); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.PathConstraintPositionTimeline.ENTRIES]); break; case SkeletonBinary.PATH_MIX: var timeline = new spine.PathConstraintMixTimeline(frameCount); timeline.pathConstraintIndex = index; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.setFrame(frameIndex, input.readFloat(), input.readFloat(), input.readFloat()); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(frameCount - 1) * spine.PathConstraintMixTimeline.ENTRIES]); } } } for (var i = 0, n = input.readInt(true); i < n; i++) { var skin = skeletonData.skins[input.readInt(true)]; for (var ii = 0, nn = input.readInt(true); ii < nn; ii++) { var slotIndex = input.readInt(true); for (var iii = 0, nnn = input.readInt(true); iii < nnn; iii++) { var attachment = skin.getAttachment(slotIndex, input.readStringRef()); var weighted = null != attachment.bones; var vertices = attachment.vertices; var deformLength = weighted ? vertices.length / 3 * 2 : vertices.length; var frameCount = input.readInt(true); var timeline = new spine.DeformTimeline(frameCount); timeline.slotIndex = slotIndex; timeline.attachment = attachment; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { var time = input.readFloat(); var deform = void 0; var end = input.readInt(true); if (0 == end) deform = weighted ? spine.Utils.newFloatArray(deformLength) : vertices; else { deform = spine.Utils.newFloatArray(deformLength); var start = input.readInt(true); end += start; if (1 == scale) for (var v = start; v < end; v++) deform[v] = input.readFloat(); else for (var v = start; v < end; v++) deform[v] = input.readFloat() * scale; if (!weighted) for (var v = 0, vn = deform.length; v < vn; v++) deform[v] += vertices[v]; } timeline.setFrame(frameIndex, time, deform); frameIndex < frameCount - 1 && this.readCurve(input, frameIndex, timeline); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[frameCount - 1]); } } } var drawOrderCount = input.readInt(true); if (drawOrderCount > 0) { var timeline = new spine.DrawOrderTimeline(drawOrderCount); var slotCount = skeletonData.slots.length; for (var i = 0; i < drawOrderCount; i++) { var time = input.readFloat(); var offsetCount = input.readInt(true); var drawOrder = spine.Utils.newArray(slotCount, 0); for (var ii = slotCount - 1; ii >= 0; ii--) drawOrder[ii] = -1; var unchanged = spine.Utils.newArray(slotCount - offsetCount, 0); var originalIndex = 0, unchangedIndex = 0; for (var ii = 0; ii < offsetCount; ii++) { var slotIndex = input.readInt(true); while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; drawOrder[originalIndex + input.readInt(true)] = originalIndex++; } while (originalIndex < slotCount) unchanged[unchangedIndex++] = originalIndex++; for (var ii = slotCount - 1; ii >= 0; ii--) -1 == drawOrder[ii] && (drawOrder[ii] = unchanged[--unchangedIndex]); timeline.setFrame(i, time, drawOrder); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[drawOrderCount - 1]); } var eventCount = input.readInt(true); if (eventCount > 0) { var timeline = new spine.EventTimeline(eventCount); for (var i = 0; i < eventCount; i++) { var time = input.readFloat(); var eventData = skeletonData.events[input.readInt(true)]; var event_4 = new spine.Event(time, eventData); event_4.intValue = input.readInt(false); event_4.floatValue = input.readFloat(); event_4.stringValue = input.readBoolean() ? input.readString() : eventData.stringValue; if (null != event_4.data.audioPath) { event_4.volume = input.readFloat(); event_4.balance = input.readFloat(); } timeline.setFrame(i, event_4); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[eventCount - 1]); } return new spine.Animation(name, timelines, duration); }; SkeletonBinary.prototype.readCurve = function(input, frameIndex, timeline) { switch (input.readByte()) { case SkeletonBinary.CURVE_STEPPED: timeline.setStepped(frameIndex); break; case SkeletonBinary.CURVE_BEZIER: this.setCurve(timeline, frameIndex, input.readFloat(), input.readFloat(), input.readFloat(), input.readFloat()); } }; SkeletonBinary.prototype.setCurve = function(timeline, frameIndex, cx1, cy1, cx2, cy2) { timeline.setCurve(frameIndex, cx1, cy1, cx2, cy2); }; SkeletonBinary.AttachmentTypeValues = [ 0, 1, 2, 3, 4, 5, 6 ]; SkeletonBinary.TransformModeValues = [ spine.TransformMode.Normal, spine.TransformMode.OnlyTranslation, spine.TransformMode.NoRotationOrReflection, spine.TransformMode.NoScale, spine.TransformMode.NoScaleOrReflection ]; SkeletonBinary.PositionModeValues = [ spine.PositionMode.Fixed, spine.PositionMode.Percent ]; SkeletonBinary.SpacingModeValues = [ spine.SpacingMode.Length, spine.SpacingMode.Fixed, spine.SpacingMode.Percent ]; SkeletonBinary.RotateModeValues = [ spine.RotateMode.Tangent, spine.RotateMode.Chain, spine.RotateMode.ChainScale ]; SkeletonBinary.BlendModeValues = [ spine.BlendMode.Normal, spine.BlendMode.Additive, spine.BlendMode.Multiply, spine.BlendMode.Screen ]; SkeletonBinary.BONE_ROTATE = 0; SkeletonBinary.BONE_TRANSLATE = 1; SkeletonBinary.BONE_SCALE = 2; SkeletonBinary.BONE_SHEAR = 3; SkeletonBinary.SLOT_ATTACHMENT = 0; SkeletonBinary.SLOT_COLOR = 1; SkeletonBinary.SLOT_TWO_COLOR = 2; SkeletonBinary.PATH_POSITION = 0; SkeletonBinary.PATH_SPACING = 1; SkeletonBinary.PATH_MIX = 2; SkeletonBinary.CURVE_LINEAR = 0; SkeletonBinary.CURVE_STEPPED = 1; SkeletonBinary.CURVE_BEZIER = 2; return SkeletonBinary; })(); spine.SkeletonBinary = SkeletonBinary; var BinaryInput = (function() { function BinaryInput(data, strings, index, buffer) { void 0 === strings && (strings = new Array()); void 0 === index && (index = 0); void 0 === buffer && (buffer = new DataView(data.buffer)); this.strings = strings; this.index = index; this.buffer = buffer; } BinaryInput.prototype.readByte = function() { return this.buffer.getInt8(this.index++); }; BinaryInput.prototype.readShort = function() { var value = this.buffer.getInt16(this.index); this.index += 2; return value; }; BinaryInput.prototype.readInt32 = function() { var value = this.buffer.getInt32(this.index); this.index += 4; return value; }; BinaryInput.prototype.readInt = function(optimizePositive) { var b = this.readByte(); var result = 127 & b; if (0 != (128 & b)) { b = this.readByte(); result |= (127 & b) << 7; if (0 != (128 & b)) { b = this.readByte(); result |= (127 & b) << 14; if (0 != (128 & b)) { b = this.readByte(); result |= (127 & b) << 21; if (0 != (128 & b)) { b = this.readByte(); result |= (127 & b) << 28; } } } } return optimizePositive ? result : result >>> 1 ^ -(1 & result); }; BinaryInput.prototype.readStringRef = function() { var index = this.readInt(true); return 0 == index ? null : this.strings[index - 1]; }; BinaryInput.prototype.readString = function() { var byteCount = this.readInt(true); switch (byteCount) { case 0: return null; case 1: return ""; } byteCount--; var chars = ""; var charCount = 0; for (var i = 0; i < byteCount; ) { var b = this.readByte(); switch (b >> 4) { case 12: case 13: chars += String.fromCharCode((31 & b) << 6 | 63 & this.readByte()); i += 2; break; case 14: chars += String.fromCharCode((15 & b) << 12 | (63 & this.readByte()) << 6 | 63 & this.readByte()); i += 3; break; default: chars += String.fromCharCode(b); i++; } } return chars; }; BinaryInput.prototype.readFloat = function() { var value = this.buffer.getFloat32(this.index); this.index += 4; return value; }; BinaryInput.prototype.readBoolean = function() { return 0 != this.readByte(); }; return BinaryInput; })(); var LinkedMesh = (function() { function LinkedMesh(mesh, skin, slotIndex, parent, inheritDeform) { this.mesh = mesh; this.skin = skin; this.slotIndex = slotIndex; this.parent = parent; this.inheritDeform = inheritDeform; } return LinkedMesh; })(); var Vertices = (function() { function Vertices(bones, vertices) { void 0 === bones && (bones = null); void 0 === vertices && (vertices = null); this.bones = bones; this.vertices = vertices; } return Vertices; })(); })(spine || (spine = {})); var spine; (function(spine) { var SkeletonBounds = (function() { function SkeletonBounds() { this.minX = 0; this.minY = 0; this.maxX = 0; this.maxY = 0; this.boundingBoxes = new Array(); this.polygons = new Array(); this.polygonPool = new spine.Pool(function() { return spine.Utils.newFloatArray(16); }); } SkeletonBounds.prototype.update = function(skeleton, updateAabb) { if (null == skeleton) throw new Error("skeleton cannot be null."); var boundingBoxes = this.boundingBoxes; var polygons = this.polygons; var polygonPool = this.polygonPool; var slots = skeleton.slots; var slotCount = slots.length; boundingBoxes.length = 0; polygonPool.freeAll(polygons); polygons.length = 0; for (var i = 0; i < slotCount; i++) { var slot = slots[i]; if (!slot.bone.active) continue; var attachment = slot.getAttachment(); if (attachment instanceof spine.BoundingBoxAttachment) { var boundingBox = attachment; boundingBoxes.push(boundingBox); var polygon = polygonPool.obtain(); polygon.length != boundingBox.worldVerticesLength && (polygon = spine.Utils.newFloatArray(boundingBox.worldVerticesLength)); polygons.push(polygon); boundingBox.computeWorldVertices(slot, 0, boundingBox.worldVerticesLength, polygon, 0, 2); } } if (updateAabb) this.aabbCompute(); else { this.minX = Number.POSITIVE_INFINITY; this.minY = Number.POSITIVE_INFINITY; this.maxX = Number.NEGATIVE_INFINITY; this.maxY = Number.NEGATIVE_INFINITY; } }; SkeletonBounds.prototype.aabbCompute = function() { var minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY; var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) { var polygon = polygons[i]; var vertices = polygon; for (var ii = 0, nn = polygon.length; ii < nn; ii += 2) { var x = vertices[ii]; var y = vertices[ii + 1]; minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } } this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; }; SkeletonBounds.prototype.aabbContainsPoint = function(x, y) { return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY; }; SkeletonBounds.prototype.aabbIntersectsSegment = function(x1, y1, x2, y2) { var minX = this.minX; var minY = this.minY; var maxX = this.maxX; var maxY = this.maxY; if (x1 <= minX && x2 <= minX || y1 <= minY && y2 <= minY || x1 >= maxX && x2 >= maxX || y1 >= maxY && y2 >= maxY) return false; var m = (y2 - y1) / (x2 - x1); var y = m * (minX - x1) + y1; if (y > minY && y < maxY) return true; y = m * (maxX - x1) + y1; if (y > minY && y < maxY) return true; var x = (minY - y1) / m + x1; if (x > minX && x < maxX) return true; x = (maxY - y1) / m + x1; if (x > minX && x < maxX) return true; return false; }; SkeletonBounds.prototype.aabbIntersectsSkeleton = function(bounds) { return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY; }; SkeletonBounds.prototype.containsPoint = function(x, y) { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (this.containsPointPolygon(polygons[i], x, y)) return this.boundingBoxes[i]; return null; }; SkeletonBounds.prototype.containsPointPolygon = function(polygon, x, y) { var vertices = polygon; var nn = polygon.length; var prevIndex = nn - 2; var inside = false; for (var ii = 0; ii < nn; ii += 2) { var vertexY = vertices[ii + 1]; var prevY = vertices[prevIndex + 1]; if (vertexY < y && prevY >= y || prevY < y && vertexY >= y) { var vertexX = vertices[ii]; vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x && (inside = !inside); } prevIndex = ii; } return inside; }; SkeletonBounds.prototype.intersectsSegment = function(x1, y1, x2, y2) { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (this.intersectsSegmentPolygon(polygons[i], x1, y1, x2, y2)) return this.boundingBoxes[i]; return null; }; SkeletonBounds.prototype.intersectsSegmentPolygon = function(polygon, x1, y1, x2, y2) { var vertices = polygon; var nn = polygon.length; var width12 = x1 - x2, height12 = y1 - y2; var det1 = x1 * y2 - y1 * x2; var x3 = vertices[nn - 2], y3 = vertices[nn - 1]; for (var ii = 0; ii < nn; ii += 2) { var x4 = vertices[ii], y4 = vertices[ii + 1]; var det2 = x3 * y4 - y3 * x4; var width34 = x3 - x4, height34 = y3 - y4; var det3 = width12 * height34 - height12 * width34; var x = (det1 * width34 - width12 * det2) / det3; if ((x >= x3 && x <= x4 || x >= x4 && x <= x3) && (x >= x1 && x <= x2 || x >= x2 && x <= x1)) { var y = (det1 * height34 - height12 * det2) / det3; if ((y >= y3 && y <= y4 || y >= y4 && y <= y3) && (y >= y1 && y <= y2 || y >= y2 && y <= y1)) return true; } x3 = x4; y3 = y4; } return false; }; SkeletonBounds.prototype.getPolygon = function(boundingBox) { if (null == boundingBox) throw new Error("boundingBox cannot be null."); var index = this.boundingBoxes.indexOf(boundingBox); return -1 == index ? null : this.polygons[index]; }; SkeletonBounds.prototype.getWidth = function() { return this.maxX - this.minX; }; SkeletonBounds.prototype.getHeight = function() { return this.maxY - this.minY; }; return SkeletonBounds; })(); spine.SkeletonBounds = SkeletonBounds; })(spine || (spine = {})); var spine; (function(spine) { var SkeletonClipping = (function() { function SkeletonClipping() { this.triangulator = new spine.Triangulator(); this.clippingPolygon = new Array(); this.clipOutput = new Array(); this.clippedVertices = new Array(); this.clippedTriangles = new Array(); this.scratch = new Array(); } SkeletonClipping.prototype.clipStart = function(slot, clip) { if (null != this.clipAttachment) return 0; this.clipAttachment = clip; var n = clip.worldVerticesLength; var vertices = spine.Utils.setArraySize(this.clippingPolygon, n); clip.computeWorldVertices(slot, 0, n, vertices, 0, 2); var clippingPolygon = this.clippingPolygon; SkeletonClipping.makeClockwise(clippingPolygon); var clippingPolygons = this.clippingPolygons = this.triangulator.decompose(clippingPolygon, this.triangulator.triangulate(clippingPolygon)); for (var i = 0, n_1 = clippingPolygons.length; i < n_1; i++) { var polygon = clippingPolygons[i]; SkeletonClipping.makeClockwise(polygon); polygon.push(polygon[0]); polygon.push(polygon[1]); } return clippingPolygons.length; }; SkeletonClipping.prototype.clipEndWithSlot = function(slot) { null != this.clipAttachment && this.clipAttachment.endSlot == slot.data && this.clipEnd(); }; SkeletonClipping.prototype.clipEnd = function() { if (null == this.clipAttachment) return; this.clipAttachment = null; this.clippingPolygons = null; this.clippedVertices.length = 0; this.clippedTriangles.length = 0; this.clippingPolygon.length = 0; }; SkeletonClipping.prototype.isClipping = function() { return null != this.clipAttachment; }; SkeletonClipping.prototype.clipTriangles = function(vertices, verticesLength, triangles, trianglesLength, uvs, light, dark, twoColor, stride, originIndexOffset, originVertOffset, originUVSOffset) { var clipOutput = this.clipOutput, clippedVertices = this.clippedVertices; var clippedTriangles = this.clippedTriangles; var polygons = this.clippingPolygons; var polygonsCount = this.clippingPolygons.length; var vertexSize = twoColor ? 12 : 8; var index = 0; originIndexOffset = originIndexOffset || 0; originVertOffset = originVertOffset || 0; originUVSOffset = originUVSOffset || 0; clippedVertices.length = 0; clippedTriangles.length = 0; outer: for (var i = originIndexOffset, n = originIndexOffset + trianglesLength; i < n; i += 3) { var vertexOffset = triangles[i] * stride; var xyOffset = vertexOffset + originVertOffset; var uvOffset = vertexOffset + originUVSOffset; var x1 = vertices[xyOffset], y1 = vertices[xyOffset + 1]; var u1 = uvs[uvOffset], v1 = uvs[uvOffset + 1]; vertexOffset = triangles[i + 1] * stride; xyOffset = vertexOffset + originVertOffset; uvOffset = vertexOffset + originUVSOffset; var x2 = vertices[xyOffset], y2 = vertices[xyOffset + 1]; var u2 = uvs[uvOffset], v2 = uvs[uvOffset + 1]; vertexOffset = triangles[i + 2] * stride; xyOffset = vertexOffset + originVertOffset; uvOffset = vertexOffset + originUVSOffset; var x3 = vertices[xyOffset], y3 = vertices[xyOffset + 1]; var u3 = uvs[uvOffset], v3 = uvs[uvOffset + 1]; for (var p = 0; p < polygonsCount; p++) { var s = clippedVertices.length; if (!this.clip(x1, y1, x2, y2, x3, y3, polygons[p], clipOutput)) { var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + 3 * vertexSize); clippedVerticesItems[s] = x1; clippedVerticesItems[s + 1] = y1; clippedVerticesItems[s + 2] = light.r; clippedVerticesItems[s + 3] = light.g; clippedVerticesItems[s + 4] = light.b; clippedVerticesItems[s + 5] = light.a; if (twoColor) { clippedVerticesItems[s + 6] = u1; clippedVerticesItems[s + 7] = v1; clippedVerticesItems[s + 8] = dark.r; clippedVerticesItems[s + 9] = dark.g; clippedVerticesItems[s + 10] = dark.b; clippedVerticesItems[s + 11] = dark.a; clippedVerticesItems[s + 12] = x2; clippedVerticesItems[s + 13] = y2; clippedVerticesItems[s + 14] = light.r; clippedVerticesItems[s + 15] = light.g; clippedVerticesItems[s + 16] = light.b; clippedVerticesItems[s + 17] = light.a; clippedVerticesItems[s + 18] = u2; clippedVerticesItems[s + 19] = v2; clippedVerticesItems[s + 20] = dark.r; clippedVerticesItems[s + 21] = dark.g; clippedVerticesItems[s + 22] = dark.b; clippedVerticesItems[s + 23] = dark.a; clippedVerticesItems[s + 24] = x3; clippedVerticesItems[s + 25] = y3; clippedVerticesItems[s + 26] = light.r; clippedVerticesItems[s + 27] = light.g; clippedVerticesItems[s + 28] = light.b; clippedVerticesItems[s + 29] = light.a; clippedVerticesItems[s + 30] = u3; clippedVerticesItems[s + 31] = v3; clippedVerticesItems[s + 32] = dark.r; clippedVerticesItems[s + 33] = dark.g; clippedVerticesItems[s + 34] = dark.b; clippedVerticesItems[s + 35] = dark.a; } else { clippedVerticesItems[s + 6] = u1; clippedVerticesItems[s + 7] = v1; clippedVerticesItems[s + 8] = x2; clippedVerticesItems[s + 9] = y2; clippedVerticesItems[s + 10] = light.r; clippedVerticesItems[s + 11] = light.g; clippedVerticesItems[s + 12] = light.b; clippedVerticesItems[s + 13] = light.a; clippedVerticesItems[s + 14] = u2; clippedVerticesItems[s + 15] = v2; clippedVerticesItems[s + 16] = x3; clippedVerticesItems[s + 17] = y3; clippedVerticesItems[s + 18] = light.r; clippedVerticesItems[s + 19] = light.g; clippedVerticesItems[s + 20] = light.b; clippedVerticesItems[s + 21] = light.a; clippedVerticesItems[s + 22] = u3; clippedVerticesItems[s + 23] = v3; } s = clippedTriangles.length; var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3); clippedTrianglesItems[s] = index; clippedTrianglesItems[s + 1] = index + 1; clippedTrianglesItems[s + 2] = index + 2; index += 3; continue outer; } var clipOutputLength = clipOutput.length; if (0 == clipOutputLength) continue; var d0 = y2 - y3, d1 = x3 - x2, d2 = x1 - x3, d4 = y3 - y1; var d = 1 / (d0 * d2 + d1 * (y1 - y3)); var clipOutputCount = clipOutputLength >> 1; var clipOutputItems = this.clipOutput; var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + clipOutputCount * vertexSize); for (var ii = 0; ii < clipOutputLength; ii += 2) { var x = clipOutputItems[ii], y = clipOutputItems[ii + 1]; clippedVerticesItems[s] = x; clippedVerticesItems[s + 1] = y; clippedVerticesItems[s + 2] = light.r; clippedVerticesItems[s + 3] = light.g; clippedVerticesItems[s + 4] = light.b; clippedVerticesItems[s + 5] = light.a; var c0 = x - x3, c1 = y - y3; var a = (d0 * c0 + d1 * c1) * d; var b = (d4 * c0 + d2 * c1) * d; var c = 1 - a - b; clippedVerticesItems[s + 6] = u1 * a + u2 * b + u3 * c; clippedVerticesItems[s + 7] = v1 * a + v2 * b + v3 * c; if (twoColor) { clippedVerticesItems[s + 8] = dark.r; clippedVerticesItems[s + 9] = dark.g; clippedVerticesItems[s + 10] = dark.b; clippedVerticesItems[s + 11] = dark.a; } s += vertexSize; } s = clippedTriangles.length; var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3 * (clipOutputCount - 2)); clipOutputCount--; for (var ii = 1; ii < clipOutputCount; ii++) { clippedTrianglesItems[s] = index; clippedTrianglesItems[s + 1] = index + ii; clippedTrianglesItems[s + 2] = index + ii + 1; s += 3; } index += clipOutputCount + 1; } } }; SkeletonClipping.prototype.clip = function(x1, y1, x2, y2, x3, y3, clippingArea, output) { var originalOutput = output; var clipped = false; var input = null; if (clippingArea.length % 4 >= 2) { input = output; output = this.scratch; } else input = this.scratch; input.length = 0; input.push(x1); input.push(y1); input.push(x2); input.push(y2); input.push(x3); input.push(y3); input.push(x1); input.push(y1); output.length = 0; var clippingVertices = clippingArea; var clippingVerticesLast = clippingArea.length - 4; for (var i = 0; ;i += 2) { var edgeX = clippingVertices[i], edgeY = clippingVertices[i + 1]; var edgeX2 = clippingVertices[i + 2], edgeY2 = clippingVertices[i + 3]; var deltaX = edgeX - edgeX2, deltaY = edgeY - edgeY2; var inputVertices = input; var inputVerticesLength = input.length - 2, outputStart = output.length; for (var ii = 0; ii < inputVerticesLength; ii += 2) { var inputX = inputVertices[ii], inputY = inputVertices[ii + 1]; var inputX2 = inputVertices[ii + 2], inputY2 = inputVertices[ii + 3]; var side2 = deltaX * (inputY2 - edgeY2) - deltaY * (inputX2 - edgeX2) > 0; if (deltaX * (inputY - edgeY2) - deltaY * (inputX - edgeX2) > 0) { if (side2) { output.push(inputX2); output.push(inputY2); continue; } var c0 = inputY2 - inputY, c2 = inputX2 - inputX; var s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); if (Math.abs(s) > 1e-6) { var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; output.push(edgeX + (edgeX2 - edgeX) * ua); output.push(edgeY + (edgeY2 - edgeY) * ua); } else { output.push(edgeX); output.push(edgeY); } } else if (side2) { var c0 = inputY2 - inputY, c2 = inputX2 - inputX; var s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); if (Math.abs(s) > 1e-6) { var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; output.push(edgeX + (edgeX2 - edgeX) * ua); output.push(edgeY + (edgeY2 - edgeY) * ua); } else { output.push(edgeX); output.push(edgeY); } output.push(inputX2); output.push(inputY2); } clipped = true; } if (outputStart == output.length) { originalOutput.length = 0; return true; } output.push(output[0]); output.push(output[1]); if (i == clippingVerticesLast) break; var temp = output; output = input; output.length = 0; input = temp; } if (originalOutput != output) { originalOutput.length = 0; for (var i = 0, n = output.length - 2; i < n; i++) originalOutput[i] = output[i]; } else originalOutput.length = originalOutput.length - 2; return clipped; }; SkeletonClipping.makeClockwise = function(polygon) { var vertices = polygon; var verticeslength = polygon.length; var area = vertices[verticeslength - 2] * vertices[1] - vertices[0] * vertices[verticeslength - 1], p1x = 0, p1y = 0, p2x = 0, p2y = 0; for (var i = 0, n = verticeslength - 3; i < n; i += 2) { p1x = vertices[i]; p1y = vertices[i + 1]; p2x = vertices[i + 2]; p2y = vertices[i + 3]; area += p1x * p2y - p2x * p1y; } if (area < 0) return; for (var i = 0, lastX = verticeslength - 2, n = verticeslength >> 1; i < n; i += 2) { var x = vertices[i], y = vertices[i + 1]; var other = lastX - i; vertices[i] = vertices[other]; vertices[i + 1] = vertices[other + 1]; vertices[other] = x; vertices[other + 1] = y; } }; return SkeletonClipping; })(); spine.SkeletonClipping = SkeletonClipping; })(spine || (spine = {})); var spine; (function(spine) { var SkeletonData = (function() { function SkeletonData() { this.bones = new Array(); this.slots = new Array(); this.skins = new Array(); this.events = new Array(); this.animations = new Array(); this.ikConstraints = new Array(); this.transformConstraints = new Array(); this.pathConstraints = new Array(); this.fps = 0; } SkeletonData.prototype.findBone = function(boneName) { if (null == boneName) throw new Error("boneName cannot be null."); var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; if (bone.name == boneName) return bone; } return null; }; SkeletonData.prototype.findBoneIndex = function(boneName) { if (null == boneName) throw new Error("boneName cannot be null."); var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].name == boneName) return i; return -1; }; SkeletonData.prototype.findSlot = function(slotName) { if (null == slotName) throw new Error("slotName cannot be null."); var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) { var slot = slots[i]; if (slot.name == slotName) return slot; } return null; }; SkeletonData.prototype.findSlotIndex = function(slotName) { if (null == slotName) throw new Error("slotName cannot be null."); var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].name == slotName) return i; return -1; }; SkeletonData.prototype.findSkin = function(skinName) { if (null == skinName) throw new Error("skinName cannot be null."); var skins = this.skins; for (var i = 0, n = skins.length; i < n; i++) { var skin = skins[i]; if (skin.name == skinName) return skin; } return null; }; SkeletonData.prototype.findEvent = function(eventDataName) { if (null == eventDataName) throw new Error("eventDataName cannot be null."); var events = this.events; for (var i = 0, n = events.length; i < n; i++) { var event_5 = events[i]; if (event_5.name == eventDataName) return event_5; } return null; }; SkeletonData.prototype.findAnimation = function(animationName) { if (null == animationName) throw new Error("animationName cannot be null."); var animations = this.animations; for (var i = 0, n = animations.length; i < n; i++) { var animation = animations[i]; if (animation.name == animationName) return animation; } return null; }; SkeletonData.prototype.findIkConstraint = function(constraintName) { if (null == constraintName) throw new Error("constraintName cannot be null."); var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) { var constraint = ikConstraints[i]; if (constraint.name == constraintName) return constraint; } return null; }; SkeletonData.prototype.findTransformConstraint = function(constraintName) { if (null == constraintName) throw new Error("constraintName cannot be null."); var transformConstraints = this.transformConstraints; for (var i = 0, n = transformConstraints.length; i < n; i++) { var constraint = transformConstraints[i]; if (constraint.name == constraintName) return constraint; } return null; }; SkeletonData.prototype.findPathConstraint = function(constraintName) { if (null == constraintName) throw new Error("constraintName cannot be null."); var pathConstraints = this.pathConstraints; for (var i = 0, n = pathConstraints.length; i < n; i++) { var constraint = pathConstraints[i]; if (constraint.name == constraintName) return constraint; } return null; }; SkeletonData.prototype.findPathConstraintIndex = function(pathConstraintName) { if (null == pathConstraintName) throw new Error("pathConstraintName cannot be null."); var pathConstraints = this.pathConstraints; for (var i = 0, n = pathConstraints.length; i < n; i++) if (pathConstraints[i].name == pathConstraintName) return i; return -1; }; return SkeletonData; })(); spine.SkeletonData = SkeletonData; })(spine || (spine = {})); var spine; (function(spine) { var SkeletonJson = (function() { function SkeletonJson(attachmentLoader) { this.scale = 1; this.linkedMeshes = new Array(); this.attachmentLoader = attachmentLoader; } SkeletonJson.prototype.readSkeletonData = function(json) { var scale = this.scale; var skeletonData = new spine.SkeletonData(); var root = "string" === typeof json ? JSON.parse(json) : json; var skeletonMap = root.skeleton; if (null != skeletonMap) { skeletonData.hash = skeletonMap.hash; skeletonData.version = skeletonMap.spine; skeletonData.x = skeletonMap.x; skeletonData.y = skeletonMap.y; skeletonData.width = skeletonMap.width; skeletonData.height = skeletonMap.height; skeletonData.fps = skeletonMap.fps; skeletonData.imagesPath = skeletonMap.images; } if (root.bones) for (var i = 0; i < root.bones.length; i++) { var boneMap = root.bones[i]; var parent_5 = null; var parentName = this.getValue(boneMap, "parent", null); if (null != parentName) { parent_5 = skeletonData.findBone(parentName); if (null == parent_5) throw new Error("Parent bone not found: " + parentName); } var data = new spine.BoneData(skeletonData.bones.length, boneMap.name, parent_5); data.length = this.getValue(boneMap, "length", 0) * scale; data.x = this.getValue(boneMap, "x", 0) * scale; data.y = this.getValue(boneMap, "y", 0) * scale; data.rotation = this.getValue(boneMap, "rotation", 0); data.scaleX = this.getValue(boneMap, "scaleX", 1); data.scaleY = this.getValue(boneMap, "scaleY", 1); data.shearX = this.getValue(boneMap, "shearX", 0); data.shearY = this.getValue(boneMap, "shearY", 0); data.transformMode = SkeletonJson.transformModeFromString(this.getValue(boneMap, "transform", "normal")); data.skinRequired = this.getValue(boneMap, "skin", false); skeletonData.bones.push(data); } if (root.slots) for (var i = 0; i < root.slots.length; i++) { var slotMap = root.slots[i]; var slotName = slotMap.name; var boneName = slotMap.bone; var boneData = skeletonData.findBone(boneName); if (null == boneData) throw new Error("Slot bone not found: " + boneName); var data = new spine.SlotData(skeletonData.slots.length, slotName, boneData); var color = this.getValue(slotMap, "color", null); null != color && data.color.setFromString(color); var dark = this.getValue(slotMap, "dark", null); if (null != dark) { data.darkColor = new spine.Color(1, 1, 1, 1); data.darkColor.setFromString(dark); } data.attachmentName = this.getValue(slotMap, "attachment", null); data.blendMode = SkeletonJson.blendModeFromString(this.getValue(slotMap, "blend", "normal")); skeletonData.slots.push(data); } if (root.ik) for (var i = 0; i < root.ik.length; i++) { var constraintMap = root.ik[i]; var data = new spine.IkConstraintData(constraintMap.name); data.order = this.getValue(constraintMap, "order", 0); data.skinRequired = this.getValue(constraintMap, "skin", false); for (var j = 0; j < constraintMap.bones.length; j++) { var boneName = constraintMap.bones[j]; var bone = skeletonData.findBone(boneName); if (null == bone) throw new Error("IK bone not found: " + boneName); data.bones.push(bone); } var targetName = constraintMap.target; data.target = skeletonData.findBone(targetName); if (null == data.target) throw new Error("IK target bone not found: " + targetName); data.mix = this.getValue(constraintMap, "mix", 1); data.softness = this.getValue(constraintMap, "softness", 0) * scale; data.bendDirection = this.getValue(constraintMap, "bendPositive", true) ? 1 : -1; data.compress = this.getValue(constraintMap, "compress", false); data.stretch = this.getValue(constraintMap, "stretch", false); data.uniform = this.getValue(constraintMap, "uniform", false); skeletonData.ikConstraints.push(data); } if (root.transform) for (var i = 0; i < root.transform.length; i++) { var constraintMap = root.transform[i]; var data = new spine.TransformConstraintData(constraintMap.name); data.order = this.getValue(constraintMap, "order", 0); data.skinRequired = this.getValue(constraintMap, "skin", false); for (var j = 0; j < constraintMap.bones.length; j++) { var boneName = constraintMap.bones[j]; var bone = skeletonData.findBone(boneName); if (null == bone) throw new Error("Transform constraint bone not found: " + boneName); data.bones.push(bone); } var targetName = constraintMap.target; data.target = skeletonData.findBone(targetName); if (null == data.target) throw new Error("Transform constraint target bone not found: " + targetName); data.local = this.getValue(constraintMap, "local", false); data.relative = this.getValue(constraintMap, "relative", false); data.offsetRotation = this.getValue(constraintMap, "rotation", 0); data.offsetX = this.getValue(constraintMap, "x", 0) * scale; data.offsetY = this.getValue(constraintMap, "y", 0) * scale; data.offsetScaleX = this.getValue(constraintMap, "scaleX", 0); data.offsetScaleY = this.getValue(constraintMap, "scaleY", 0); data.offsetShearY = this.getValue(constraintMap, "shearY", 0); data.rotateMix = this.getValue(constraintMap, "rotateMix", 1); data.translateMix = this.getValue(constraintMap, "translateMix", 1); data.scaleMix = this.getValue(constraintMap, "scaleMix", 1); data.shearMix = this.getValue(constraintMap, "shearMix", 1); skeletonData.transformConstraints.push(data); } if (root.path) for (var i = 0; i < root.path.length; i++) { var constraintMap = root.path[i]; var data = new spine.PathConstraintData(constraintMap.name); data.order = this.getValue(constraintMap, "order", 0); data.skinRequired = this.getValue(constraintMap, "skin", false); for (var j = 0; j < constraintMap.bones.length; j++) { var boneName = constraintMap.bones[j]; var bone = skeletonData.findBone(boneName); if (null == bone) throw new Error("Transform constraint bone not found: " + boneName); data.bones.push(bone); } var targetName = constraintMap.target; data.target = skeletonData.findSlot(targetName); if (null == data.target) throw new Error("Path target slot not found: " + targetName); data.positionMode = SkeletonJson.positionModeFromString(this.getValue(constraintMap, "positionMode", "percent")); data.spacingMode = SkeletonJson.spacingModeFromString(this.getValue(constraintMap, "spacingMode", "length")); data.rotateMode = SkeletonJson.rotateModeFromString(this.getValue(constraintMap, "rotateMode", "tangent")); data.offsetRotation = this.getValue(constraintMap, "rotation", 0); data.position = this.getValue(constraintMap, "position", 0); data.positionMode == spine.PositionMode.Fixed && (data.position *= scale); data.spacing = this.getValue(constraintMap, "spacing", 0); data.spacingMode != spine.SpacingMode.Length && data.spacingMode != spine.SpacingMode.Fixed || (data.spacing *= scale); data.rotateMix = this.getValue(constraintMap, "rotateMix", 1); data.translateMix = this.getValue(constraintMap, "translateMix", 1); skeletonData.pathConstraints.push(data); } if (root.skins) { var skins = root.skins; var isArray = skins instanceof Array; if (!isArray) { var skinArr = []; for (var skinName in skins) skinArr.push({ name: skinName, attachments: skins[skinName] }); skins = skinArr; } for (var i = 0; i < skins.length; i++) { var skinMap = skins[i]; var skin = new spine.Skin(skinMap.name); if (skinMap.bones) for (var ii = 0; ii < skinMap.bones.length; ii++) { var bone = skeletonData.findBone(skinMap.bones[ii]); if (null == bone) throw new Error("Skin bone not found: " + skinMap.bones[i]); skin.bones.push(bone); } if (skinMap.ik) for (var ii = 0; ii < skinMap.ik.length; ii++) { var constraint = skeletonData.findIkConstraint(skinMap.ik[ii]); if (null == constraint) throw new Error("Skin IK constraint not found: " + skinMap.ik[i]); skin.constraints.push(constraint); } if (skinMap.transform) for (var ii = 0; ii < skinMap.transform.length; ii++) { var constraint = skeletonData.findTransformConstraint(skinMap.transform[ii]); if (null == constraint) throw new Error("Skin transform constraint not found: " + skinMap.transform[i]); skin.constraints.push(constraint); } if (skinMap.path) for (var ii = 0; ii < skinMap.path.length; ii++) { var constraint = skeletonData.findPathConstraint(skinMap.path[ii]); if (null == constraint) throw new Error("Skin path constraint not found: " + skinMap.path[i]); skin.constraints.push(constraint); } for (var slotName in skinMap.attachments) { var slot = skeletonData.findSlot(slotName); if (null == slot) throw new Error("Slot not found: " + slotName); var slotMap = skinMap.attachments[slotName]; for (var entryName in slotMap) { var attachment = this.readAttachment(slotMap[entryName], skin, slot.index, entryName, skeletonData); null != attachment && skin.setAttachment(slot.index, entryName, attachment); } } skeletonData.skins.push(skin); "default" == skin.name && (skeletonData.defaultSkin = skin); } } for (var i = 0, n = this.linkedMeshes.length; i < n; i++) { var linkedMesh = this.linkedMeshes[i]; var skin = null == linkedMesh.skin ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin); if (null == skin) throw new Error("Skin not found: " + linkedMesh.skin); var parent_6 = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent); if (null == parent_6) throw new Error("Parent mesh not found: " + linkedMesh.parent); linkedMesh.mesh.deformAttachment = linkedMesh.inheritDeform ? parent_6 : linkedMesh.mesh; linkedMesh.mesh.setParentMesh(parent_6); linkedMesh.mesh.updateUVs(); } this.linkedMeshes.length = 0; if (root.events) for (var eventName in root.events) { var eventMap = root.events[eventName]; var data = new spine.EventData(eventName); data.intValue = this.getValue(eventMap, "int", 0); data.floatValue = this.getValue(eventMap, "float", 0); data.stringValue = this.getValue(eventMap, "string", ""); data.audioPath = this.getValue(eventMap, "audio", null); if (null != data.audioPath) { data.volume = this.getValue(eventMap, "volume", 1); data.balance = this.getValue(eventMap, "balance", 0); } skeletonData.events.push(data); } if (root.animations) for (var animationName in root.animations) { var animationMap = root.animations[animationName]; this.readAnimation(animationMap, animationName, skeletonData); } return skeletonData; }; SkeletonJson.prototype.readAttachment = function(map, skin, slotIndex, name, skeletonData) { var scale = this.scale; name = this.getValue(map, "name", name); var type = this.getValue(map, "type", "region"); switch (type) { case "region": var path = this.getValue(map, "path", name); var region = this.attachmentLoader.newRegionAttachment(skin, name, path); if (null == region) return null; region.path = path; region.x = this.getValue(map, "x", 0) * scale; region.y = this.getValue(map, "y", 0) * scale; region.scaleX = this.getValue(map, "scaleX", 1); region.scaleY = this.getValue(map, "scaleY", 1); region.rotation = this.getValue(map, "rotation", 0); region.width = map.width * scale; region.height = map.height * scale; var color = this.getValue(map, "color", null); null != color && region.color.setFromString(color); region.updateOffset(); return region; case "boundingbox": var box = this.attachmentLoader.newBoundingBoxAttachment(skin, name); if (null == box) return null; this.readVertices(map, box, map.vertexCount << 1); var color = this.getValue(map, "color", null); null != color && box.color.setFromString(color); return box; case "mesh": case "linkedmesh": var path = this.getValue(map, "path", name); var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (null == mesh) return null; mesh.path = path; var color = this.getValue(map, "color", null); null != color && mesh.color.setFromString(color); mesh.width = this.getValue(map, "width", 0) * scale; mesh.height = this.getValue(map, "height", 0) * scale; var parent_7 = this.getValue(map, "parent", null); if (null != parent_7) { this.linkedMeshes.push(new LinkedMesh(mesh, this.getValue(map, "skin", null), slotIndex, parent_7, this.getValue(map, "deform", true))); return mesh; } var uvs = map.uvs; this.readVertices(map, mesh, uvs.length); mesh.triangles = map.triangles; mesh.regionUVs = uvs; mesh.updateUVs(); mesh.edges = this.getValue(map, "edges", null); mesh.hullLength = 2 * this.getValue(map, "hull", 0); return mesh; case "path": var path = this.attachmentLoader.newPathAttachment(skin, name); if (null == path) return null; path.closed = this.getValue(map, "closed", false); path.constantSpeed = this.getValue(map, "constantSpeed", true); var vertexCount = map.vertexCount; this.readVertices(map, path, vertexCount << 1); var lengths = spine.Utils.newArray(vertexCount / 3, 0); for (var i = 0; i < map.lengths.length; i++) lengths[i] = map.lengths[i] * scale; path.lengths = lengths; var color = this.getValue(map, "color", null); null != color && path.color.setFromString(color); return path; case "point": var point = this.attachmentLoader.newPointAttachment(skin, name); if (null == point) return null; point.x = this.getValue(map, "x", 0) * scale; point.y = this.getValue(map, "y", 0) * scale; point.rotation = this.getValue(map, "rotation", 0); var color = this.getValue(map, "color", null); null != color && point.color.setFromString(color); return point; case "clipping": var clip = this.attachmentLoader.newClippingAttachment(skin, name); if (null == clip) return null; var end = this.getValue(map, "end", null); if (null != end) { var slot = skeletonData.findSlot(end); if (null == slot) throw new Error("Clipping end slot not found: " + end); clip.endSlot = slot; } var vertexCount = map.vertexCount; this.readVertices(map, clip, vertexCount << 1); var color = this.getValue(map, "color", null); null != color && clip.color.setFromString(color); return clip; } return null; }; SkeletonJson.prototype.readVertices = function(map, attachment, verticesLength) { var scale = this.scale; attachment.worldVerticesLength = verticesLength; var vertices = map.vertices; if (verticesLength == vertices.length) { var scaledVertices = spine.Utils.toFloatArray(vertices); if (1 != scale) for (var i = 0, n = vertices.length; i < n; i++) scaledVertices[i] *= scale; attachment.vertices = scaledVertices; return; } var weights = new Array(); var bones = new Array(); for (var i = 0, n = vertices.length; i < n; ) { var boneCount = vertices[i++]; bones.push(boneCount); for (var nn = i + 4 * boneCount; i < nn; i += 4) { bones.push(vertices[i]); weights.push(vertices[i + 1] * scale); weights.push(vertices[i + 2] * scale); weights.push(vertices[i + 3]); } } attachment.bones = bones; attachment.vertices = spine.Utils.toFloatArray(weights); }; SkeletonJson.prototype.readAnimation = function(map, name, skeletonData) { var scale = this.scale; var timelines = new Array(); var duration = 0; if (map.slots) for (var slotName in map.slots) { var slotMap = map.slots[slotName]; var slotIndex = skeletonData.findSlotIndex(slotName); if (-1 == slotIndex) throw new Error("Slot not found: " + slotName); for (var timelineName in slotMap) { var timelineMap = slotMap[timelineName]; if ("attachment" == timelineName) { var timeline = new spine.AttachmentTimeline(timelineMap.length); timeline.slotIndex = slotIndex; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; timeline.setFrame(frameIndex++, this.getValue(valueMap, "time", 0), valueMap.name); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } else if ("color" == timelineName) { var timeline = new spine.ColorTimeline(timelineMap.length); timeline.slotIndex = slotIndex; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; var color = new spine.Color(); color.setFromString(valueMap.color); timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), color.r, color.g, color.b, color.a); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.ColorTimeline.ENTRIES]); } else { if ("twoColor" != timelineName) throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); var timeline = new spine.TwoColorTimeline(timelineMap.length); timeline.slotIndex = slotIndex; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; var light = new spine.Color(); var dark = new spine.Color(); light.setFromString(valueMap.light); dark.setFromString(valueMap.dark); timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), light.r, light.g, light.b, light.a, dark.r, dark.g, dark.b); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TwoColorTimeline.ENTRIES]); } } } if (map.bones) for (var boneName in map.bones) { var boneMap = map.bones[boneName]; var boneIndex = skeletonData.findBoneIndex(boneName); if (-1 == boneIndex) throw new Error("Bone not found: " + boneName); for (var timelineName in boneMap) { var timelineMap = boneMap[timelineName]; if ("rotate" === timelineName) { var timeline = new spine.RotateTimeline(timelineMap.length); timeline.boneIndex = boneIndex; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "angle", 0)); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.RotateTimeline.ENTRIES]); } else { if ("translate" !== timelineName && "scale" !== timelineName && "shear" !== timelineName) throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); var timeline = null; var timelineScale = 1, defaultValue = 0; if ("scale" === timelineName) { timeline = new spine.ScaleTimeline(timelineMap.length); defaultValue = 1; } else if ("shear" === timelineName) timeline = new spine.ShearTimeline(timelineMap.length); else { timeline = new spine.TranslateTimeline(timelineMap.length); timelineScale = scale; } timeline.boneIndex = boneIndex; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; var x = this.getValue(valueMap, "x", defaultValue), y = this.getValue(valueMap, "y", defaultValue); timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), x * timelineScale, y * timelineScale); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TranslateTimeline.ENTRIES]); } } } if (map.ik) for (var constraintName in map.ik) { var constraintMap = map.ik[constraintName]; var constraint = skeletonData.findIkConstraint(constraintName); var timeline = new spine.IkConstraintTimeline(constraintMap.length); timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(constraint); var frameIndex = 0; for (var i = 0; i < constraintMap.length; i++) { var valueMap = constraintMap[i]; timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "mix", 1), this.getValue(valueMap, "softness", 0) * scale, this.getValue(valueMap, "bendPositive", true) ? 1 : -1, this.getValue(valueMap, "compress", false), this.getValue(valueMap, "stretch", false)); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.IkConstraintTimeline.ENTRIES]); } if (map.transform) for (var constraintName in map.transform) { var constraintMap = map.transform[constraintName]; var constraint = skeletonData.findTransformConstraint(constraintName); var timeline = new spine.TransformConstraintTimeline(constraintMap.length); timeline.transformConstraintIndex = skeletonData.transformConstraints.indexOf(constraint); var frameIndex = 0; for (var i = 0; i < constraintMap.length; i++) { var valueMap = constraintMap[i]; timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1), this.getValue(valueMap, "scaleMix", 1), this.getValue(valueMap, "shearMix", 1)); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TransformConstraintTimeline.ENTRIES]); } var mapPath = map.path || map.paths; if (mapPath) for (var constraintName in mapPath) { var constraintMap = mapPath[constraintName]; var index = skeletonData.findPathConstraintIndex(constraintName); if (-1 == index) throw new Error("Path constraint not found: " + constraintName); var data = skeletonData.pathConstraints[index]; for (var timelineName in constraintMap) { var timelineMap = constraintMap[timelineName]; if ("position" === timelineName || "spacing" === timelineName) { var timeline = null; var timelineScale = 1; if ("spacing" === timelineName) { timeline = new spine.PathConstraintSpacingTimeline(timelineMap.length); data.spacingMode != spine.SpacingMode.Length && data.spacingMode != spine.SpacingMode.Fixed || (timelineScale = scale); } else { timeline = new spine.PathConstraintPositionTimeline(timelineMap.length); data.positionMode == spine.PositionMode.Fixed && (timelineScale = scale); } timeline.pathConstraintIndex = index; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, timelineName, 0) * timelineScale); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintPositionTimeline.ENTRIES]); } else if ("mix" === timelineName) { var timeline = new spine.PathConstraintMixTimeline(timelineMap.length); timeline.pathConstraintIndex = index; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1)); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintMixTimeline.ENTRIES]); } } } if (map.deform) for (var deformName in map.deform) { var deformMap = map.deform[deformName]; var skin = skeletonData.findSkin(deformName); if (null == skin) throw new Error("Skin not found: " + deformName); for (var slotName in deformMap) { var slotMap = deformMap[slotName]; var slotIndex = skeletonData.findSlotIndex(slotName); if (-1 == slotIndex) throw new Error("Slot not found: " + slotMap.name); for (var timelineName in slotMap) { var timelineMap = slotMap[timelineName]; var attachment = skin.getAttachment(slotIndex, timelineName); if (null == attachment) continue; var weighted = null != attachment.bones; var vertices = attachment.vertices; var deformLength = weighted ? vertices.length / 3 * 2 : vertices.length; var timeline = new spine.DeformTimeline(timelineMap.length); timeline.slotIndex = slotIndex; timeline.attachment = attachment; var frameIndex = 0; for (var j = 0; j < timelineMap.length; j++) { var valueMap = timelineMap[j]; var deform = void 0; var verticesValue = this.getValue(valueMap, "vertices", null); if (null == verticesValue) deform = weighted ? spine.Utils.newFloatArray(deformLength) : vertices; else { deform = spine.Utils.newFloatArray(deformLength); var start = this.getValue(valueMap, "offset", 0); spine.Utils.arrayCopy(verticesValue, 0, deform, start, verticesValue.length); if (1 != scale) for (var i = start, n = i + verticesValue.length; i < n; i++) deform[i] *= scale; if (!weighted) for (var i = 0; i < deformLength; i++) deform[i] += vertices[i]; } timeline.setFrame(frameIndex, this.getValue(valueMap, "time", 0), deform); this.readCurve(valueMap, timeline, frameIndex); frameIndex++; } timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } } } var drawOrderNode = map.drawOrder; null == drawOrderNode && (drawOrderNode = map.draworder); if (null != drawOrderNode) { var timeline = new spine.DrawOrderTimeline(drawOrderNode.length); var slotCount = skeletonData.slots.length; var frameIndex = 0; for (var j = 0; j < drawOrderNode.length; j++) { var drawOrderMap = drawOrderNode[j]; var drawOrder = null; var offsets = this.getValue(drawOrderMap, "offsets", null); if (null != offsets) { drawOrder = spine.Utils.newArray(slotCount, -1); var unchanged = spine.Utils.newArray(slotCount - offsets.length, 0); var originalIndex = 0, unchangedIndex = 0; for (var i = 0; i < offsets.length; i++) { var offsetMap = offsets[i]; var slotIndex = skeletonData.findSlotIndex(offsetMap.slot); if (-1 == slotIndex) throw new Error("Slot not found: " + offsetMap.slot); while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; drawOrder[originalIndex + offsetMap.offset] = originalIndex++; } while (originalIndex < slotCount) unchanged[unchangedIndex++] = originalIndex++; for (var i = slotCount - 1; i >= 0; i--) -1 == drawOrder[i] && (drawOrder[i] = unchanged[--unchangedIndex]); } timeline.setFrame(frameIndex++, this.getValue(drawOrderMap, "time", 0), drawOrder); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } if (map.events) { var timeline = new spine.EventTimeline(map.events.length); var frameIndex = 0; for (var i = 0; i < map.events.length; i++) { var eventMap = map.events[i]; var eventData = skeletonData.findEvent(eventMap.name); if (null == eventData) throw new Error("Event not found: " + eventMap.name); var event_6 = new spine.Event(spine.Utils.toSinglePrecision(this.getValue(eventMap, "time", 0)), eventData); event_6.intValue = this.getValue(eventMap, "int", eventData.intValue); event_6.floatValue = this.getValue(eventMap, "float", eventData.floatValue); event_6.stringValue = this.getValue(eventMap, "string", eventData.stringValue); if (null != event_6.data.audioPath) { event_6.volume = this.getValue(eventMap, "volume", 1); event_6.balance = this.getValue(eventMap, "balance", 0); } timeline.setFrame(frameIndex++, event_6); } timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } if (isNaN(duration)) throw new Error("Error while parsing animation, duration is NaN"); skeletonData.animations.push(new spine.Animation(name, timelines, duration)); }; SkeletonJson.prototype.readCurve = function(map, timeline, frameIndex) { var curve = map.curve; if (!curve) return; "stepped" == curve ? timeline.setStepped(frameIndex) : "[object Array]" === Object.prototype.toString.call(curve) ? timeline.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]) : timeline.setCurve(frameIndex, curve, this.getValue(map, "c2", 0), this.getValue(map, "c3", 1), this.getValue(map, "c4", 1)); }; SkeletonJson.prototype.getValue = function(map, prop, defaultValue) { return void 0 !== map[prop] ? map[prop] : defaultValue; }; SkeletonJson.blendModeFromString = function(str) { str = str.toLowerCase(); if ("normal" == str) return spine.BlendMode.Normal; if ("additive" == str) return spine.BlendMode.Additive; if ("multiply" == str) return spine.BlendMode.Multiply; if ("screen" == str) return spine.BlendMode.Screen; throw new Error("Unknown blend mode: " + str); }; SkeletonJson.positionModeFromString = function(str) { str = str.toLowerCase(); if ("fixed" == str) return spine.PositionMode.Fixed; if ("percent" == str) return spine.PositionMode.Percent; throw new Error("Unknown position mode: " + str); }; SkeletonJson.spacingModeFromString = function(str) { str = str.toLowerCase(); if ("length" == str) return spine.SpacingMode.Length; if ("fixed" == str) return spine.SpacingMode.Fixed; if ("percent" == str) return spine.SpacingMode.Percent; throw new Error("Unknown position mode: " + str); }; SkeletonJson.rotateModeFromString = function(str) { str = str.toLowerCase(); if ("tangent" == str) return spine.RotateMode.Tangent; if ("chain" == str) return spine.RotateMode.Chain; if ("chainscale" == str) return spine.RotateMode.ChainScale; throw new Error("Unknown rotate mode: " + str); }; SkeletonJson.transformModeFromString = function(str) { str = str.toLowerCase(); if ("normal" == str) return spine.TransformMode.Normal; if ("onlytranslation" == str) return spine.TransformMode.OnlyTranslation; if ("norotationorreflection" == str) return spine.TransformMode.NoRotationOrReflection; if ("noscale" == str) return spine.TransformMode.NoScale; if ("noscaleorreflection" == str) return spine.TransformMode.NoScaleOrReflection; throw new Error("Unknown transform mode: " + str); }; return SkeletonJson; })(); spine.SkeletonJson = SkeletonJson; var LinkedMesh = (function() { function LinkedMesh(mesh, skin, slotIndex, parent, inheritDeform) { this.mesh = mesh; this.skin = skin; this.slotIndex = slotIndex; this.parent = parent; this.inheritDeform = inheritDeform; } return LinkedMesh; })(); })(spine || (spine = {})); var spine; (function(spine) { var SkinEntry = (function() { function SkinEntry(slotIndex, name, attachment) { this.slotIndex = slotIndex; this.name = name; this.attachment = attachment; } return SkinEntry; })(); spine.SkinEntry = SkinEntry; var Skin = (function() { function Skin(name) { this.attachments = new Array(); this.bones = Array(); this.constraints = new Array(); if (null == name) throw new Error("name cannot be null."); this.name = name; } Skin.prototype.setAttachment = function(slotIndex, name, attachment) { if (null == attachment) throw new Error("attachment cannot be null."); var attachments = this.attachments; slotIndex >= attachments.length && (attachments.length = slotIndex + 1); attachments[slotIndex] || (attachments[slotIndex] = {}); attachments[slotIndex][name] = attachment; }; Skin.prototype.addSkin = function(skin) { for (var i = 0; i < skin.bones.length; i++) { var bone = skin.bones[i]; var contained = false; for (var j = 0; j < this.bones.length; j++) if (this.bones[j] == bone) { contained = true; break; } contained || this.bones.push(bone); } for (var i = 0; i < skin.constraints.length; i++) { var constraint = skin.constraints[i]; var contained = false; for (var j = 0; j < this.constraints.length; j++) if (this.constraints[j] == constraint) { contained = true; break; } contained || this.constraints.push(constraint); } var attachments = skin.getAttachments(); for (var i = 0; i < attachments.length; i++) { var attachment = attachments[i]; this.setAttachment(attachment.slotIndex, attachment.name, attachment.attachment); } }; Skin.prototype.copySkin = function(skin) { for (var i = 0; i < skin.bones.length; i++) { var bone = skin.bones[i]; var contained = false; for (var j = 0; j < this.bones.length; j++) if (this.bones[j] == bone) { contained = true; break; } contained || this.bones.push(bone); } for (var i = 0; i < skin.constraints.length; i++) { var constraint = skin.constraints[i]; var contained = false; for (var j = 0; j < this.constraints.length; j++) if (this.constraints[j] == constraint) { contained = true; break; } contained || this.constraints.push(constraint); } var attachments = skin.getAttachments(); for (var i = 0; i < attachments.length; i++) { var attachment = attachments[i]; if (null == attachment.attachment) continue; if (attachment.attachment instanceof spine.MeshAttachment) { attachment.attachment = attachment.attachment.newLinkedMesh(); this.setAttachment(attachment.slotIndex, attachment.name, attachment.attachment); } else { attachment.attachment = attachment.attachment.copy(); this.setAttachment(attachment.slotIndex, attachment.name, attachment.attachment); } } }; Skin.prototype.getAttachment = function(slotIndex, name) { var dictionary = this.attachments[slotIndex]; return dictionary ? dictionary[name] : null; }; Skin.prototype.removeAttachment = function(slotIndex, name) { var dictionary = this.attachments[slotIndex]; dictionary && (dictionary[name] = null); }; Skin.prototype.getAttachments = function() { var entries = new Array(); for (var i = 0; i < this.attachments.length; i++) { var slotAttachments = this.attachments[i]; if (slotAttachments) for (var name_4 in slotAttachments) { var attachment = slotAttachments[name_4]; attachment && entries.push(new SkinEntry(i, name_4, attachment)); } } return entries; }; Skin.prototype.getAttachmentsForSlot = function(slotIndex, attachments) { var slotAttachments = this.attachments[slotIndex]; if (slotAttachments) for (var name_5 in slotAttachments) { var attachment = slotAttachments[name_5]; attachment && attachments.push(new SkinEntry(slotIndex, name_5, attachment)); } }; Skin.prototype.clear = function() { this.attachments.length = 0; this.bones.length = 0; this.constraints.length = 0; }; Skin.prototype.attachAll = function(skeleton, oldSkin) { var slotIndex = 0; for (var i = 0; i < skeleton.slots.length; i++) { var slot = skeleton.slots[i]; var slotAttachment = slot.getAttachment(); if (slotAttachment && slotIndex < oldSkin.attachments.length) { var dictionary = oldSkin.attachments[slotIndex]; for (var key in dictionary) { var skinAttachment = dictionary[key]; if (slotAttachment == skinAttachment) { var attachment = this.getAttachment(slotIndex, key); null != attachment && slot.setAttachment(attachment); break; } } } slotIndex++; } }; return Skin; })(); spine.Skin = Skin; })(spine || (spine = {})); var spine; (function(spine) { var Slot = (function() { function Slot(data, bone) { this.deform = new Array(); if (null == data) throw new Error("data cannot be null."); if (null == bone) throw new Error("bone cannot be null."); this.data = data; this.bone = bone; this.color = new spine.Color(); this.darkColor = null == data.darkColor ? null : new spine.Color(); this.setToSetupPose(); } Slot.prototype.getSkeleton = function() { return this.bone.skeleton; }; Slot.prototype.getAttachment = function() { return this.attachment; }; Slot.prototype.setAttachment = function(attachment) { if (this.attachment == attachment) return; this.attachment = attachment; this.attachmentTime = this.bone.skeleton.time; this.deform.length = 0; }; Slot.prototype.setAttachmentTime = function(time) { this.attachmentTime = this.bone.skeleton.time - time; }; Slot.prototype.getAttachmentTime = function() { return this.bone.skeleton.time - this.attachmentTime; }; Slot.prototype.setToSetupPose = function() { this.color.setFromColor(this.data.color); null != this.darkColor && this.darkColor.setFromColor(this.data.darkColor); if (null == this.data.attachmentName) this.attachment = null; else { this.attachment = null; this.setAttachment(this.bone.skeleton.getAttachment(this.data.index, this.data.attachmentName)); } }; return Slot; })(); spine.Slot = Slot; })(spine || (spine = {})); var spine; (function(spine) { var SlotData = (function() { function SlotData(index, name, boneData) { this.color = new spine.Color(1, 1, 1, 1); if (index < 0) throw new Error("index must be >= 0."); if (null == name) throw new Error("name cannot be null."); if (null == boneData) throw new Error("boneData cannot be null."); this.index = index; this.name = name; this.boneData = boneData; } return SlotData; })(); spine.SlotData = SlotData; })(spine || (spine = {})); var spine; (function(spine) { var Texture = (function() { function Texture(image) { this._image = image; } Texture.prototype.getImage = function() { return this._image; }; Texture.filterFromString = function(text) { switch (text.toLowerCase()) { case "nearest": return TextureFilter.Nearest; case "linear": return TextureFilter.Linear; case "mipmap": return TextureFilter.MipMap; case "mipmapnearestnearest": return TextureFilter.MipMapNearestNearest; case "mipmaplinearnearest": return TextureFilter.MipMapLinearNearest; case "mipmapnearestlinear": return TextureFilter.MipMapNearestLinear; case "mipmaplinearlinear": return TextureFilter.MipMapLinearLinear; default: throw new Error("Unknown texture filter " + text); } }; Texture.wrapFromString = function(text) { switch (text.toLowerCase()) { case "mirroredtepeat": return TextureWrap.MirroredRepeat; case "clamptoedge": return TextureWrap.ClampToEdge; case "repeat": return TextureWrap.Repeat; default: throw new Error("Unknown texture wrap " + text); } }; return Texture; })(); spine.Texture = Texture; var TextureFilter; (function(TextureFilter) { TextureFilter[TextureFilter["Nearest"] = 9728] = "Nearest"; TextureFilter[TextureFilter["Linear"] = 9729] = "Linear"; TextureFilter[TextureFilter["MipMap"] = 9987] = "MipMap"; TextureFilter[TextureFilter["MipMapNearestNearest"] = 9984] = "MipMapNearestNearest"; TextureFilter[TextureFilter["MipMapLinearNearest"] = 9985] = "MipMapLinearNearest"; TextureFilter[TextureFilter["MipMapNearestLinear"] = 9986] = "MipMapNearestLinear"; TextureFilter[TextureFilter["MipMapLinearLinear"] = 9987] = "MipMapLinearLinear"; })(TextureFilter = spine.TextureFilter || (spine.TextureFilter = {})); var TextureWrap; (function(TextureWrap) { TextureWrap[TextureWrap["MirroredRepeat"] = 33648] = "MirroredRepeat"; TextureWrap[TextureWrap["ClampToEdge"] = 33071] = "ClampToEdge"; TextureWrap[TextureWrap["Repeat"] = 10497] = "Repeat"; })(TextureWrap = spine.TextureWrap || (spine.TextureWrap = {})); var TextureRegion = (function() { function TextureRegion() { this.u = 0; this.v = 0; this.u2 = 0; this.v2 = 0; this.width = 0; this.height = 0; this.rotate = false; this.offsetX = 0; this.offsetY = 0; this.originalWidth = 0; this.originalHeight = 0; } return TextureRegion; })(); spine.TextureRegion = TextureRegion; var FakeTexture = (function(_super) { __extends(FakeTexture, _super); function FakeTexture() { return null !== _super && _super.apply(this, arguments) || this; } FakeTexture.prototype.setFilters = function(minFilter, magFilter) {}; FakeTexture.prototype.setWraps = function(uWrap, vWrap) {}; FakeTexture.prototype.dispose = function() {}; return FakeTexture; })(Texture); spine.FakeTexture = FakeTexture; })(spine || (spine = {})); var spine; (function(spine) { var TextureAtlas = (function() { function TextureAtlas(atlasText, textureLoader) { this.pages = new Array(); this.regions = new Array(); this.load(atlasText, textureLoader); } TextureAtlas.prototype.load = function(atlasText, textureLoader) { if (null == textureLoader) throw new Error("textureLoader cannot be null."); var reader = new TextureAtlasReader(atlasText); var tuple = new Array(4); var page = null; while (true) { var line = reader.readLine(); if (null == line) break; line = line.trim(); if (0 == line.length) page = null; else if (page) { var region = new TextureAtlasRegion(); region.name = line; region.page = page; var rotateValue = reader.readValue(); "true" == rotateValue.toLocaleLowerCase() ? region.degrees = 90 : "false" == rotateValue.toLocaleLowerCase() ? region.degrees = 0 : region.degrees = parseFloat(rotateValue); region.rotate = 90 == region.degrees; reader.readTuple(tuple); var x = parseInt(tuple[0]); var y = parseInt(tuple[1]); reader.readTuple(tuple); var width = parseInt(tuple[0]); var height = parseInt(tuple[1]); region.u = x / page.width; region.v = y / page.height; if (region.rotate) { region.u2 = (x + height) / page.width; region.v2 = (y + width) / page.height; } else { region.u2 = (x + width) / page.width; region.v2 = (y + height) / page.height; } region.x = x; region.y = y; region.width = Math.abs(width); region.height = Math.abs(height); 4 == reader.readTuple(tuple) && 4 == reader.readTuple(tuple) && reader.readTuple(tuple); region.originalWidth = parseInt(tuple[0]); region.originalHeight = parseInt(tuple[1]); reader.readTuple(tuple); region.offsetX = parseInt(tuple[0]); region.offsetY = parseInt(tuple[1]); region.index = parseInt(reader.readValue()); region.texture = page.texture; this.regions.push(region); } else { page = new TextureAtlasPage(); page.name = line; if (2 == reader.readTuple(tuple)) { page.width = parseInt(tuple[0]); page.height = parseInt(tuple[1]); reader.readTuple(tuple); } reader.readTuple(tuple); page.minFilter = spine.Texture.filterFromString(tuple[0]); page.magFilter = spine.Texture.filterFromString(tuple[1]); var direction = reader.readValue(); page.uWrap = spine.TextureWrap.ClampToEdge; page.vWrap = spine.TextureWrap.ClampToEdge; "x" == direction ? page.uWrap = spine.TextureWrap.Repeat : "y" == direction ? page.vWrap = spine.TextureWrap.Repeat : "xy" == direction && (page.uWrap = page.vWrap = spine.TextureWrap.Repeat); page.texture = textureLoader(line); page.texture.setFilters(page.minFilter, page.magFilter); page.texture.setWraps(page.uWrap, page.vWrap); page.width = page.texture.getImage().width; page.height = page.texture.getImage().height; this.pages.push(page); } } }; TextureAtlas.prototype.findRegion = function(name) { for (var i = 0; i < this.regions.length; i++) if (this.regions[i].name == name) return this.regions[i]; return null; }; TextureAtlas.prototype.dispose = function() { for (var i = 0; i < this.pages.length; i++) this.pages[i].texture.dispose(); }; return TextureAtlas; })(); spine.TextureAtlas = TextureAtlas; var TextureAtlasReader = (function() { function TextureAtlasReader(text) { this.index = 0; this.lines = text.split(/\r\n|\r|\n/); } TextureAtlasReader.prototype.readLine = function() { if (this.index >= this.lines.length) return null; return this.lines[this.index++]; }; TextureAtlasReader.prototype.readValue = function() { var line = this.readLine(); var colon = line.indexOf(":"); if (-1 == colon) throw new Error("Invalid line: " + line); return line.substring(colon + 1).trim(); }; TextureAtlasReader.prototype.readTuple = function(tuple) { var line = this.readLine(); var colon = line.indexOf(":"); if (-1 == colon) throw new Error("Invalid line: " + line); var i = 0, lastMatch = colon + 1; for (;i < 3; i++) { var comma = line.indexOf(",", lastMatch); if (-1 == comma) break; tuple[i] = line.substr(lastMatch, comma - lastMatch).trim(); lastMatch = comma + 1; } tuple[i] = line.substring(lastMatch).trim(); return i + 1; }; return TextureAtlasReader; })(); var TextureAtlasPage = (function() { function TextureAtlasPage() {} return TextureAtlasPage; })(); spine.TextureAtlasPage = TextureAtlasPage; var TextureAtlasRegion = (function(_super) { __extends(TextureAtlasRegion, _super); function TextureAtlasRegion() { return null !== _super && _super.apply(this, arguments) || this; } return TextureAtlasRegion; })(spine.TextureRegion); spine.TextureAtlasRegion = TextureAtlasRegion; })(spine || (spine = {})); var spine; (function(spine) { var TransformConstraint = (function() { function TransformConstraint(data, skeleton) { this.rotateMix = 0; this.translateMix = 0; this.scaleMix = 0; this.shearMix = 0; this.temp = new spine.Vector2(); this.active = false; if (null == data) throw new Error("data cannot be null."); if (null == skeleton) throw new Error("skeleton cannot be null."); this.data = data; this.rotateMix = data.rotateMix; this.translateMix = data.translateMix; this.scaleMix = data.scaleMix; this.shearMix = data.shearMix; this.bones = new Array(); for (var i = 0; i < data.bones.length; i++) this.bones.push(skeleton.findBone(data.bones[i].name)); this.target = skeleton.findBone(data.target.name); } TransformConstraint.prototype.isActive = function() { return this.active; }; TransformConstraint.prototype.apply = function() { this.update(); }; TransformConstraint.prototype.update = function() { this.data.local ? this.data.relative ? this.applyRelativeLocal() : this.applyAbsoluteLocal() : this.data.relative ? this.applyRelativeWorld() : this.applyAbsoluteWorld(); }; TransformConstraint.prototype.applyAbsoluteWorld = function() { var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; var target = this.target; var ta = target.a, tb = target.b, tc = target.c, td = target.d; var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad; var offsetRotation = this.data.offsetRotation * degRadReflect; var offsetShearY = this.data.offsetShearY * degRadReflect; var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; var modified = false; if (0 != rotateMix) { var a = bone.a, b = bone.b, c = bone.c, d = bone.d; var r = Math.atan2(tc, ta) - Math.atan2(c, a) + offsetRotation; r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : r < -spine.MathUtils.PI && (r += spine.MathUtils.PI2); r *= rotateMix; var cos = Math.cos(r), sin = Math.sin(r); bone.a = cos * a - sin * c; bone.b = cos * b - sin * d; bone.c = sin * a + cos * c; bone.d = sin * b + cos * d; modified = true; } if (0 != translateMix) { var temp = this.temp; target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY)); bone.worldX += (temp.x - bone.worldX) * translateMix; bone.worldY += (temp.y - bone.worldY) * translateMix; modified = true; } if (scaleMix > 0) { var s = Math.sqrt(bone.a * bone.a + bone.c * bone.c); var ts = Math.sqrt(ta * ta + tc * tc); s > 1e-5 && (s = (s + (ts - s + this.data.offsetScaleX) * scaleMix) / s); bone.a *= s; bone.c *= s; s = Math.sqrt(bone.b * bone.b + bone.d * bone.d); ts = Math.sqrt(tb * tb + td * td); s > 1e-5 && (s = (s + (ts - s + this.data.offsetScaleY) * scaleMix) / s); bone.b *= s; bone.d *= s; modified = true; } if (shearMix > 0) { var b = bone.b, d = bone.d; var by = Math.atan2(d, b); var r = Math.atan2(td, tb) - Math.atan2(tc, ta) - (by - Math.atan2(bone.c, bone.a)); r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : r < -spine.MathUtils.PI && (r += spine.MathUtils.PI2); r = by + (r + offsetShearY) * shearMix; var s = Math.sqrt(b * b + d * d); bone.b = Math.cos(r) * s; bone.d = Math.sin(r) * s; modified = true; } modified && (bone.appliedValid = false); } }; TransformConstraint.prototype.applyRelativeWorld = function() { var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; var target = this.target; var ta = target.a, tb = target.b, tc = target.c, td = target.d; var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad; var offsetRotation = this.data.offsetRotation * degRadReflect, offsetShearY = this.data.offsetShearY * degRadReflect; var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; var modified = false; if (0 != rotateMix) { var a = bone.a, b = bone.b, c = bone.c, d = bone.d; var r = Math.atan2(tc, ta) + offsetRotation; r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : r < -spine.MathUtils.PI && (r += spine.MathUtils.PI2); r *= rotateMix; var cos = Math.cos(r), sin = Math.sin(r); bone.a = cos * a - sin * c; bone.b = cos * b - sin * d; bone.c = sin * a + cos * c; bone.d = sin * b + cos * d; modified = true; } if (0 != translateMix) { var temp = this.temp; target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY)); bone.worldX += temp.x * translateMix; bone.worldY += temp.y * translateMix; modified = true; } if (scaleMix > 0) { var s = (Math.sqrt(ta * ta + tc * tc) - 1 + this.data.offsetScaleX) * scaleMix + 1; bone.a *= s; bone.c *= s; s = (Math.sqrt(tb * tb + td * td) - 1 + this.data.offsetScaleY) * scaleMix + 1; bone.b *= s; bone.d *= s; modified = true; } if (shearMix > 0) { var r = Math.atan2(td, tb) - Math.atan2(tc, ta); r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : r < -spine.MathUtils.PI && (r += spine.MathUtils.PI2); var b = bone.b, d = bone.d; r = Math.atan2(d, b) + (r - spine.MathUtils.PI / 2 + offsetShearY) * shearMix; var s = Math.sqrt(b * b + d * d); bone.b = Math.cos(r) * s; bone.d = Math.sin(r) * s; modified = true; } modified && (bone.appliedValid = false); } }; TransformConstraint.prototype.applyAbsoluteLocal = function() { var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; var target = this.target; target.appliedValid || target.updateAppliedTransform(); var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; bone.appliedValid || bone.updateAppliedTransform(); var rotation = bone.arotation; if (0 != rotateMix) { var r = target.arotation - rotation + this.data.offsetRotation; r -= 360 * (16384 - (16384.499999999996 - r / 360 | 0)); rotation += r * rotateMix; } var x = bone.ax, y = bone.ay; if (0 != translateMix) { x += (target.ax - x + this.data.offsetX) * translateMix; y += (target.ay - y + this.data.offsetY) * translateMix; } var scaleX = bone.ascaleX, scaleY = bone.ascaleY; if (0 != scaleMix) { scaleX > 1e-5 && (scaleX = (scaleX + (target.ascaleX - scaleX + this.data.offsetScaleX) * scaleMix) / scaleX); scaleY > 1e-5 && (scaleY = (scaleY + (target.ascaleY - scaleY + this.data.offsetScaleY) * scaleMix) / scaleY); } var shearY = bone.ashearY; if (0 != shearMix) { var r = target.ashearY - shearY + this.data.offsetShearY; r -= 360 * (16384 - (16384.499999999996 - r / 360 | 0)); bone.shearY += r * shearMix; } bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY); } }; TransformConstraint.prototype.applyRelativeLocal = function() { var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; var target = this.target; target.appliedValid || target.updateAppliedTransform(); var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) { var bone = bones[i]; bone.appliedValid || bone.updateAppliedTransform(); var rotation = bone.arotation; 0 != rotateMix && (rotation += (target.arotation + this.data.offsetRotation) * rotateMix); var x = bone.ax, y = bone.ay; if (0 != translateMix) { x += (target.ax + this.data.offsetX) * translateMix; y += (target.ay + this.data.offsetY) * translateMix; } var scaleX = bone.ascaleX, scaleY = bone.ascaleY; if (0 != scaleMix) { scaleX > 1e-5 && (scaleX *= (target.ascaleX - 1 + this.data.offsetScaleX) * scaleMix + 1); scaleY > 1e-5 && (scaleY *= (target.ascaleY - 1 + this.data.offsetScaleY) * scaleMix + 1); } var shearY = bone.ashearY; 0 != shearMix && (shearY += (target.ashearY + this.data.offsetShearY) * shearMix); bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY); } }; return TransformConstraint; })(); spine.TransformConstraint = TransformConstraint; })(spine || (spine = {})); var spine; (function(spine) { var TransformConstraintData = (function(_super) { __extends(TransformConstraintData, _super); function TransformConstraintData(name) { var _this = _super.call(this, name, 0, false) || this; _this.bones = new Array(); _this.rotateMix = 0; _this.translateMix = 0; _this.scaleMix = 0; _this.shearMix = 0; _this.offsetRotation = 0; _this.offsetX = 0; _this.offsetY = 0; _this.offsetScaleX = 0; _this.offsetScaleY = 0; _this.offsetShearY = 0; _this.relative = false; _this.local = false; return _this; } return TransformConstraintData; })(spine.ConstraintData); spine.TransformConstraintData = TransformConstraintData; })(spine || (spine = {})); var spine; (function(spine) { var Triangulator = (function() { function Triangulator() { this.convexPolygons = new Array(); this.convexPolygonsIndices = new Array(); this.indicesArray = new Array(); this.isConcaveArray = new Array(); this.triangles = new Array(); this.polygonPool = new spine.Pool(function() { return new Array(); }); this.polygonIndicesPool = new spine.Pool(function() { return new Array(); }); } Triangulator.prototype.triangulate = function(verticesArray) { var vertices = verticesArray; var vertexCount = verticesArray.length >> 1; var indices = this.indicesArray; indices.length = 0; for (var i = 0; i < vertexCount; i++) indices[i] = i; var isConcave = this.isConcaveArray; isConcave.length = 0; for (var i = 0, n = vertexCount; i < n; ++i) isConcave[i] = Triangulator.isConcave(i, vertexCount, vertices, indices); var triangles = this.triangles; triangles.length = 0; while (vertexCount > 3) { var previous = vertexCount - 1, i = 0, next = 1; while (true) { outer: if (!isConcave[i]) { var p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1; var p1x = vertices[p1], p1y = vertices[p1 + 1]; var p2x = vertices[p2], p2y = vertices[p2 + 1]; var p3x = vertices[p3], p3y = vertices[p3 + 1]; for (var ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) { if (!isConcave[ii]) continue; var v = indices[ii] << 1; var vx = vertices[v], vy = vertices[v + 1]; if (Triangulator.positiveArea(p3x, p3y, p1x, p1y, vx, vy) && Triangulator.positiveArea(p1x, p1y, p2x, p2y, vx, vy) && Triangulator.positiveArea(p2x, p2y, p3x, p3y, vx, vy)) break outer; } break; } if (0 == next) { do { if (!isConcave[i]) break; i--; } while (i > 0); break; } previous = i; i = next; next = (next + 1) % vertexCount; } triangles.push(indices[(vertexCount + i - 1) % vertexCount]); triangles.push(indices[i]); triangles.push(indices[(i + 1) % vertexCount]); indices.splice(i, 1); isConcave.splice(i, 1); vertexCount--; var previousIndex = (vertexCount + i - 1) % vertexCount; var nextIndex = i == vertexCount ? 0 : i; isConcave[previousIndex] = Triangulator.isConcave(previousIndex, vertexCount, vertices, indices); isConcave[nextIndex] = Triangulator.isConcave(nextIndex, vertexCount, vertices, indices); } if (3 == vertexCount) { triangles.push(indices[2]); triangles.push(indices[0]); triangles.push(indices[1]); } return triangles; }; Triangulator.prototype.decompose = function(verticesArray, triangles) { var vertices = verticesArray; var convexPolygons = this.convexPolygons; this.polygonPool.freeAll(convexPolygons); convexPolygons.length = 0; var convexPolygonsIndices = this.convexPolygonsIndices; this.polygonIndicesPool.freeAll(convexPolygonsIndices); convexPolygonsIndices.length = 0; var polygonIndices = this.polygonIndicesPool.obtain(); polygonIndices.length = 0; var polygon = this.polygonPool.obtain(); polygon.length = 0; var fanBaseIndex = -1, lastWinding = 0; for (var i = 0, n = triangles.length; i < n; i += 3) { var t1 = triangles[i] << 1, t2 = triangles[i + 1] << 1, t3 = triangles[i + 2] << 1; var x1 = vertices[t1], y1 = vertices[t1 + 1]; var x2 = vertices[t2], y2 = vertices[t2 + 1]; var x3 = vertices[t3], y3 = vertices[t3 + 1]; var merged = false; if (fanBaseIndex == t1) { var o = polygon.length - 4; var winding1 = Triangulator.winding(polygon[o], polygon[o + 1], polygon[o + 2], polygon[o + 3], x3, y3); var winding2 = Triangulator.winding(x3, y3, polygon[0], polygon[1], polygon[2], polygon[3]); if (winding1 == lastWinding && winding2 == lastWinding) { polygon.push(x3); polygon.push(y3); polygonIndices.push(t3); merged = true; } } if (!merged) { if (polygon.length > 0) { convexPolygons.push(polygon); convexPolygonsIndices.push(polygonIndices); } else { this.polygonPool.free(polygon); this.polygonIndicesPool.free(polygonIndices); } polygon = this.polygonPool.obtain(); polygon.length = 0; polygon.push(x1); polygon.push(y1); polygon.push(x2); polygon.push(y2); polygon.push(x3); polygon.push(y3); polygonIndices = this.polygonIndicesPool.obtain(); polygonIndices.length = 0; polygonIndices.push(t1); polygonIndices.push(t2); polygonIndices.push(t3); lastWinding = Triangulator.winding(x1, y1, x2, y2, x3, y3); fanBaseIndex = t1; } } if (polygon.length > 0) { convexPolygons.push(polygon); convexPolygonsIndices.push(polygonIndices); } for (var i = 0, n = convexPolygons.length; i < n; i++) { polygonIndices = convexPolygonsIndices[i]; if (0 == polygonIndices.length) continue; var firstIndex = polygonIndices[0]; var lastIndex = polygonIndices[polygonIndices.length - 1]; polygon = convexPolygons[i]; var o = polygon.length - 4; var prevPrevX = polygon[o], prevPrevY = polygon[o + 1]; var prevX = polygon[o + 2], prevY = polygon[o + 3]; var firstX = polygon[0], firstY = polygon[1]; var secondX = polygon[2], secondY = polygon[3]; var winding = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY); for (var ii = 0; ii < n; ii++) { if (ii == i) continue; var otherIndices = convexPolygonsIndices[ii]; if (3 != otherIndices.length) continue; var otherFirstIndex = otherIndices[0]; var otherSecondIndex = otherIndices[1]; var otherLastIndex = otherIndices[2]; var otherPoly = convexPolygons[ii]; var x3 = otherPoly[otherPoly.length - 2], y3 = otherPoly[otherPoly.length - 1]; if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) continue; var winding1 = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3); var winding2 = Triangulator.winding(x3, y3, firstX, firstY, secondX, secondY); if (winding1 == winding && winding2 == winding) { otherPoly.length = 0; otherIndices.length = 0; polygon.push(x3); polygon.push(y3); polygonIndices.push(otherLastIndex); prevPrevX = prevX; prevPrevY = prevY; prevX = x3; prevY = y3; ii = 0; } } } for (var i = convexPolygons.length - 1; i >= 0; i--) { polygon = convexPolygons[i]; if (0 == polygon.length) { convexPolygons.splice(i, 1); this.polygonPool.free(polygon); polygonIndices = convexPolygonsIndices[i]; convexPolygonsIndices.splice(i, 1); this.polygonIndicesPool.free(polygonIndices); } } return convexPolygons; }; Triangulator.isConcave = function(index, vertexCount, vertices, indices) { var previous = indices[(vertexCount + index - 1) % vertexCount] << 1; var current = indices[index] << 1; var next = indices[(index + 1) % vertexCount] << 1; return !this.positiveArea(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], vertices[next + 1]); }; Triangulator.positiveArea = function(p1x, p1y, p2x, p2y, p3x, p3y) { return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0; }; Triangulator.winding = function(p1x, p1y, p2x, p2y, p3x, p3y) { var px = p2x - p1x, py = p2y - p1y; return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1; }; return Triangulator; })(); spine.Triangulator = Triangulator; })(spine || (spine = {})); var spine; (function(spine) { var IntSet = (function() { function IntSet() { this.array = new Array(); } IntSet.prototype.add = function(value) { var contains = this.contains(value); this.array[0 | value] = 0 | value; return !contains; }; IntSet.prototype.contains = function(value) { return void 0 != this.array[0 | value]; }; IntSet.prototype.remove = function(value) { this.array[0 | value] = void 0; }; IntSet.prototype.clear = function() { this.array.length = 0; }; return IntSet; })(); spine.IntSet = IntSet; var Color = (function() { function Color(r, g, b, a) { void 0 === r && (r = 0); void 0 === g && (g = 0); void 0 === b && (b = 0); void 0 === a && (a = 0); this.r = r; this.g = g; this.b = b; this.a = a; } Color.prototype.set = function(r, g, b, a) { this.r = r; this.g = g; this.b = b; this.a = a; this.clamp(); return this; }; Color.prototype.setFromColor = function(c) { this.r = c.r; this.g = c.g; this.b = c.b; this.a = c.a; return this; }; Color.prototype.setFromString = function(hex) { hex = "#" == hex.charAt(0) ? hex.substr(1) : hex; this.r = parseInt(hex.substr(0, 2), 16) / 255; this.g = parseInt(hex.substr(2, 2), 16) / 255; this.b = parseInt(hex.substr(4, 2), 16) / 255; this.a = (8 != hex.length ? 255 : parseInt(hex.substr(6, 2), 16)) / 255; return this; }; Color.prototype.add = function(r, g, b, a) { this.r += r; this.g += g; this.b += b; this.a += a; this.clamp(); return this; }; Color.prototype.clamp = function() { this.r < 0 ? this.r = 0 : this.r > 1 && (this.r = 1); this.g < 0 ? this.g = 0 : this.g > 1 && (this.g = 1); this.b < 0 ? this.b = 0 : this.b > 1 && (this.b = 1); this.a < 0 ? this.a = 0 : this.a > 1 && (this.a = 1); return this; }; Color.rgba8888ToColor = function(color, value) { color.r = ((4278190080 & value) >>> 24) / 255; color.g = ((16711680 & value) >>> 16) / 255; color.b = ((65280 & value) >>> 8) / 255; color.a = (255 & value) / 255; }; Color.rgb888ToColor = function(color, value) { color.r = ((16711680 & value) >>> 16) / 255; color.g = ((65280 & value) >>> 8) / 255; color.b = (255 & value) / 255; }; Color.WHITE = new Color(1, 1, 1, 1); Color.RED = new Color(1, 0, 0, 1); Color.GREEN = new Color(0, 1, 0, 1); Color.BLUE = new Color(0, 0, 1, 1); Color.MAGENTA = new Color(1, 0, 1, 1); return Color; })(); spine.Color = Color; var MathUtils = (function() { function MathUtils() {} MathUtils.clamp = function(value, min, max) { if (value < min) return min; if (value > max) return max; return value; }; MathUtils.cosDeg = function(degrees) { return Math.cos(degrees * MathUtils.degRad); }; MathUtils.sinDeg = function(degrees) { return Math.sin(degrees * MathUtils.degRad); }; MathUtils.signum = function(value) { return value > 0 ? 1 : value < 0 ? -1 : 0; }; MathUtils.toInt = function(x) { return x > 0 ? Math.floor(x) : Math.ceil(x); }; MathUtils.cbrt = function(x) { var y = Math.pow(Math.abs(x), 1 / 3); return x < 0 ? -y : y; }; MathUtils.randomTriangular = function(min, max) { return MathUtils.randomTriangularWith(min, max, .5 * (min + max)); }; MathUtils.randomTriangularWith = function(min, max, mode) { var u = Math.random(); var d = max - min; if (u <= (mode - min) / d) return min + Math.sqrt(u * d * (mode - min)); return max - Math.sqrt((1 - u) * d * (max - mode)); }; MathUtils.PI = 3.1415927; MathUtils.PI2 = 2 * MathUtils.PI; MathUtils.radiansToDegrees = 180 / MathUtils.PI; MathUtils.radDeg = MathUtils.radiansToDegrees; MathUtils.degreesToRadians = MathUtils.PI / 180; MathUtils.degRad = MathUtils.degreesToRadians; return MathUtils; })(); spine.MathUtils = MathUtils; var Interpolation = (function() { function Interpolation() {} Interpolation.prototype.apply = function(start, end, a) { return start + (end - start) * this.applyInternal(a); }; return Interpolation; })(); spine.Interpolation = Interpolation; var Pow = (function(_super) { __extends(Pow, _super); function Pow(power) { var _this = _super.call(this) || this; _this.power = 2; _this.power = power; return _this; } Pow.prototype.applyInternal = function(a) { if (a <= .5) return Math.pow(2 * a, this.power) / 2; return Math.pow(2 * (a - 1), this.power) / (this.power % 2 == 0 ? -2 : 2) + 1; }; return Pow; })(Interpolation); spine.Pow = Pow; var PowOut = (function(_super) { __extends(PowOut, _super); function PowOut(power) { return _super.call(this, power) || this; } PowOut.prototype.applyInternal = function(a) { return Math.pow(a - 1, this.power) * (this.power % 2 == 0 ? -1 : 1) + 1; }; return PowOut; })(Pow); spine.PowOut = PowOut; var Utils = (function() { function Utils() {} Utils.arrayCopy = function(source, sourceStart, dest, destStart, numElements) { for (var i = sourceStart, j = destStart; i < sourceStart + numElements; i++, j++) dest[j] = source[i]; }; Utils.setArraySize = function(array, size, value) { void 0 === value && (value = 0); var oldSize = array.length; if (oldSize == size) return array; array.length = size; if (oldSize < size) for (var i = oldSize; i < size; i++) array[i] = value; return array; }; Utils.ensureArrayCapacity = function(array, size, value) { void 0 === value && (value = 0); if (array.length >= size) return array; return Utils.setArraySize(array, size, value); }; Utils.newArray = function(size, defaultValue) { var array = new Array(size); for (var i = 0; i < size; i++) array[i] = defaultValue; return array; }; Utils.newFloatArray = function(size) { if (Utils.SUPPORTS_TYPED_ARRAYS) return new Float32Array(size); var array = new Array(size); for (var i = 0; i < array.length; i++) array[i] = 0; return array; }; Utils.newShortArray = function(size) { if (Utils.SUPPORTS_TYPED_ARRAYS) return new Int16Array(size); var array = new Array(size); for (var i = 0; i < array.length; i++) array[i] = 0; return array; }; Utils.toFloatArray = function(array) { return Utils.SUPPORTS_TYPED_ARRAYS ? new Float32Array(array) : array; }; Utils.toSinglePrecision = function(value) { return Utils.SUPPORTS_TYPED_ARRAYS ? Math.fround(value) : value; }; Utils.webkit602BugfixHelper = function(alpha, blend) {}; Utils.contains = function(array, element, identity) { void 0 === identity && (identity = true); for (var i = 0; i < array.length; i++) if (array[i] == element) return true; return false; }; Utils.SUPPORTS_TYPED_ARRAYS = "undefined" !== typeof Float32Array; return Utils; })(); spine.Utils = Utils; var DebugUtils = (function() { function DebugUtils() {} DebugUtils.logBones = function(skeleton) { for (var i = 0; i < skeleton.bones.length; i++) { var bone = skeleton.bones[i]; console.log(bone.data.name + ", " + bone.a + ", " + bone.b + ", " + bone.c + ", " + bone.d + ", " + bone.worldX + ", " + bone.worldY); } }; return DebugUtils; })(); spine.DebugUtils = DebugUtils; var Pool = (function() { function Pool(instantiator) { this.items = new Array(); this.instantiator = instantiator; } Pool.prototype.obtain = function() { return this.items.length > 0 ? this.items.pop() : this.instantiator(); }; Pool.prototype.free = function(item) { item.reset && item.reset(); this.items.push(item); }; Pool.prototype.freeAll = function(items) { for (var i = 0; i < items.length; i++) { items[i].reset && items[i].reset(); this.items[i] = items[i]; } }; Pool.prototype.clear = function() { this.items.length = 0; }; return Pool; })(); spine.Pool = Pool; var Vector2 = (function() { function Vector2(x, y) { void 0 === x && (x = 0); void 0 === y && (y = 0); this.x = x; this.y = y; } Vector2.prototype.set = function(x, y) { this.x = x; this.y = y; return this; }; Vector2.prototype.length = function() { var x = this.x; var y = this.y; return Math.sqrt(x * x + y * y); }; Vector2.prototype.normalize = function() { var len = this.length(); if (0 != len) { this.x /= len; this.y /= len; } return this; }; return Vector2; })(); spine.Vector2 = Vector2; var TimeKeeper = (function() { function TimeKeeper() { this.maxDelta = .064; this.framesPerSecond = 0; this.delta = 0; this.totalTime = 0; this.lastTime = Date.now() / 1e3; this.frameCount = 0; this.frameTime = 0; } TimeKeeper.prototype.update = function() { var now = Date.now() / 1e3; this.delta = now - this.lastTime; this.frameTime += this.delta; this.totalTime += this.delta; this.delta > this.maxDelta && (this.delta = this.maxDelta); this.lastTime = now; this.frameCount++; if (this.frameTime > 1) { this.framesPerSecond = this.frameCount / this.frameTime; this.frameTime = 0; this.frameCount = 0; } }; return TimeKeeper; })(); spine.TimeKeeper = TimeKeeper; var WindowedMean = (function() { function WindowedMean(windowSize) { void 0 === windowSize && (windowSize = 32); this.addedValues = 0; this.lastValue = 0; this.mean = 0; this.dirty = true; this.values = new Array(windowSize); } WindowedMean.prototype.hasEnoughData = function() { return this.addedValues >= this.values.length; }; WindowedMean.prototype.addValue = function(value) { this.addedValues < this.values.length && this.addedValues++; this.values[this.lastValue++] = value; this.lastValue > this.values.length - 1 && (this.lastValue = 0); this.dirty = true; }; WindowedMean.prototype.getMean = function() { if (this.hasEnoughData()) { if (this.dirty) { var mean = 0; for (var i = 0; i < this.values.length; i++) mean += this.values[i]; this.mean = mean / this.values.length; this.dirty = false; } return this.mean; } return 0; }; return WindowedMean; })(); spine.WindowedMean = WindowedMean; })(spine || (spine = {})); (function() { Math.fround || (Math.fround = (function(array) { return function(x) { return array[0] = x, array[0]; }; })(new Float32Array(1))); })(); var spine; (function(spine) { var Attachment = (function() { function Attachment(name) { if (null == name) throw new Error("name cannot be null."); this.name = name; } return Attachment; })(); spine.Attachment = Attachment; var VertexAttachment = (function(_super) { __extends(VertexAttachment, _super); function VertexAttachment(name) { var _this = _super.call(this, name) || this; _this.id = (65535 & VertexAttachment.nextID++) << 11; _this.worldVerticesLength = 0; _this.deformAttachment = _this; return _this; } VertexAttachment.prototype.computeWorldVertices = function(slot, start, count, worldVertices, offset, stride) { count = offset + (count >> 1) * stride; var skeleton = slot.bone.skeleton; var deformArray = slot.deform; var vertices = this.vertices; var bones = this.bones; if (null == bones) { deformArray.length > 0 && (vertices = deformArray); var bone = slot.bone; var x = bone.worldX; var y = bone.worldY; var a = bone.a, b = bone.b, c = bone.c, d = bone.d; for (var v_1 = start, w = offset; w < count; v_1 += 2, w += stride) { var vx = vertices[v_1], vy = vertices[v_1 + 1]; worldVertices[w] = vx * a + vy * b + x; worldVertices[w + 1] = vx * c + vy * d + y; } return; } var v = 0, skip = 0; for (var i = 0; i < start; i += 2) { var n = bones[v]; v += n + 1; skip += n; } var skeletonBones = skeleton.bones; if (0 == deformArray.length) for (var w = offset, b = 3 * skip; w < count; w += stride) { var wx = 0, wy = 0; var n = bones[v++]; n += v; for (;v < n; v++, b += 3) { var bone = skeletonBones[bones[v]]; var vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } else { var deform = deformArray; for (var w = offset, b = 3 * skip, f = skip << 1; w < count; w += stride) { var wx = 0, wy = 0; var n = bones[v++]; n += v; for (;v < n; v++, b += 3, f += 2) { var bone = skeletonBones[bones[v]]; var vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } } }; VertexAttachment.prototype.copyTo = function(attachment) { if (null != this.bones) { attachment.bones = new Array(this.bones.length); spine.Utils.arrayCopy(this.bones, 0, attachment.bones, 0, this.bones.length); } else attachment.bones = null; if (null != this.vertices) { attachment.vertices = spine.Utils.newFloatArray(this.vertices.length); spine.Utils.arrayCopy(this.vertices, 0, attachment.vertices, 0, this.vertices.length); } else attachment.vertices = null; attachment.worldVerticesLength = this.worldVerticesLength; attachment.deformAttachment = this.deformAttachment; }; VertexAttachment.nextID = 0; return VertexAttachment; })(Attachment); spine.VertexAttachment = VertexAttachment; })(spine || (spine = {})); var spine; (function(spine) { var AttachmentType; (function(AttachmentType) { AttachmentType[AttachmentType["Region"] = 0] = "Region"; AttachmentType[AttachmentType["BoundingBox"] = 1] = "BoundingBox"; AttachmentType[AttachmentType["Mesh"] = 2] = "Mesh"; AttachmentType[AttachmentType["LinkedMesh"] = 3] = "LinkedMesh"; AttachmentType[AttachmentType["Path"] = 4] = "Path"; AttachmentType[AttachmentType["Point"] = 5] = "Point"; AttachmentType[AttachmentType["Clipping"] = 6] = "Clipping"; })(AttachmentType = spine.AttachmentType || (spine.AttachmentType = {})); })(spine || (spine = {})); var spine; (function(spine) { var BoundingBoxAttachment = (function(_super) { __extends(BoundingBoxAttachment, _super); function BoundingBoxAttachment(name) { var _this = _super.call(this, name) || this; _this.color = new spine.Color(1, 1, 1, 1); return _this; } BoundingBoxAttachment.prototype.copy = function() { var copy = new BoundingBoxAttachment(name); this.copyTo(copy); copy.color.setFromColor(this.color); return copy; }; return BoundingBoxAttachment; })(spine.VertexAttachment); spine.BoundingBoxAttachment = BoundingBoxAttachment; })(spine || (spine = {})); var spine; (function(spine) { var ClippingAttachment = (function(_super) { __extends(ClippingAttachment, _super); function ClippingAttachment(name) { var _this = _super.call(this, name) || this; _this.color = new spine.Color(.2275, .2275, .8078, 1); return _this; } ClippingAttachment.prototype.copy = function() { var copy = new ClippingAttachment(name); this.copyTo(copy); copy.endSlot = this.endSlot; copy.color.setFromColor(this.color); return copy; }; return ClippingAttachment; })(spine.VertexAttachment); spine.ClippingAttachment = ClippingAttachment; })(spine || (spine = {})); var spine; (function(spine) { var MeshAttachment = (function(_super) { __extends(MeshAttachment, _super); function MeshAttachment(name) { var _this = _super.call(this, name) || this; _this.color = new spine.Color(1, 1, 1, 1); _this.tempColor = new spine.Color(0, 0, 0, 0); return _this; } MeshAttachment.prototype.updateUVs = function() { var regionUVs = this.regionUVs; null != this.uvs && this.uvs.length == regionUVs.length || (this.uvs = spine.Utils.newFloatArray(regionUVs.length)); var uvs = this.uvs; var n = this.uvs.length; var u = this.region.u, v = this.region.v, width = 0, height = 0; if (this.region instanceof spine.TextureAtlasRegion) { var region = this.region; var textureWidth = region.texture.getImage().width, textureHeight = region.texture.getImage().height; switch (region.degrees) { case 90: u -= (region.originalHeight - region.offsetY - region.height) / textureWidth; v -= (region.originalWidth - region.offsetX - region.width) / textureHeight; width = region.originalHeight / textureWidth; height = region.originalWidth / textureHeight; for (var i = 0; i < n; i += 2) { uvs[i] = u + regionUVs[i + 1] * width; uvs[i + 1] = v + (1 - regionUVs[i]) * height; } return; case 180: u -= (region.originalWidth - region.offsetX - region.width) / textureWidth; v -= region.offsetY / textureHeight; width = region.originalWidth / textureWidth; height = region.originalHeight / textureHeight; for (var i = 0; i < n; i += 2) { uvs[i] = u + (1 - regionUVs[i]) * width; uvs[i + 1] = v + (1 - regionUVs[i + 1]) * height; } return; case 270: u -= region.offsetY / textureWidth; v -= region.offsetX / textureHeight; width = region.originalHeight / textureWidth; height = region.originalWidth / textureHeight; for (var i = 0; i < n; i += 2) { uvs[i] = u + (1 - regionUVs[i + 1]) * width; uvs[i + 1] = v + regionUVs[i] * height; } return; } u -= region.offsetX / textureWidth; v -= (region.originalHeight - region.offsetY - region.height) / textureHeight; width = region.originalWidth / textureWidth; height = region.originalHeight / textureHeight; } else if (null == this.region) { u = v = 0; width = height = 1; } else { width = this.region.u2 - u; height = this.region.v2 - v; } for (var i = 0; i < n; i += 2) { uvs[i] = u + regionUVs[i] * width; uvs[i + 1] = v + regionUVs[i + 1] * height; } }; MeshAttachment.prototype.getParentMesh = function() { return this.parentMesh; }; MeshAttachment.prototype.setParentMesh = function(parentMesh) { this.parentMesh = parentMesh; if (null != parentMesh) { this.bones = parentMesh.bones; this.vertices = parentMesh.vertices; this.worldVerticesLength = parentMesh.worldVerticesLength; this.regionUVs = parentMesh.regionUVs; this.triangles = parentMesh.triangles; this.hullLength = parentMesh.hullLength; this.worldVerticesLength = parentMesh.worldVerticesLength; } }; MeshAttachment.prototype.copy = function() { if (null != this.parentMesh) return this.newLinkedMesh(); var copy = new MeshAttachment(this.name); copy.region = this.region; copy.path = this.path; copy.color.setFromColor(this.color); this.copyTo(copy); copy.regionUVs = new Array(this.regionUVs.length); spine.Utils.arrayCopy(this.regionUVs, 0, copy.regionUVs, 0, this.regionUVs.length); copy.uvs = new Array(this.uvs.length); spine.Utils.arrayCopy(this.uvs, 0, copy.uvs, 0, this.uvs.length); copy.triangles = new Array(this.triangles.length); spine.Utils.arrayCopy(this.triangles, 0, copy.triangles, 0, this.triangles.length); copy.hullLength = this.hullLength; if (null != this.edges) { copy.edges = new Array(this.edges.length); spine.Utils.arrayCopy(this.edges, 0, copy.edges, 0, this.edges.length); } copy.width = this.width; copy.height = this.height; return copy; }; MeshAttachment.prototype.newLinkedMesh = function() { var copy = new MeshAttachment(this.name); copy.region = this.region; copy.path = this.path; copy.color.setFromColor(this.color); copy.deformAttachment = this.deformAttachment; copy.setParentMesh(null != this.parentMesh ? this.parentMesh : this); copy.updateUVs(); return copy; }; return MeshAttachment; })(spine.VertexAttachment); spine.MeshAttachment = MeshAttachment; })(spine || (spine = {})); var spine; (function(spine) { var PathAttachment = (function(_super) { __extends(PathAttachment, _super); function PathAttachment(name) { var _this = _super.call(this, name) || this; _this.closed = false; _this.constantSpeed = false; _this.color = new spine.Color(1, 1, 1, 1); return _this; } PathAttachment.prototype.copy = function() { var copy = new PathAttachment(name); this.copyTo(copy); copy.lengths = new Array(this.lengths.length); spine.Utils.arrayCopy(this.lengths, 0, copy.lengths, 0, this.lengths.length); copy.closed = closed; copy.constantSpeed = this.constantSpeed; copy.color.setFromColor(this.color); return copy; }; return PathAttachment; })(spine.VertexAttachment); spine.PathAttachment = PathAttachment; })(spine || (spine = {})); var spine; (function(spine) { var PointAttachment = (function(_super) { __extends(PointAttachment, _super); function PointAttachment(name) { var _this = _super.call(this, name) || this; _this.color = new spine.Color(.38, .94, 0, 1); return _this; } PointAttachment.prototype.computeWorldPosition = function(bone, point) { point.x = this.x * bone.a + this.y * bone.b + bone.worldX; point.y = this.x * bone.c + this.y * bone.d + bone.worldY; return point; }; PointAttachment.prototype.computeWorldRotation = function(bone) { var cos = spine.MathUtils.cosDeg(this.rotation), sin = spine.MathUtils.sinDeg(this.rotation); var x = cos * bone.a + sin * bone.b; var y = cos * bone.c + sin * bone.d; return Math.atan2(y, x) * spine.MathUtils.radDeg; }; PointAttachment.prototype.copy = function() { var copy = new PointAttachment(name); copy.x = this.x; copy.y = this.y; copy.rotation = this.rotation; copy.color.setFromColor(this.color); return copy; }; return PointAttachment; })(spine.VertexAttachment); spine.PointAttachment = PointAttachment; })(spine || (spine = {})); var spine; (function(spine) { var RegionAttachment = (function(_super) { __extends(RegionAttachment, _super); function RegionAttachment(name) { var _this = _super.call(this, name) || this; _this.x = 0; _this.y = 0; _this.scaleX = 1; _this.scaleY = 1; _this.rotation = 0; _this.width = 0; _this.height = 0; _this.color = new spine.Color(1, 1, 1, 1); _this.offset = spine.Utils.newFloatArray(8); _this.uvs = spine.Utils.newFloatArray(8); _this.tempColor = new spine.Color(1, 1, 1, 1); return _this; } RegionAttachment.prototype.updateOffset = function() { var regionScaleX = this.width / this.region.originalWidth * this.scaleX; var regionScaleY = this.height / this.region.originalHeight * this.scaleY; var localX = -this.width / 2 * this.scaleX + this.region.offsetX * regionScaleX; var localY = -this.height / 2 * this.scaleY + this.region.offsetY * regionScaleY; var localX2 = localX + this.region.width * regionScaleX; var localY2 = localY + this.region.height * regionScaleY; var radians = this.rotation * Math.PI / 180; var cos = Math.cos(radians); var sin = Math.sin(radians); var localXCos = localX * cos + this.x; var localXSin = localX * sin; var localYCos = localY * cos + this.y; var localYSin = localY * sin; var localX2Cos = localX2 * cos + this.x; var localX2Sin = localX2 * sin; var localY2Cos = localY2 * cos + this.y; var localY2Sin = localY2 * sin; var offset = this.offset; offset[RegionAttachment.OX1] = localXCos - localYSin; offset[RegionAttachment.OY1] = localYCos + localXSin; offset[RegionAttachment.OX2] = localXCos - localY2Sin; offset[RegionAttachment.OY2] = localY2Cos + localXSin; offset[RegionAttachment.OX3] = localX2Cos - localY2Sin; offset[RegionAttachment.OY3] = localY2Cos + localX2Sin; offset[RegionAttachment.OX4] = localX2Cos - localYSin; offset[RegionAttachment.OY4] = localYCos + localX2Sin; }; RegionAttachment.prototype.setRegion = function(region) { this.region = region; var uvs = this.uvs; if (90 === region.degrees) { uvs[2] = region.u; uvs[3] = region.v2; uvs[4] = region.u; uvs[5] = region.v; uvs[6] = region.u2; uvs[7] = region.v; uvs[0] = region.u2; uvs[1] = region.v2; } else if (270 === region.degrees) { uvs[6] = region.u; uvs[7] = region.v2; uvs[0] = region.u; uvs[1] = region.v; uvs[2] = region.u2; uvs[3] = region.v; uvs[4] = region.u2; uvs[5] = region.v2; } else { uvs[0] = region.u; uvs[1] = region.v2; uvs[2] = region.u; uvs[3] = region.v; uvs[4] = region.u2; uvs[5] = region.v; uvs[6] = region.u2; uvs[7] = region.v2; } }; RegionAttachment.prototype.computeWorldVertices = function(bone, worldVertices, offset, stride) { var vertexOffset = this.offset; var x = bone.worldX, y = bone.worldY; var a = bone.a, b = bone.b, c = bone.c, d = bone.d; var offsetX = 0, offsetY = 0; offsetX = vertexOffset[RegionAttachment.OX1]; offsetY = vertexOffset[RegionAttachment.OY1]; worldVertices[offset] = offsetX * a + offsetY * b + x; worldVertices[offset + 1] = offsetX * c + offsetY * d + y; offset += stride; offsetX = vertexOffset[RegionAttachment.OX2]; offsetY = vertexOffset[RegionAttachment.OY2]; worldVertices[offset] = offsetX * a + offsetY * b + x; worldVertices[offset + 1] = offsetX * c + offsetY * d + y; offset += stride; offsetX = vertexOffset[RegionAttachment.OX3]; offsetY = vertexOffset[RegionAttachment.OY3]; worldVertices[offset] = offsetX * a + offsetY * b + x; worldVertices[offset + 1] = offsetX * c + offsetY * d + y; offset += stride; offsetX = vertexOffset[RegionAttachment.OX4]; offsetY = vertexOffset[RegionAttachment.OY4]; worldVertices[offset] = offsetX * a + offsetY * b + x; worldVertices[offset + 1] = offsetX * c + offsetY * d + y; }; RegionAttachment.prototype.copy = function() { var copy = new RegionAttachment(name); copy.region = this.region; copy.rendererObject = this.rendererObject; copy.path = this.path; copy.x = this.x; copy.y = this.y; copy.scaleX = this.scaleX; copy.scaleY = this.scaleY; copy.rotation = this.rotation; copy.width = this.width; copy.height = this.height; spine.Utils.arrayCopy(this.uvs, 0, copy.uvs, 0, 8); spine.Utils.arrayCopy(this.offset, 0, copy.offset, 0, 8); copy.color.setFromColor(this.color); return copy; }; RegionAttachment.OX1 = 0; RegionAttachment.OY1 = 1; RegionAttachment.OX2 = 2; RegionAttachment.OY2 = 3; RegionAttachment.OX3 = 4; RegionAttachment.OY3 = 5; RegionAttachment.OX4 = 6; RegionAttachment.OY4 = 7; RegionAttachment.X1 = 0; RegionAttachment.Y1 = 1; RegionAttachment.C1R = 2; RegionAttachment.C1G = 3; RegionAttachment.C1B = 4; RegionAttachment.C1A = 5; RegionAttachment.U1 = 6; RegionAttachment.V1 = 7; RegionAttachment.X2 = 8; RegionAttachment.Y2 = 9; RegionAttachment.C2R = 10; RegionAttachment.C2G = 11; RegionAttachment.C2B = 12; RegionAttachment.C2A = 13; RegionAttachment.U2 = 14; RegionAttachment.V2 = 15; RegionAttachment.X3 = 16; RegionAttachment.Y3 = 17; RegionAttachment.C3R = 18; RegionAttachment.C3G = 19; RegionAttachment.C3B = 20; RegionAttachment.C3A = 21; RegionAttachment.U3 = 22; RegionAttachment.V3 = 23; RegionAttachment.X4 = 24; RegionAttachment.Y4 = 25; RegionAttachment.C4R = 26; RegionAttachment.C4G = 27; RegionAttachment.C4B = 28; RegionAttachment.C4A = 29; RegionAttachment.U4 = 30; RegionAttachment.V4 = 31; return RegionAttachment; })(spine.Attachment); spine.RegionAttachment = RegionAttachment; })(spine || (spine = {})); var spine; (function(spine) { var JitterEffect = (function() { function JitterEffect(jitterX, jitterY) { this.jitterX = 0; this.jitterY = 0; this.jitterX = jitterX; this.jitterY = jitterY; } JitterEffect.prototype.begin = function(skeleton) {}; JitterEffect.prototype.transform = function(position, uv, light, dark) { position.x += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY); position.y += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY); }; JitterEffect.prototype.end = function() {}; return JitterEffect; })(); spine.JitterEffect = JitterEffect; })(spine || (spine = {})); var spine; (function(spine) { var SwirlEffect = (function() { function SwirlEffect(radius, interpolation) { this.centerX = 0; this.centerY = 0; this.radius = 0; this.angle = 0; this.worldX = 0; this.worldY = 0; this.radius = radius; this.interpolation = interpolation; } SwirlEffect.prototype.begin = function(skeleton) { this.worldX = skeleton.x + this.centerX; this.worldY = skeleton.y + this.centerY; }; SwirlEffect.prototype.transform = function(position, uv, light, dark) { var radAngle = this.angle * spine.MathUtils.degreesToRadians; var x = position.x - this.worldX; var y = position.y - this.worldY; var dist = Math.sqrt(x * x + y * y); if (dist < this.radius) { var theta = this.interpolation.apply(0, radAngle, (this.radius - dist) / this.radius); var cos = Math.cos(theta); var sin = Math.sin(theta); position.x = cos * x - sin * y + this.worldX; position.y = sin * x + cos * y + this.worldY; } }; SwirlEffect.prototype.end = function() {}; SwirlEffect.interpolation = new spine.PowOut(2); return SwirlEffect; })(); spine.SwirlEffect = SwirlEffect; })(spine || (spine = {})); module.exports = spine; }), {} ], 289: [ (function(require, module, exports) { "use strict"; var TrackEntryListeners = require("./track-entry-listeners"); var spine = require("./lib/spine"); var MaxCacheTime = 30; var FrameTime = 1 / 60; var _vertices = []; var _indices = []; var _boneInfoOffset = 0; var _vertexOffset = 0; var _indexOffset = 0; var _vfOffset = 0; var _preTexUrl = null; var _preBlendMode = null; var _segVCount = 0; var _segICount = 0; var _segOffset = 0; var _colorOffset = 0; var _preFinalColor = null; var _preDarkColor = null; var _perVertexSize = 6; var _perClipVertexSize = 12; var _vfCount = 0, _indexCount = 0; var _tempr, _tempg, _tempb, _tempa; var _finalColor32, _darkColor32; var _finalColor = new spine.Color(1, 1, 1, 1); var _darkColor = new spine.Color(1, 1, 1, 1); var _quadTriangles = [ 0, 1, 2, 2, 3, 0 ]; var AnimationCache = cc.Class({ ctor: function ctor() { this._privateMode = false; this._inited = false; this._invalid = true; this._enableCacheAttachedInfo = false; this.frames = []; this.totalTime = 0; this._frameIdx = -1; this.isCompleted = false; this._skeletonInfo = null; this._animationName = null; this._tempSegments = null; this._tempColors = null; this._tempBoneInfos = null; }, init: function init(skeletonInfo, animationName) { this._inited = true; this._animationName = animationName; this._skeletonInfo = skeletonInfo; }, clear: function clear() { this._inited = false; for (var i = 0, n = this.frames.length; i < n; i++) { var frame = this.frames[i]; frame.segments.length = 0; } this.invalidAllFrame(); }, bind: function bind(listener) { var completeHandle = function(entry) { entry && entry.animation.name === this._animationName && (this.isCompleted = true); }.bind(this); listener.complete = completeHandle; }, unbind: function unbind(listener) { listener.complete = null; }, begin: function begin() { if (!this._invalid) return; var skeletonInfo = this._skeletonInfo; var preAnimationCache = skeletonInfo.curAnimationCache; preAnimationCache && preAnimationCache !== this && (this._privateMode ? preAnimationCache.invalidAllFrame() : preAnimationCache.updateToFrame()); var skeleton = skeletonInfo.skeleton; var listener = skeletonInfo.listener; var state = skeletonInfo.state; var animation = skeleton.data.findAnimation(this._animationName); state.setAnimationWith(0, animation, false); this.bind(listener); skeletonInfo.curAnimationCache = this; this._frameIdx = -1; this.isCompleted = false; this.totalTime = 0; this._invalid = false; }, end: function end() { if (!this._needToUpdate()) { this._skeletonInfo.curAnimationCache = null; this.frames.length = this._frameIdx + 1; this.isCompleted = true; this.unbind(this._skeletonInfo.listener); } }, _needToUpdate: function _needToUpdate(toFrameIdx) { return !this.isCompleted && this.totalTime < MaxCacheTime && (void 0 == toFrameIdx || this._frameIdx < toFrameIdx); }, updateToFrame: function updateToFrame(toFrameIdx) { if (!this._inited) return; this.begin(); if (!this._needToUpdate(toFrameIdx)) return; var skeletonInfo = this._skeletonInfo; var skeleton = skeletonInfo.skeleton; var clipper = skeletonInfo.clipper; var state = skeletonInfo.state; do { skeleton.update(FrameTime); state.update(FrameTime); state.apply(skeleton); skeleton.updateWorldTransform(); this._frameIdx++; this._updateFrame(skeleton, clipper, this._frameIdx); this.totalTime += FrameTime; } while (this._needToUpdate(toFrameIdx)); this.end(); }, isInited: function isInited() { return this._inited; }, isInvalid: function isInvalid() { return this._invalid; }, invalidAllFrame: function invalidAllFrame() { this.isCompleted = false; this._invalid = true; }, updateAllFrame: function updateAllFrame() { this.invalidAllFrame(); this.updateToFrame(); }, enableCacheAttachedInfo: function enableCacheAttachedInfo() { if (!this._enableCacheAttachedInfo) { this._enableCacheAttachedInfo = true; this.invalidAllFrame(); } }, _updateFrame: function _updateFrame(skeleton, clipper, index) { _vfOffset = 0; _boneInfoOffset = 0; _indexOffset = 0; _vertexOffset = 0; _preTexUrl = null; _preBlendMode = null; _segVCount = 0; _segICount = 0; _segOffset = 0; _colorOffset = 0; _preFinalColor = null; _preDarkColor = null; this.frames[index] = this.frames[index] || { segments: [], colors: [], boneInfos: [], vertices: null, verticesMulti: null, uintVert: null, indices: null }; var frame = this.frames[index]; var segments = this._tempSegments = frame.segments; var colors = this._tempColors = frame.colors; var boneInfos = this._tempBoneInfos = frame.boneInfos; this._traverseSkeleton(skeleton, clipper); _colorOffset > 0 && (colors[_colorOffset - 1].vfOffset = _vfOffset); colors.length = _colorOffset; boneInfos.length = _boneInfoOffset; var preSegOffset = _segOffset - 1; if (preSegOffset >= 0) if (_segICount > 0) { var preSegInfo = segments[preSegOffset]; preSegInfo.indexCount = _segICount; preSegInfo.vfCount = _segVCount * _perVertexSize; preSegInfo.vertexCount = _segVCount; segments.length = _segOffset; } else segments.length = _segOffset - 1; if (0 == segments.length) return; var vertices = frame.vertices; var uintVert = frame.uintVert; if (!vertices || vertices.length < _vfOffset) { vertices = frame.vertices = new Float32Array(_vfOffset); uintVert = frame.uintVert = new Uint32Array(vertices.buffer); } for (var i = 0, j = 0; i < _vfOffset; ) { vertices[i++] = _vertices[j++]; vertices[i++] = _vertices[j++]; vertices[i++] = _vertices[j++]; vertices[i++] = _vertices[j++]; uintVert[i++] = _vertices[j++]; uintVert[i++] = _vertices[j++]; } var indices = frame.indices; (!indices || indices.length < _indexOffset) && (indices = frame.indices = new Uint16Array(_indexOffset)); for (var _i = 0; _i < _indexOffset; _i++) indices[_i] = _indices[_i]; frame.vertices = vertices; frame.uintVert = uintVert; frame.indices = indices; }, fillVertices: function fillVertices(skeletonColor, attachmentColor, slotColor, clipper, slot) { _tempa = slotColor.a * attachmentColor.a * skeletonColor.a * 255; _tempr = attachmentColor.r * skeletonColor.r * 255; _tempg = attachmentColor.g * skeletonColor.g * 255; _tempb = attachmentColor.b * skeletonColor.b * 255; _finalColor.r = _tempr * slotColor.r; _finalColor.g = _tempg * slotColor.g; _finalColor.b = _tempb * slotColor.b; _finalColor.a = _tempa; if (null == slot.darkColor) _darkColor.set(0, 0, 0, 1); else { _darkColor.r = slot.darkColor.r * _tempr; _darkColor.g = slot.darkColor.g * _tempg; _darkColor.b = slot.darkColor.b * _tempb; } _darkColor.a = 0; _finalColor32 = (_finalColor.a << 24 >>> 0) + (_finalColor.b << 16) + (_finalColor.g << 8) + _finalColor.r; _darkColor32 = (_darkColor.a << 24 >>> 0) + (_darkColor.b << 16) + (_darkColor.g << 8) + _darkColor.r; if (_preFinalColor !== _finalColor32 || _preDarkColor !== _darkColor32) { var colors = this._tempColors; _preFinalColor = _finalColor32; _preDarkColor = _darkColor32; _colorOffset > 0 && (colors[_colorOffset - 1].vfOffset = _vfOffset); colors[_colorOffset++] = { fr: _finalColor.r, fg: _finalColor.g, fb: _finalColor.b, fa: _finalColor.a, dr: _darkColor.r, dg: _darkColor.g, db: _darkColor.b, da: _darkColor.a, vfOffset: 0 }; } if (clipper.isClipping()) { clipper.clipTriangles(_vertices, _vfCount, _indices, _indexCount, _vertices, _finalColor, _darkColor, true, _perVertexSize, _indexOffset, _vfOffset, _vfOffset + 2); var clippedVertices = clipper.clippedVertices; var clippedTriangles = clipper.clippedTriangles; _indexCount = clippedTriangles.length; _vfCount = clippedVertices.length / _perClipVertexSize * _perVertexSize; for (var ii = 0, jj = _indexOffset, nn = clippedTriangles.length; ii < nn; ) _indices[jj++] = clippedTriangles[ii++]; for (var _v = 0, _n = clippedVertices.length, offset = _vfOffset; _v < _n; _v += 12, offset += _perVertexSize) { _vertices[offset] = clippedVertices[_v]; _vertices[offset + 1] = clippedVertices[_v + 1]; _vertices[offset + 2] = clippedVertices[_v + 6]; _vertices[offset + 3] = clippedVertices[_v + 7]; _vertices[offset + 4] = _finalColor32; _vertices[offset + 5] = _darkColor32; } } else for (var v = _vfOffset, n = _vfOffset + _vfCount; v < n; v += _perVertexSize) { _vertices[v + 4] = _finalColor32; _vertices[v + 5] = _darkColor32; } }, _traverseSkeleton: function _traverseSkeleton(skeleton, clipper) { var segments = this._tempSegments; var boneInfos = this._tempBoneInfos; var skeletonColor = skeleton.color; var attachment, attachmentColor, slotColor, uvs, triangles; var isRegion, isMesh, isClip; var texture; var preSegOffset, preSegInfo; var blendMode; var slot; var bones = skeleton.bones; if (this._enableCacheAttachedInfo) for (var i = 0, l = bones.length; i < l; i++, _boneInfoOffset++) { var bone = bones[i]; var boneInfo = boneInfos[_boneInfoOffset]; boneInfo || (boneInfo = boneInfos[_boneInfoOffset] = {}); boneInfo.a = bone.a; boneInfo.b = bone.b; boneInfo.c = bone.c; boneInfo.d = bone.d; boneInfo.worldX = bone.worldX; boneInfo.worldY = bone.worldY; } for (var slotIdx = 0, slotCount = skeleton.drawOrder.length; slotIdx < slotCount; slotIdx++) { slot = skeleton.drawOrder[slotIdx]; if (!slot.bone.active) continue; _vfCount = 0; _indexCount = 0; attachment = slot.getAttachment(); if (!attachment) { clipper.clipEndWithSlot(slot); continue; } isRegion = attachment instanceof spine.RegionAttachment; isMesh = attachment instanceof spine.MeshAttachment; isClip = attachment instanceof spine.ClippingAttachment; if (isClip) { clipper.clipStart(slot, attachment); continue; } if (!isRegion && !isMesh) { clipper.clipEndWithSlot(slot); continue; } texture = attachment.region.texture._texture; if (!texture) { clipper.clipEndWithSlot(slot); continue; } blendMode = slot.data.blendMode; if (_preTexUrl !== texture._texture._id || _preBlendMode !== blendMode) { _preTexUrl = texture._texture._id; _preBlendMode = blendMode; preSegOffset = _segOffset - 1; if (preSegOffset >= 0) if (_segICount > 0) { preSegInfo = segments[preSegOffset]; preSegInfo.indexCount = _segICount; preSegInfo.vertexCount = _segVCount; preSegInfo.vfCount = _segVCount * _perVertexSize; } else _segOffset--; segments[_segOffset] = { tex: texture, blendMode: blendMode, indexCount: 0, vertexCount: 0, vfCount: 0 }; _segOffset++; _segICount = 0; _segVCount = 0; } if (isRegion) { triangles = _quadTriangles; _vfCount = 4 * _perVertexSize; _indexCount = 6; attachment.computeWorldVertices(slot.bone, _vertices, _vfOffset, _perVertexSize); } else if (isMesh) { triangles = attachment.triangles; _vfCount = (attachment.worldVerticesLength >> 1) * _perVertexSize; _indexCount = triangles.length; attachment.computeWorldVertices(slot, 0, attachment.worldVerticesLength, _vertices, _vfOffset, _perVertexSize); } if (0 == _vfCount || 0 == _indexCount) { clipper.clipEndWithSlot(slot); continue; } for (var ii = 0, jj = _indexOffset, nn = triangles.length; ii < nn; ) _indices[jj++] = triangles[ii++]; uvs = attachment.uvs; for (var v = _vfOffset, n = _vfOffset + _vfCount, u = 0; v < n; v += _perVertexSize, u += 2) { _vertices[v + 2] = uvs[u]; _vertices[v + 3] = uvs[u + 1]; } attachmentColor = attachment.color; slotColor = slot.color; this.fillVertices(skeletonColor, attachmentColor, slotColor, clipper, slot); if (_indexCount > 0) { for (var _ii = _indexOffset, _nn = _indexOffset + _indexCount; _ii < _nn; _ii++) _indices[_ii] += _segVCount; _indexOffset += _indexCount; _vfOffset += _vfCount; _vertexOffset = _vfOffset / _perVertexSize; _segICount += _indexCount; _segVCount += _vfCount / _perVertexSize; } clipper.clipEndWithSlot(slot); } clipper.clipEnd(); } }); var SkeletonCache = cc.Class({ ctor: function ctor() { this._privateMode = false; this._animationPool = {}; this._skeletonCache = {}; }, enablePrivateMode: function enablePrivateMode() { this._privateMode = true; }, clear: function clear() { this._animationPool = {}; this._skeletonCache = {}; }, removeSkeleton: function removeSkeleton(uuid) { var skeletonInfo = this._skeletonCache[uuid]; if (!skeletonInfo) return; var animationsCache = skeletonInfo.animationsCache; for (var aniKey in animationsCache) { var animationCache = animationsCache[aniKey]; if (!animationCache) continue; this._animationPool[uuid + "#" + aniKey] = animationCache; animationCache.clear(); } delete this._skeletonCache[uuid]; }, getSkeletonCache: function getSkeletonCache(uuid, skeletonData) { var skeletonInfo = this._skeletonCache[uuid]; if (!skeletonInfo) { var skeleton = new spine.Skeleton(skeletonData); var clipper = new spine.SkeletonClipping(); var stateData = new spine.AnimationStateData(skeleton.data); var state = new spine.AnimationState(stateData); var listener = new TrackEntryListeners(); state.addListener(listener); this._skeletonCache[uuid] = skeletonInfo = { skeleton: skeleton, clipper: clipper, state: state, listener: listener, animationsCache: {}, curAnimationCache: null }; } return skeletonInfo; }, getAnimationCache: function getAnimationCache(uuid, animationName) { var skeletonInfo = this._skeletonCache[uuid]; if (!skeletonInfo) return null; var animationsCache = skeletonInfo.animationsCache; return animationsCache[animationName]; }, invalidAnimationCache: function invalidAnimationCache(uuid) { var skeletonInfo = this._skeletonCache[uuid]; var skeleton = skeletonInfo && skeletonInfo.skeleton; if (!skeleton) return; var animationsCache = skeletonInfo.animationsCache; for (var aniKey in animationsCache) { var animationCache = animationsCache[aniKey]; animationCache.invalidAllFrame(); } }, initAnimationCache: function initAnimationCache(uuid, animationName) { if (!animationName) return null; var skeletonInfo = this._skeletonCache[uuid]; var skeleton = skeletonInfo && skeletonInfo.skeleton; if (!skeleton) return null; var animation = skeleton.data.findAnimation(animationName); if (!animation) return null; var animationsCache = skeletonInfo.animationsCache; var animationCache = animationsCache[animationName]; if (!animationCache) { var poolKey = uuid + "#" + animationName; animationCache = this._animationPool[poolKey]; if (animationCache) delete this._animationPool[poolKey]; else { animationCache = new AnimationCache(); animationCache._privateMode = this._privateMode; } animationCache.init(skeletonInfo, animationName); animationsCache[animationName] = animationCache; } return animationCache; }, updateAnimationCache: function updateAnimationCache(uuid, animationName) { if (animationName) { var animationCache = this.initAnimationCache(uuid, animationName); if (!animationCache) return null; animationCache.updateAllFrame(); } else { var skeletonInfo = this._skeletonCache[uuid]; var skeleton = skeletonInfo && skeletonInfo.skeleton; if (!skeleton) return; var animationsCache = skeletonInfo.animationsCache; for (var aniKey in animationsCache) { var _animationCache = animationsCache[aniKey]; _animationCache.updateAllFrame(); } } } }); SkeletonCache.FrameTime = FrameTime; SkeletonCache.sharedCache = new SkeletonCache(); module.exports = SkeletonCache; }), { "./lib/spine": 288, "./track-entry-listeners": 293 } ], 290: [ (function(require, module, exports) { "use strict"; function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = "undefined" !== typeof Symbol && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && "number" === typeof o.length) { it && (o = it); var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if ("string" === typeof o) return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); "Object" === n && o.constructor && (n = o.constructor.name); if ("Map" === n || "Set" === n) return Array.from(o); if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { (null == len || len > arr.length) && (len = arr.length); for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var SkeletonCache = (true, require("./skeleton-cache").sharedCache); var RegionData = (function() { RegionData.updateUV = function updateUV(region) { var texture = region.texture._texture; if (region.rotate) { region.u = region.x / texture.width; region.v = region.y / texture.height; region.u2 = (region.x + region.height) / texture.width; region.v2 = (region.y + region.width) / texture.height; } else { region.u = region.x / texture.width; region.v = region.y / texture.height; region.u2 = (region.x + region.width) / texture.width; region.v2 = (region.y + region.height) / texture.height; } }; function RegionData(attachmentOrSpriteFrame) { this.x = void 0; this.y = void 0; this.degrees = void 0; this.texture = void 0; this.texture2D = void 0; this.u = void 0; this.v = void 0; this.u2 = void 0; this.v2 = void 0; this.width = void 0; this.height = void 0; this.rotate = void 0; this.offsetX = void 0; this.offsetY = void 0; this.originalWidth = void 0; this.originalHeight = void 0; attachmentOrSpriteFrame instanceof cc.SpriteFrame ? this.initWithSpriteFrame(attachmentOrSpriteFrame) : null != attachmentOrSpriteFrame && this.initWithAttachment(attachmentOrSpriteFrame); } var _proto = RegionData.prototype; _proto.initWithSpriteFrame = function initWithSpriteFrame(spriteFrame) { var texture = spriteFrame.getTexture(); var rect = spriteFrame.getRect(); var origSize = spriteFrame.getOriginalSize(); var _offset = spriteFrame.getOffset(); var rotate = spriteFrame.isRotated(); var offset = cc.v2(.5 * (origSize.width - rect.width) + _offset.x, .5 * (origSize.height - rect.height) + _offset.y); var degrees = rotate ? 270 : 0; this.x = rect.x; this.y = rect.y; this.width = rect.width; this.height = rect.height; this.originalWidth = origSize.width; this.originalHeight = origSize.height; this.offsetX = offset.x; this.offsetY = offset.y; this.rotate = 0 != degrees; this.degrees = degrees; this.updateWithTexture2D(texture); }; _proto.initWithAttachment = function initWithAttachment(attachment) { false; var region = attachment.region; this.x = region.x; this.y = region.y; this.width = region.width; this.height = region.height; this.originalWidth = region.originalWidth; this.originalHeight = region.originalHeight; this.offsetX = region.offsetX; this.offsetY = region.offsetY; this.rotate = region.rotate; this.degrees = region.degrees; this.texture = region.texture; this.texture2D = region.texture._texture; this.u = region.u; this.u2 = region.u2; this.v = region.v; this.v2 = region.v2; }; _proto.updateUV = function updateUV() { RegionData.updateUV(this); }; _proto.updateWithPackedFrame = function updateWithPackedFrame(packedFrame) { this.x = packedFrame.x; this.y = packedFrame.y; this.updateWithTexture2D(packedFrame.texture); }; _proto.updateWithTexture2D = function updateWithTexture2D(texture2d) { var spTex; false; this.texture = new sp.SkeletonTexture({ width: texture2d.width, height: texture2d.height }); this.texture.setRealTexture(texture2d); this.texture2D = texture2d; this.updateUV(); }; _proto.toSpriteFrame = function toSpriteFrame(strict) { if (strict && (270 !== this.degrees || 0 !== this.degrees)) return null; var frame = new cc.SpriteFrame(this.texture2D, cc.rect(this.x, this.y, this.width, this.height), this.rotate, cc.v2(this.offsetX - .5 * (this.originalWidth - this.width), this.offsetY - .5 * (this.originalHeight - this.height)), cc.size(this.originalWidth, this.originalHeight)); return frame; }; _proto.assignToAttachment = function assignToAttachment(attachment, strict, resetDynamicAtlas) { void 0 === strict && (strict = true); void 0 === resetDynamicAtlas && (resetDynamicAtlas = true); var spriteFrame; false; var region = attachment.region; if (resetDynamicAtlas && region && region._spriteFrame) { var _spriteFrame = region._spriteFrame; region._spriteFrame = null; _spriteFrame.destroy(); } if (strict) { region.x = this.x; region.y = this.y; region.width = this.width; region.height = this.height; region.originalWidth = this.originalWidth; region.originalHeight = this.originalHeight; region.offsetX = this.offsetX; region.offsetY = this.offsetY; region.rotate = this.rotate; region.degrees = this.degrees; region.texture = this.texture; region.u = this.u; region.u2 = this.u2; region.v = this.v; region.v2 = this.v2; } if (attachment instanceof sp.spine.MeshAttachment) attachment.updateUVs(); else if (attachment instanceof sp.spine.RegionAttachment) { attachment.setRegion(region); attachment.updateOffset(); } }; _proto.reset = function reset() { this.texture = null; this.texture2D = null; }; return RegionData; })(); RegionData.middlewareTextureID = -1; var SkeletonData = cc.Class({ name: "sp.SkeletonData", extends: cc.Asset, ctor: function ctor() { this.reset(); }, properties: { _skeletonJson: null, skeletonJsonStr: { get: function get() { return this._skeletonJson ? JSON.stringify(this._skeletonJson) : ""; } }, skeletonJson: { get: function get() { return this._skeletonJson; }, set: function set(value) { this.reset(); this._skeletonJson = "string" == typeof value ? JSON.parse(value) : value; !this._uuid && value.skeleton && (this._uuid = value.skeleton.hash); } }, _atlasText: "", atlasText: { get: function get() { return this._atlasText; }, set: function set(value) { this._atlasText = value; this.reset(); } }, textures: { default: [], type: [ cc.Texture2D ] }, textureNames: { default: [], type: [ cc.String ] }, scale: 1, _nativeAsset: { get: function get() { return this._buffer; }, set: function set(bin) { this._buffer = bin.buffer || bin; this.reset(); }, override: true } }, statics: { preventDeferredLoadDependents: true, cloneId: 0 }, createNode: false, reset: function reset() { this._skeletonCache = null; this._atlasCache = null; false; }, ensureTexturesLoaded: function ensureTexturesLoaded(loaded, caller) { var textures = this.textures; var texsLen = textures.length; if (0 == texsLen) { loaded.call(caller, false); return; } var loadedCount = 0; var loadedItem = function loadedItem() { loadedCount++; if (loadedCount >= texsLen) { loaded && loaded.call(caller, true); loaded = null; } }; for (var i = 0; i < texsLen; i++) { var tex = textures[i]; tex.loaded ? loadedItem() : tex.once("load", loadedItem); } }, isTexturesLoaded: function isTexturesLoaded() { var textures = this.textures; var texsLen = textures.length; for (var i = 0; i < texsLen; i++) { var tex = textures[i]; if (!tex.loaded) return false; } return true; }, getRuntimeData: function getRuntimeData(quiet) { if (this._skeletonCache) return this._skeletonCache; if (!(this.textures && this.textures.length > 0) && this.textureNames && this.textureNames.length > 0) { quiet || cc.errorID(7507, this.name); return null; } var atlas = this._getAtlas(quiet); if (!atlas) return null; var attachmentLoader = new sp.spine.AtlasAttachmentLoader(atlas); var resData = null; var reader = null; if (this.skeletonJson) { reader = new sp.spine.SkeletonJson(attachmentLoader); resData = this.skeletonJson; } else { reader = new sp.spine.SkeletonBinary(attachmentLoader); resData = new Uint8Array(this._nativeAsset); } reader.scale = this.scale; this._skeletonCache = reader.readSkeletonData(resData); atlas.dispose(); return this._skeletonCache; }, getSkinsEnum: false, getAnimsEnum: false, _getTexture: function _getTexture(line) { var names = this.textureNames; for (var i = 0; i < names.length; i++) if (names[i] === line) { var texture = this.textures[i]; var tex = new sp.SkeletonTexture({ width: texture.width, height: texture.height }); tex.setRealTexture(texture); return tex; } cc.errorID(7506, line); return null; }, _getAtlas: function _getAtlas(quiet) { if (this._atlasCache) return this._atlasCache; if (!this.atlasText) { quiet || cc.errorID(7508, this.name); return null; } return this._atlasCache = new sp.spine.TextureAtlas(this.atlasText, this._getTexture.bind(this)); }, clone: function clone() { var cloned = new SkeletonData(); SkeletonData.cloneId++; var suffix = "(clone " + String(SkeletonData.cloneId) + ")"; cloned._uuid = this._uuid.split("(")[0] + suffix; cloned.name = this.name + suffix; cloned.scale = this.scale; cloned._atlasText = this._atlasText; cloned.textureNames = this.textureNames; cloned._skeletonJson = this._skeletonJson; cloned.textures = this.textures; var realUuid; false; cloned._buffer = this._buffer; cloned.getRuntimeData(); return cloned; }, _destroyFromDynamicAtlas: function _destroyFromDynamicAtlas() { if (this._skeletonCache) { var skins = this._skeletonCache.skins; for (var _iterator = _createForOfIteratorHelperLoose(skins), _step; !(_step = _iterator()).done; ) { var skin = _step.value; for (var _iterator2 = _createForOfIteratorHelperLoose(skin.attachments), _step2; !(_step2 = _iterator2()).done; ) { var attachments = _step2.value; for (var key in attachments) { var region = attachments[key].region; if (region && region._spriteFrame) { var spriteFrame = region._spriteFrame; region._spriteFrame = null; spriteFrame.destroy(); } } } } } }, destroy: function destroy() { this._destroyFromDynamicAtlas(); SkeletonCache.removeSkeleton(this._uuid); this._super(); } }); sp.SkeletonData = module.exports = SkeletonData; sp.RegionData = RegionData; }), { "./skeleton-cache": 289 } ], 291: [ (function(require, module, exports) { "use strict"; sp.SkeletonTexture = cc.Class({ name: "sp.SkeletonTexture", extends: sp.spine.Texture, _texture: null, _material: null, setRealTexture: function setRealTexture(tex) { this._texture = tex; }, getRealTexture: function getRealTexture() { return this._texture; }, setFilters: function setFilters(minFilter, magFilter) { this._texture && this._texture.setFilters(minFilter, magFilter); }, setWraps: function setWraps(uWrap, vWrap) { this._texture && this._texture.setWrapMode(uWrap, vWrap); }, dispose: function dispose() {} }); }), {} ], 292: [ (function(require, module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var _assembler = _interopRequireDefault(require("../../cocos2d/core/renderer/assembler")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = "undefined" !== typeof Symbol && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && "number" === typeof o.length) { it && (o = it); var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if ("string" === typeof o) return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); "Object" === n && o.constructor && (n = o.constructor.name); if ("Map" === n || "Set" === n) return Array.from(o); if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { (null == len || len > arr.length) && (len = arr.length); for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Skeleton = require("./Skeleton"); var spine = require("./lib/spine"); var RenderFlow = require("../../cocos2d/core/renderer/render-flow"); var VertexFormat = require("../../cocos2d/core/renderer/webgl/vertex-format"); var VFOneColor = VertexFormat.vfmtPosUvColor; var VFOneColorTexId = VertexFormat.vfmtPosUvColorTexId; var VFTwoColor = VertexFormat.vfmtPosUvTwoColor; var VFTwoColorTexId = VertexFormat.vfmtPosUvTwoColorTexId; var gfx = cc.gfx; var FLAG_BATCH = 16; var FLAG_TWO_COLOR = 1; var _handleVal = 0; var _quadTriangles = [ 0, 1, 2, 2, 3, 0 ]; var _slotColor = cc.color(0, 0, 255, 255); var _boneColor = cc.color(255, 0, 0, 255); var _originColor = cc.color(0, 255, 0, 255); var _meshColor = cc.color(255, 255, 0, 255); var _finalColor = null; var _darkColor = null; var _tempPos = null, _tempUv = null; true; _finalColor = new spine.Color(1, 1, 1, 1); _darkColor = new spine.Color(1, 1, 1, 1); _tempPos = new spine.Vector2(); _tempUv = new spine.Vector2(); var _premultipliedAlpha; var _multiplier; var _slotRangeStart; var _slotRangeEnd; var _useTint; var _useMulti; var _texId; var _debugSlots; var _debugBones; var _debugMesh; var _nodeR, _nodeG, _nodeB, _nodeA; var _finalColor32, _darkColor32; var _vertexFormat; var _perVertexSize; var _perClipVertexSize; var _vertexFloatCount = 0, _vertexCount = 0, _vertexFloatOffset = 0, _vertexOffset = 0, _indexCount = 0, _indexOffset = 0, _vfOffset = 0; var _tempr, _tempg, _tempb; var _inRange; var _mustFlush; var _x, _y, _m00, _m04, _m12, _m01, _m05, _m13; var _r, _g, _b, _fr, _fg, _fb, _fa, _dr, _dg, _db, _da; var _comp, _buffer, _renderer, _node, _needColor, _vertexEffect; var _packedRegions = []; var _tmpRegionData = new sp.RegionData(); function _getSlotMaterial(tex, blendMode) { var src, dst; switch (blendMode) { case spine.BlendMode.Additive: src = _premultipliedAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; dst = cc.macro.ONE; break; case spine.BlendMode.Multiply: src = cc.macro.DST_COLOR; dst = cc.macro.ONE_MINUS_SRC_ALPHA; break; case spine.BlendMode.Screen: src = cc.macro.ONE; dst = cc.macro.ONE_MINUS_SRC_COLOR; break; case spine.BlendMode.Normal: default: src = _premultipliedAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; dst = cc.macro.ONE_MINUS_SRC_ALPHA; } var useModel = !_comp.enableBatch; var baseMaterial = _comp._materials[0]; if (!baseMaterial) return null; if (_useMulti) { var key = tex.getId() + src + dst + _useTint; var materialCache = _comp._materialCache; var materialInfo = materialCache[key]; if (!materialInfo) { var texId = baseMaterial.material.getMultiHandler().getIndex(tex.getImpl()); if (materialCache.baseMaterial) materialInfo = { material: cc.MaterialVariant.create(baseMaterial), texId: texId }; else { materialInfo = { material: baseMaterial, texId: texId }; materialCache.baseMaterial = materialInfo; } _comp._defineMaterialTint(baseMaterial, _useTint); if (-1 === texId) { materialInfo.material.setProperty("texture", tex); materialInfo.texId = 0; } materialInfo.material.setBlend(true, gfx.BLEND_FUNC_ADD, src, dst, gfx.BLEND_FUNC_ADD, src, dst); materialCache[key] = materialInfo; } _texId = materialInfo.texId; return materialInfo.material; } var _key = tex.getId() + src + dst + _useTint + useModel; var _materialCache = _comp._materialCache; var material = _materialCache[_key]; if (!material) { if (_materialCache.baseMaterial) material = cc.MaterialVariant.create(baseMaterial); else { material = baseMaterial; _materialCache.baseMaterial = baseMaterial; } material.define("CC_USE_MODEL", useModel); material.define("USE_TINT", _useTint); material.setProperty("texture", tex); material.setBlend(true, gfx.BLEND_FUNC_ADD, src, dst, gfx.BLEND_FUNC_ADD, src, dst); _materialCache[_key] = material; } return material; } function _handleColor(color) { _fa = color.fa * _nodeA; _multiplier = _premultipliedAlpha ? _fa / 255 : 1; _r = _nodeR * _multiplier; _g = _nodeG * _multiplier; _b = _nodeB * _multiplier; _fr = color.fr * _r; _fg = color.fg * _g; _fb = color.fb * _b; _finalColor32 = (_fa << 24 >>> 0) + (_fb << 16) + (_fg << 8) + _fr; _dr = color.dr * _r; _dg = color.dg * _g; _db = color.db * _b; _da = _premultipliedAlpha ? 255 : 0; _darkColor32 = (_da << 24 >>> 0) + (_db << 16) + (_dg << 8) + _dr; } function _spineColorToInt32(spineColor) { return (spineColor.a << 24 >>> 0) + (spineColor.b << 16) + (spineColor.g << 8) + spineColor.r; } var SpineAssembler = (function(_Assembler) { _inheritsLoose(SpineAssembler, _Assembler); function SpineAssembler() { return _Assembler.apply(this, arguments) || this; } var _proto = SpineAssembler.prototype; _proto.updateRenderData = function updateRenderData(comp) { if (comp.isAnimationCached()) return; this.handleDynamicAtlasAndSwitchMaterial(comp); var skeleton = comp._skeleton; skeleton && skeleton.updateWorldTransform(); }; _proto.handleDynamicAtlasAndSwitchMaterial = function handleDynamicAtlasAndSwitchMaterial(comp) { if (comp._dataDirty) { this.packDynamicAtlasForSpine(comp); var autoSwitchMaterial = comp.autoSwitchMaterial; if (cc.sp.autoSwitchMaterial && 0 === autoSwitchMaterial || 1 === autoSwitchMaterial) { var material = comp._materials[0]; if (!material) return false; var skins = comp.skeletonData._skeletonCache.skins; root: for (var _iterator = _createForOfIteratorHelperLoose(skins), _step; !(_step = _iterator()).done; ) { var skin = _step.value; for (var _iterator2 = _createForOfIteratorHelperLoose(skin.attachments), _step2; !(_step2 = _iterator2()).done; ) { var attachments = _step2.value; for (var key in attachments) { var attachment; var texture; false; var region = attachments[key].region; if (region && region.texture) { this.checkAndSwitchMaterial(comp, region.texture._texture, material); break root; } } } } } comp._dataDirty = false; } }; _proto.updatePackedAttachment = function updatePackedAttachment(attachment, strict) { _tmpRegionData.assignToAttachment(attachment, strict, false); var region = attachment.region; var frame = region._spriteFrame; region._original._ref++; frame.once("_resetDynamicAtlasFrame", (function() { _tmpRegionData.initWithAttachment(attachment); _tmpRegionData.x = region._original._x; _tmpRegionData.y = region._original._y; _tmpRegionData.texture = region._original._texture; false; region._original._ref--; region._original._ref <= 0 && (region._original = null); _tmpRegionData.assignToAttachment(attachment, true, false); _tmpRegionData.reset(); })); }; _proto.packDynamicAtlasForSpine = function packDynamicAtlasForSpine(comp) { false; _packedRegions.length = 0; var allowDynamicAtlas = comp.allowDynamicAtlas; if ((cc.sp.allowDynamicAtlas && 0 === allowDynamicAtlas || 1 === allowDynamicAtlas) && cc.dynamicAtlasManager) { var skins = comp.skeletonData._skeletonCache.skins; for (var _iterator3 = _createForOfIteratorHelperLoose(skins), _step3; !(_step3 = _iterator3()).done; ) { var skin = _step3.value; for (var _iterator4 = _createForOfIteratorHelperLoose(skin.attachments), _step4; !(_step4 = _iterator4()).done; ) { var attachments = _step4.value; for (var key in attachments) { var attachment = attachments[key]; if (attachment) { var texture; var spriteFrame; var frame; var packedFrame; false; var region = attachment.region; var alreadyInAtlas = !!region._original; if (alreadyInAtlas) _packedRegions.includes(region) && this.updatePackedAttachment(attachment, false); else if (region.texture && region.texture._texture.packable) { if (region._spriteFrame) { var _spriteFrame = region._spriteFrame; region._spriteFrame = null; _spriteFrame.destroy(); } _tmpRegionData.initWithAttachment(attachment); var _frame = _tmpRegionData.toSpriteFrame(); var _packedFrame = cc.dynamicAtlasManager.insertSpriteFrame(_frame); if (_packedFrame) { _frame._setDynamicAtlasFrame(_packedFrame); region._original = { _texture: region.texture, _x: region.x, _y: region.y, _ref: 0 }; region._spriteFrame = _frame; _tmpRegionData.updateWithPackedFrame(_packedFrame); this.updatePackedAttachment(attachment); _packedRegions.push(region); } else _frame.destroy(); } } } } } } _tmpRegionData.reset(); _packedRegions.length = 0; }; _proto.fillVertices = function fillVertices(skeletonColor, attachmentColor, slotColor, clipper, slot) { var vbuf = _buffer._vData, ibuf = _buffer._iData, uintVData = _buffer._uintVData; var offsetInfo; _finalColor.a = slotColor.a * attachmentColor.a * skeletonColor.a * _nodeA * 255; _multiplier = _premultipliedAlpha ? _finalColor.a : 255; _tempr = _nodeR * attachmentColor.r * skeletonColor.r * _multiplier; _tempg = _nodeG * attachmentColor.g * skeletonColor.g * _multiplier; _tempb = _nodeB * attachmentColor.b * skeletonColor.b * _multiplier; _finalColor.r = _tempr * slotColor.r; _finalColor.g = _tempg * slotColor.g; _finalColor.b = _tempb * slotColor.b; if (null == slot.darkColor) _darkColor.set(0, 0, 0, 1); else { _darkColor.r = slot.darkColor.r * _tempr; _darkColor.g = slot.darkColor.g * _tempg; _darkColor.b = slot.darkColor.b * _tempb; } _darkColor.a = _premultipliedAlpha ? 255 : 0; if (clipper.isClipping()) { var uvs = vbuf.subarray(_vertexFloatOffset + 2); clipper.clipTriangles(vbuf.subarray(_vertexFloatOffset), _vertexFloatCount, ibuf.subarray(_indexOffset), _indexCount, uvs, _finalColor, _darkColor, _useTint, _perVertexSize); var clippedVertices = new Float32Array(clipper.clippedVertices); var clippedTriangles = clipper.clippedTriangles; _indexCount = clippedTriangles.length; _vertexFloatCount = clippedVertices.length / _perClipVertexSize * _perVertexSize; offsetInfo = _buffer.requestForSpine(_vertexFloatCount / _perVertexSize, _indexCount); _indexOffset = offsetInfo.indiceOffset, _vertexOffset = offsetInfo.vertexOffset, _vertexFloatOffset = offsetInfo.byteOffset >> 2; vbuf = _buffer._vData, ibuf = _buffer._iData; uintVData = _buffer._uintVData; ibuf.set(clippedTriangles, _indexOffset); if (_vertexEffect) for (var _v2 = 0, _n2 = clippedVertices.length, offset = _vertexFloatOffset; _v2 < _n2; _v2 += _perClipVertexSize, offset += _perVertexSize) { _tempPos.x = clippedVertices[_v2]; _tempPos.y = clippedVertices[_v2 + 1]; _finalColor.set(clippedVertices[_v2 + 2], clippedVertices[_v2 + 3], clippedVertices[_v2 + 4], clippedVertices[_v2 + 5]); _tempUv.x = clippedVertices[_v2 + 6]; _tempUv.y = clippedVertices[_v2 + 7]; _useTint ? _darkColor.set(clippedVertices[_v2 + 8], clippedVertices[_v2 + 9], clippedVertices[_v2 + 10], clippedVertices[_v2 + 11]) : _darkColor.set(0, 0, 0, 0); _vertexEffect.transform(_tempPos, _tempUv, _finalColor, _darkColor); vbuf[offset] = _tempPos.x; vbuf[offset + 1] = _tempPos.y; vbuf[offset + 2] = _tempUv.x; vbuf[offset + 3] = _tempUv.y; uintVData[offset + 4] = _spineColorToInt32(_finalColor); if (_useTint) { uintVData[offset + 5] = _spineColorToInt32(_darkColor); _useMulti && (vbuf[offset + 6] = _texId); } else _useMulti && (vbuf[offset + 5] = _texId); } else for (var _v3 = 0, _n3 = clippedVertices.length, _offset = _vertexFloatOffset; _v3 < _n3; _v3 += _perClipVertexSize, _offset += _perVertexSize) { vbuf[_offset] = clippedVertices[_v3]; vbuf[_offset + 1] = clippedVertices[_v3 + 1]; vbuf[_offset + 2] = clippedVertices[_v3 + 6]; vbuf[_offset + 3] = clippedVertices[_v3 + 7]; _finalColor32 = (clippedVertices[_v3 + 5] << 24 >>> 0) + (clippedVertices[_v3 + 4] << 16) + (clippedVertices[_v3 + 3] << 8) + clippedVertices[_v3 + 2]; uintVData[_offset + 4] = _finalColor32; if (_useTint) { _darkColor32 = (clippedVertices[_v3 + 11] << 24 >>> 0) + (clippedVertices[_v3 + 10] << 16) + (clippedVertices[_v3 + 9] << 8) + clippedVertices[_v3 + 8]; uintVData[_offset + 5] = _darkColor32; _useMulti && (vbuf[_offset + 6] = _texId); } else _useMulti && (vbuf[_offset + 5] = _texId); } } else if (_vertexEffect) for (var v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) { _tempPos.x = vbuf[v]; _tempPos.y = vbuf[v + 1]; _tempUv.x = vbuf[v + 2]; _tempUv.y = vbuf[v + 3]; _vertexEffect.transform(_tempPos, _tempUv, _finalColor, _darkColor); vbuf[v] = _tempPos.x; vbuf[v + 1] = _tempPos.y; vbuf[v + 2] = _tempUv.x; vbuf[v + 3] = _tempUv.y; uintVData[v + 4] = _spineColorToInt32(_finalColor); if (_useTint) { uintVData[v + 5] = _spineColorToInt32(_darkColor); _useMulti && (vbuf[v + 6] = _texId); } else _useMulti && (vbuf[v + 5] = _texId); } else { _finalColor32 = _spineColorToInt32(_finalColor); _darkColor32 = _spineColorToInt32(_darkColor); for (var _v = _vertexFloatOffset, _n = _vertexFloatOffset + _vertexFloatCount; _v < _n; _v += _perVertexSize) { uintVData[_v + 4] = _finalColor32; if (_useTint) { uintVData[_v + 5] = _darkColor32; _useMulti && (vbuf[_v + 6] = _texId); } else _useMulti && (vbuf[_v + 5] = _texId); } } }; _proto.realTimeTraverse = function realTimeTraverse(worldMat) { var vbuf; var ibuf; var locSkeleton = _comp._skeleton; var skeletonColor = locSkeleton.color; var graphics = _comp._debugRenderer; var clipper = _comp._clipper; var material = null; var attachment, attachmentColor, slotColor, uvs, triangles; var isRegion, isMesh, isClip; var offsetInfo; var slot; var worldMatm; _slotRangeStart = _comp._startSlotIndex; _slotRangeEnd = _comp._endSlotIndex; _inRange = false; -1 == _slotRangeStart && (_inRange = true); _debugSlots = _comp.debugSlots; _debugBones = _comp.debugBones; _debugMesh = _comp.debugMesh; if (graphics && (_debugBones || _debugSlots || _debugMesh)) { graphics.clear(); graphics.lineWidth = 2; } _perClipVertexSize = _useTint ? _useMulti ? 16 : 12 : _useMulti ? 12 : 8; _vertexFloatCount = 0; _vertexFloatOffset = 0; _vertexOffset = 0; _indexCount = 0; _indexOffset = 0; for (var slotIdx = 0, slotCount = locSkeleton.drawOrder.length; slotIdx < slotCount; slotIdx++) { slot = locSkeleton.drawOrder[slotIdx]; if (void 0 == slot || !slot.bone.active) continue; _slotRangeStart >= 0 && _slotRangeStart == slot.data.index && (_inRange = true); if (!_inRange) { clipper.clipEndWithSlot(slot); continue; } _slotRangeEnd >= 0 && _slotRangeEnd == slot.data.index && (_inRange = false); _vertexFloatCount = 0; _indexCount = 0; attachment = slot.getAttachment(); if (!attachment) { clipper.clipEndWithSlot(slot); continue; } isRegion = attachment instanceof spine.RegionAttachment; isMesh = attachment instanceof spine.MeshAttachment; isClip = attachment instanceof spine.ClippingAttachment; if (isClip) { clipper.clipStart(slot, attachment); continue; } if (!isRegion && !isMesh) { clipper.clipEndWithSlot(slot); continue; } material = _getSlotMaterial(attachment.region.texture._texture, slot.data.blendMode); if (!material) { clipper.clipEndWithSlot(slot); continue; } if (_mustFlush || material.getHash() !== _renderer.material.getHash()) { _mustFlush = false; _renderer._flush(); _renderer.node = _node; _renderer.material = material; } if (isRegion) { triangles = _quadTriangles; _vertexFloatCount = 4 * _perVertexSize; _indexCount = 6; offsetInfo = _buffer.requestForSpine(4, 6); _indexOffset = offsetInfo.indiceOffset, _vertexOffset = offsetInfo.vertexOffset, _vertexFloatOffset = offsetInfo.byteOffset >> 2; vbuf = _buffer._vData, ibuf = _buffer._iData; attachment.computeWorldVertices(slot.bone, vbuf, _vertexFloatOffset, _perVertexSize); if (graphics && _debugSlots) { graphics.strokeColor = _slotColor; graphics.moveTo(vbuf[_vertexFloatOffset], vbuf[_vertexFloatOffset + 1]); for (var ii = _vertexFloatOffset + _perVertexSize, nn = _vertexFloatOffset + _vertexFloatCount; ii < nn; ii += _perVertexSize) graphics.lineTo(vbuf[ii], vbuf[ii + 1]); graphics.close(); graphics.stroke(); } } else if (isMesh) { triangles = attachment.triangles; _vertexFloatCount = (attachment.worldVerticesLength >> 1) * _perVertexSize; _indexCount = triangles.length; offsetInfo = _buffer.requestForSpine(_vertexFloatCount / _perVertexSize, _indexCount); _indexOffset = offsetInfo.indiceOffset, _vertexOffset = offsetInfo.vertexOffset, _vertexFloatOffset = offsetInfo.byteOffset >> 2; vbuf = _buffer._vData, ibuf = _buffer._iData; attachment.computeWorldVertices(slot, 0, attachment.worldVerticesLength, vbuf, _vertexFloatOffset, _perVertexSize); if (graphics && _debugMesh) { graphics.strokeColor = _meshColor; for (var _ii = 0, _nn = triangles.length; _ii < _nn; _ii += 3) { var v1 = triangles[_ii] * _perVertexSize + _vertexFloatOffset; var v2 = triangles[_ii + 1] * _perVertexSize + _vertexFloatOffset; var v3 = triangles[_ii + 2] * _perVertexSize + _vertexFloatOffset; graphics.moveTo(vbuf[v1], vbuf[v1 + 1]); graphics.lineTo(vbuf[v2], vbuf[v2 + 1]); graphics.lineTo(vbuf[v3], vbuf[v3 + 1]); graphics.close(); graphics.stroke(); } } } if (0 == _vertexFloatCount || 0 == _indexCount) { clipper.clipEndWithSlot(slot); continue; } ibuf.set(triangles, _indexOffset); uvs = attachment.uvs; for (var v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount, u = 0; v < n; v += _perVertexSize, u += 2) { vbuf[v + 2] = uvs[u]; vbuf[v + 3] = uvs[u + 1]; } attachmentColor = attachment.color, slotColor = slot.color; this.fillVertices(skeletonColor, attachmentColor, slotColor, clipper, slot); vbuf = _buffer._vData, ibuf = _buffer._iData; if (_indexCount > 0) { for (var _ii2 = _indexOffset, _nn2 = _indexOffset + _indexCount; _ii2 < _nn2; _ii2++) ibuf[_ii2] += _vertexOffset; if (worldMat) { worldMatm = worldMat.m; _m00 = worldMatm[0]; _m04 = worldMatm[4]; _m12 = worldMatm[12]; _m01 = worldMatm[1]; _m05 = worldMatm[5]; _m13 = worldMatm[13]; for (var _ii3 = _vertexFloatOffset, _nn3 = _vertexFloatOffset + _vertexFloatCount; _ii3 < _nn3; _ii3 += _perVertexSize) { _x = vbuf[_ii3]; _y = vbuf[_ii3 + 1]; vbuf[_ii3] = _x * _m00 + _y * _m04 + _m12; vbuf[_ii3 + 1] = _x * _m01 + _y * _m05 + _m13; } } _buffer.adjustForSpine(_vertexFloatCount / _perVertexSize, _indexCount); } clipper.clipEndWithSlot(slot); } clipper.clipEnd(); if (graphics && _debugBones) { var bone; graphics.strokeColor = _boneColor; graphics.fillColor = _slotColor; for (var i = 0, _n4 = locSkeleton.bones.length; i < _n4; i++) { bone = locSkeleton.bones[i]; var x = bone.data.length * bone.a + bone.worldX; var y = bone.data.length * bone.c + bone.worldY; graphics.moveTo(bone.worldX, bone.worldY); graphics.lineTo(x, y); graphics.stroke(); graphics.circle(bone.worldX, bone.worldY, 1.5 * Math.PI); graphics.fill(); 0 === i && (graphics.fillColor = _originColor); } } }; _proto.cacheVerticesConvertToMulti = function cacheVerticesConvertToMulti(vertices) { var verticesMulti = new Float32Array(vertices.length + vertices.length / 6); for (var i = 0, j = 0; j < vertices.length; ) { verticesMulti[i++] = vertices[j++]; verticesMulti[i++] = vertices[j++]; verticesMulti[i++] = vertices[j++]; verticesMulti[i++] = vertices[j++]; verticesMulti[i++] = vertices[j++]; verticesMulti[i++] = vertices[j++]; verticesMulti[i++] = 0; } return verticesMulti; }; _proto.cacheTraverse = function cacheTraverse(worldMat) { var frame = _comp._curFrame; if (!frame) return; var segments = frame.segments; if (0 == segments.length) return; var vbuf, ibuf, uintbuf; var material; var offsetInfo; var vertices = frame.vertices; var indices = frame.indices; var worldMatm; var useMultiTint = _useMulti && _useTint; if (useMultiTint) { frame.verticesMulti || (frame.verticesMulti = this.cacheVerticesConvertToMulti(frame.vertices)); vertices = frame.verticesMulti; } var frameVFOffset = 0, frameIndexOffset = 0, segVFCount = 0; if (worldMat) { worldMatm = worldMat.m; _m00 = worldMatm[0]; _m01 = worldMatm[1]; _m04 = worldMatm[4]; _m05 = worldMatm[5]; _m12 = worldMatm[12]; _m13 = worldMatm[13]; } var justTranslate = 1 === _m00 && 0 === _m01 && 0 === _m04 && 1 === _m05; var needBatch = _handleVal & FLAG_BATCH; var calcTranslate = needBatch && justTranslate; var colorOffset = 0; var colors = frame.colors; var nowColor = colors[colorOffset++]; var maxVFOffset = useMultiTint ? nowColor.vfOffset + nowColor.vfOffset / 6 : nowColor.vfOffset; _handleColor(nowColor); for (var i = 0, n = segments.length; i < n; i++) { var segInfo = segments[i]; material = _getSlotMaterial(segInfo.tex, segInfo.blendMode); if (!material) continue; if (_mustFlush || material.getHash() !== _renderer.material.getHash()) { _mustFlush = false; _renderer._flush(); _renderer.node = _node; _renderer.material = material; } _vertexCount = segInfo.vertexCount; _indexCount = segInfo.indexCount; offsetInfo = _buffer.requestForSpine(_vertexCount, _indexCount); _indexOffset = offsetInfo.indiceOffset; _vertexOffset = offsetInfo.vertexOffset; _vfOffset = offsetInfo.byteOffset >> 2; vbuf = _buffer._vData; ibuf = _buffer._iData; uintbuf = _buffer._uintVData; for (var ii = _indexOffset, il = _indexOffset + _indexCount; ii < il; ii++) ibuf[ii] = _vertexOffset + indices[frameIndexOffset++]; segVFCount = useMultiTint ? segInfo.vfCount + segInfo.vfCount / 6 : segInfo.vfCount; vbuf.set(vertices.subarray(frameVFOffset, frameVFOffset + segVFCount), _vfOffset); frameVFOffset += segVFCount; if (calcTranslate) for (var _ii4 = _vfOffset, _il = _vfOffset + segVFCount; _ii4 < _il; _ii4 += _perVertexSize) { vbuf[_ii4] += _m12; vbuf[_ii4 + 1] += _m13; } else if (needBatch) for (var _ii5 = _vfOffset, _il2 = _vfOffset + segVFCount; _ii5 < _il2; _ii5 += _perVertexSize) { _x = vbuf[_ii5]; _y = vbuf[_ii5 + 1]; vbuf[_ii5] = _x * _m00 + _y * _m04 + _m12; vbuf[_ii5 + 1] = _x * _m01 + _y * _m05 + _m13; } _buffer.adjustForSpine(_vertexCount, _indexCount); if (_useMulti) if (_useTint) if (_needColor) { var frameColorOffset = frameVFOffset - segVFCount; for (var _ii6 = _vfOffset + 4, _il3 = _vfOffset + 4 + segVFCount; _ii6 < _il3; _ii6 += _perVertexSize, frameColorOffset += _perVertexSize) { if (frameColorOffset >= maxVFOffset) { nowColor = colors[colorOffset++]; _handleColor(nowColor); maxVFOffset = useMultiTint ? nowColor.vfOffset + nowColor.vfOffset / 6 : nowColor.vfOffset; } uintbuf[_ii6] = _finalColor32; uintbuf[_ii6 + 1] = _darkColor32; vbuf[_ii6 + 2] = _texId; } } else for (var _ii7 = _vfOffset + 4, _il4 = _vfOffset + 4 + segVFCount; _ii7 < _il4; _ii7 += _perVertexSize) vbuf[_ii7 + 2] = _texId; else if (_needColor) { var _frameColorOffset = frameVFOffset - segVFCount; for (var _ii8 = _vfOffset + 4, _il5 = _vfOffset + 4 + segVFCount; _ii8 < _il5; _ii8 += _perVertexSize, _frameColorOffset += _perVertexSize) { if (_frameColorOffset >= maxVFOffset) { nowColor = colors[colorOffset++]; _handleColor(nowColor); maxVFOffset = useMultiTint ? nowColor.vfOffset + nowColor.vfOffset / 6 : nowColor.vfOffset; } uintbuf[_ii8] = _finalColor32; vbuf[_ii8 + 1] = _texId; } } else for (var _ii9 = _vfOffset + 4, _il6 = _vfOffset + 4 + segVFCount; _ii9 < _il6; _ii9 += _perVertexSize) vbuf[_ii9 + 1] = _texId; else if (_needColor) { var _frameColorOffset2 = frameVFOffset - segVFCount; for (var _ii10 = _vfOffset + 4, _il7 = _vfOffset + 4 + segVFCount; _ii10 < _il7; _ii10 += _perVertexSize, _frameColorOffset2 += _perVertexSize) { if (_frameColorOffset2 >= maxVFOffset) { nowColor = colors[colorOffset++]; _handleColor(nowColor); maxVFOffset = useMultiTint ? nowColor.vfOffset + nowColor.vfOffset / 6 : nowColor.vfOffset; } uintbuf[_ii10] = _finalColor32; uintbuf[_ii10 + 1] = _darkColor32; } } } }; _proto.fillBuffers = function fillBuffers(comp, renderer) { var node = comp.node; node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; if (!comp._skeleton) return; var nodeColor = node._color; _nodeR = nodeColor.r / 255; _nodeG = nodeColor.g / 255; _nodeB = nodeColor.b / 255; _nodeA = nodeColor.a / 255; var baseMaterial = comp._materials[0]; if (!baseMaterial) return; _useMulti = baseMaterial.material.isMultiSupport(); _useTint = comp.useTint; _vertexFormat = _useTint ? _useMulti ? VFTwoColorTexId : VFTwoColor : _useMulti ? VFOneColorTexId : comp.isAnimationCached() ? VFTwoColor : VFOneColor; _perVertexSize = _useTint ? _useMulti ? 7 : 6 : _useMulti ? 6 : comp.isAnimationCached() ? 6 : 5; _node = comp.node; _buffer = renderer.getBuffer("mesh", _vertexFormat); _renderer = renderer; _comp = comp; _mustFlush = true; _premultipliedAlpha = comp.premultipliedAlpha; _multiplier = 1; _handleVal = 0; _needColor = false; _vertexEffect = comp._effectDelegate && comp._effectDelegate._vertexEffect; (4294967295 !== nodeColor._val || _premultipliedAlpha) && (_needColor = true); _useTint && (_handleVal |= FLAG_TWO_COLOR); var worldMat = void 0; if (_comp.enableBatch) { worldMat = _node._worldMatrix; _mustFlush = false; _handleVal |= FLAG_BATCH; } if (comp.isAnimationCached()) this.cacheTraverse(worldMat); else { _vertexEffect && _vertexEffect.begin(comp._skeleton); this.realTimeTraverse(worldMat); _vertexEffect && _vertexEffect.end(); } renderer.worldMatDirty++; comp.attachUtil._syncAttachedNode(); _node = void 0; _buffer = void 0; _renderer = void 0; _comp = void 0; _vertexEffect = null; }; _proto.postFillBuffers = function postFillBuffers(comp, renderer) { renderer.worldMatDirty--; }; return SpineAssembler; })(_assembler["default"]); exports["default"] = SpineAssembler; _assembler["default"].register(Skeleton, SpineAssembler); module.exports = exports["default"]; }), { "../../cocos2d/core/renderer/assembler": 157, "../../cocos2d/core/renderer/render-flow": 161, "../../cocos2d/core/renderer/webgl/vertex-format": 202, "./Skeleton": 286, "./lib/spine": 288 } ], 293: [ (function(require, module, exports) { "use strict"; var TrackEntryListeners = function TrackEntryListeners() { this.start = null; this.end = null; this.complete = null; this.event = null; this.interrupt = null; this.dispose = null; }; TrackEntryListeners.getListeners = function(entry) { entry.listener || (entry.listener = new TrackEntryListeners()); return entry.listener; }; module.exports = TrackEntryListeners; }), {} ], 294: [ (function(require, module, exports) { "use strict"; var spine = require("./lib/spine"); sp.VertexEffectDelegate = cc.Class({ name: "sp.VertexEffectDelegate", ctor: function ctor() { this._vertexEffect = null; this._interpolation = null; this._effectType = "none"; }, clear: function clear() { this._vertexEffect = null; this._interpolation = null; this._effectType = "none"; }, initJitter: function initJitter(jitterX, jitterY) { this._effectType = "jitter"; this._vertexEffect = new spine.JitterEffect(jitterX, jitterY); return this._vertexEffect; }, initSwirlWithPow: function initSwirlWithPow(radius, power) { this._interpolation = new spine.Pow(power); this._vertexEffect = new spine.SwirlEffect(radius, this._interpolation); return this._vertexEffect; }, initSwirlWithPowOut: function initSwirlWithPowOut(radius, power) { this._interpolation = new spine.PowOut(power); this._vertexEffect = new spine.SwirlEffect(radius, this._interpolation); return this._vertexEffect; }, getJitterVertexEffect: function getJitterVertexEffect() { return this._vertexEffect; }, getSwirlVertexEffect: function getSwirlVertexEffect() { return this._vertexEffect; }, getVertexEffect: function getVertexEffect() { return this._vertexEffect; }, getEffectType: function getEffectType() { return this._effectType; } }); module.exports = sp.VertexEffectDelegate; }), { "./lib/spine": 288 } ], 295: [ (function(require, module, exports) { "use strict"; var _global = "undefined" === typeof window ? global : window; _global.cc = _global.cc || {}; cc.internal = cc.internal || {}; require("./predefine"); require("./polyfill/string"); require("./polyfill/misc"); require("./polyfill/array"); require("./polyfill/object"); require("./polyfill/array-buffer"); require("./polyfill/number"); true; require("./polyfill/typescript"); require("./cocos2d/core/predefine"); true; require("./cocos2d"); require("./extends"); false; module.exports = _global.cc; }), { "./cocos2d": 245, "./cocos2d/core/predefine": 154, "./extends": 284, "./package": void 0, "./polyfill/array": 297, "./polyfill/array-buffer": 296, "./polyfill/misc": 298, "./polyfill/number": 299, "./polyfill/object": 300, "./polyfill/string": 301, "./polyfill/typescript": 302, "./predefine": 303 } ], 296: [ (function(require, module, exports) { "use strict"; if (!ArrayBuffer.isView) { var TypedArray = Object.getPrototypeOf(Int8Array); ArrayBuffer.isView = "function" === typeof TypedArray ? function(obj) { return obj instanceof TypedArray; } : function(obj) { if ("object" !== typeof obj) return false; var ctor = obj.constructor; return ctor === Float64Array || ctor === Float32Array || ctor === Uint8Array || ctor === Uint32Array || ctor === Int8Array; }; } }), {} ], 297: [ (function(require, module, exports) { "use strict"; Array.isArray || (Array.isArray = function(arg) { return "[object Array]" === Object.prototype.toString.call(arg); }); Array.prototype.find || (Array.prototype.find = function(callback) { var length = this.length; for (var i = 0; i < length; i++) { var element = this[i]; if (callback.call(this, element, i, this)) return element; } return; }); Array.prototype.includes || (Array.prototype.includes = function(value) { return -1 !== this.indexOf(value); }); }), {} ], 298: [ (function(require, module, exports) { "use strict"; Math.sign || (Math.sign = function(x) { x = +x; if (0 === x || isNaN(x)) return x; return x > 0 ? 1 : -1; }); Math.log2 || (Math.log2 = function(x) { return Math.log(x) * Math.LOG2E; }); Number.isInteger || (Number.isInteger = function(value) { return "number" === typeof value && isFinite(value) && Math.floor(value) === value; }); if ((false, false) || !console.time) { var Timer = window.performance || Date; var _timerTable = Object.create(null); console.time = function(label) { _timerTable[label] = Timer.now(); }; console.timeEnd = function(label) { var startTime = _timerTable[label]; var duration = Timer.now() - startTime; console.log(label + ": " + duration + "ms"); }; } }), {} ], 299: [ (function(require, module, exports) { "use strict"; Number.parseFloat = Number.parseFloat || parseFloat; Number.parseInt = Number.parseInt || parseInt; }), {} ], 300: [ (function(require, module, exports) { "use strict"; Object.assign || (Object.assign = function(target, source) { return cc.js.mixin(target, source); }); Object.getOwnPropertyDescriptors || (Object.getOwnPropertyDescriptors = function(obj) { var descriptors = {}; var ownKeys = Object.getOwnPropertyNames(obj); Object.getOwnPropertySymbols && (ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(obj))); for (var i = 0; i < ownKeys.length; ++i) { var key = ownKeys[i]; descriptors[key] = Object.getOwnPropertyDescriptor(obj, key); } return descriptors; }); }), {} ], 301: [ (function(require, module, exports) { "use strict"; String.prototype.startsWith || (String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.lastIndexOf(searchString, position) === position; }); String.prototype.endsWith || (String.prototype.endsWith = function(searchString, position) { ("undefined" === typeof position || position > this.length) && (position = this.length); position -= searchString.length; var lastIndex = this.indexOf(searchString, position); return -1 !== lastIndex && lastIndex === position; }); String.prototype.trimLeft || (String.prototype.trimLeft = function() { return this.replace(/^\s+/, ""); }); }), {} ], 302: [ (function(require, module, exports) { "use strict"; var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) { d.__proto__ = b; } || function(d, b) { for (var p in b) b.hasOwnProperty(p) && (d[p] = b[p]); }; window.__extends = function(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __()); }; window.__assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]); } return t; }; window.__rest = function(s, e) { var t = {}; for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0 && (t[p] = s[p]); if (null != s && "function" === typeof Object.getOwnPropertySymbols) for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]) && (t[p[i]] = s[p[i]]); return t; }; window.__decorate = function(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ("object" === typeof Reflect && "function" === typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) (d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r); return c > 3 && r && Object.defineProperty(target, key, r), r; }; window.__param = function(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; }; window.__metadata = function(metadataKey, metadataValue) { if ("object" === typeof Reflect && "function" === typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue); }; window.__awaiter = function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; window.__generator = function(thisArg, body) { var _ = { label: 0, sent: function sent() { if (1 & t[0]) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), throw: verb(1), return: verb(2) }, "function" === typeof Symbol && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([ n, v ]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = 2 & op[0] ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; (y = 0, t) && (op = [ 2 & op[0], t.value ]); switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [ 0 ]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (6 === op[0] || 2 === op[0])) { _ = 0; continue; } if (3 === op[0] && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (6 === op[0] && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } t[2] && _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [ 6, e ]; y = 0; } finally { f = t = 0; } if (5 & op[0]) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; window.__exportStar = function(m, o) { for (var p in m) "default" === p || Object.prototype.hasOwnProperty.call(o, p) || __createBinding(o, m, p); }; window.__createBinding = Object.create ? function(o, m, k, k2) { void 0 === k2 && (k2 = k); Object.defineProperty(o, k2, { enumerable: true, get: function get() { return m[k]; } }); } : function(o, m, k, k2) { void 0 === k2 && (k2 = k); o[k2] = m[k]; }; window.__values = function(o) { var s = "function" === typeof Symbol && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && "number" === typeof o.length) return { next: function next() { o && i >= o.length && (o = void 0); return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; window.__read = function(o, n) { var m = "function" === typeof Symbol && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((void 0 === n || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { r && !r.done && (m = i["return"]) && m.call(i); } finally { if (e) throw e.error; } } return ar; }; window.__spread = function() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; window.__spreadArrays = function() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; window.__await = function(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; window.__asyncGenerator = function(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { g[n] && (i[n] = function(v) { return new Promise(function(a, b) { q.push([ n, v, a, b ]) > 1 || resume(n, v); }); }); } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { (f(v), q.shift(), q.length) && resume(q[0][0], q[0][1]); } }; window.__asyncDelegator = function(o) { var i, p; return i = {}, verb("next"), verb("throw", (function(e) { throw e; })), verb("return"), i[Symbol.iterator] = function() { return this; }, i; function verb(n, f) { i[n] = o[n] ? function(v) { return (p = !p) ? { value: __await(o[n](v)), done: "return" === n } : f ? f(v) : v; } : f; } }; window.__asyncValues = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = "function" === typeof __values ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then((function(v) { resolve({ value: v, done: d }); }), reject); } }; window.__makeTemplateObject = function(cooked, raw) { Object.defineProperty ? Object.defineProperty(cooked, "raw", { value: raw }) : cooked.raw = raw; return cooked; }; var __setModuleDefault = Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }; window.__importStar = function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (null != mod) for (var k in mod) "default" !== k && Object.prototype.hasOwnProperty.call(mod, k) && __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; window.__importDefault = function(mod) { return mod && mod.__esModule ? mod : { default: mod }; }; window.__classPrivateFieldGet = function(receiver, privateMap) { if (!privateMap.has(receiver)) throw new TypeError("attempted to get private field on non-instance"); return privateMap.get(receiver); }; window.__classPrivateFieldSet = function(receiver, privateMap, value) { if (!privateMap.has(receiver)) throw new TypeError("attempted to set private field on non-instance"); privateMap.set(receiver, value); return value; }; }), {} ], 303: [ (function(require, module, exports) { "use strict"; var _global = "undefined" === typeof window ? global : window; function defineMacro(name, defaultValue) { "undefined" === typeof _global[name] && (_global[name] = defaultValue); } function defineDeprecatedMacroGetter(name, defaultValue) { "undefined" === typeof _global[name] && Object.defineProperty(_global, name, { get: function get() { var recommandedUsage; "CC_WECHATGAMESUB" === name ? recommandedUsage = "cc.sys.platform === cc.sys.WECHAT_GAME_SUB" : "CC_WECHATGAME" === name ? recommandedUsage = "cc.sys.platform === cc.sys.WECHAT_GAME" : "CC_QQPLAY" === name && (recommandedUsage = "cc.sys.platform === cc.sys.QQ_PLAY"); cc.warnID(1400, name, recommandedUsage); return defaultValue; } }); } function defined(name) { return "object" === typeof _global[name]; } defineMacro("CC_BUILD", false); true; _global.CC_BUILD = true; _global.CC_DEV = false; _global.CC_DEBUG = true; _global.CC_JSB = false; _global.CC_NATIVERENDERER = false; _global.CC_SUPPORT_JIT = true; _global.CC_PHYSICS_BUILTIN = false; _global.CC_PHYSICS_CANNON = false; _global.CC_EDITOR = false; _global.CC_PREVIEW = false; _global.CC_TEST = false; _global.CC_RUNTIME = false; _global.CC_JSB = false; var WECHATGAMESUB = !!(defined("wx") && wx.getSharedCanvas); var WECHATGAME = !!(defined("wx") && (wx.getSystemInfoSync || wx.getSharedCanvas)); var QQPLAY = defined("bk"); defineDeprecatedMacroGetter("CC_WECHATGAMESUB", WECHATGAMESUB); defineDeprecatedMacroGetter("CC_WECHATGAME", WECHATGAME); defineDeprecatedMacroGetter("CC_QQPLAY", QQPLAY); false; var engineVersion = "2.4.9"; _global["CocosEngine"] = cc.ENGINE_VERSION = engineVersion; }), {} ] }, {}, [ 295 ]); //# sourceMappingURL=cocos2d-js.js.map